问:
How to don't overwrite the MySql column if the front end file field is empty
I'm using the below controller exports.update to upload data and files on my CRUD app. I'm having a big issue, and I please need help/advice.

On the client side if the upload file field e.g. covid_19D remains empty but other values are filled and a post request is submitted, the file empty field overwrites the covid_19D MySql database column, deleting previous entered filename and leaving the covid_19D MySql column value empty.

How I can go around this? If a post request is submitted on the client-side and the file field is empty, to not overwrite the previous loaded filename on the MySql column?

Here is my front-end:
crew-forms.hbs

      {{!-- covid-19 vaccination --}}

        <input class="form-control" type="text" placeholder="COVID-19 VACCINATION CERTIFICATES" aria-label="readonly input example" readonly data-bs-trigger="focus" role="button" data-bs-toggle="popover" title="Covid-19 vaccination certificate.">

        <input type="text" id="datepickercovid_19" value="{{this.covid_19}}" placeholder="iss. date (mm/dd/yyyy)" name='covid_19'>

      {{!-- input file covid_19 --}}

        <input type="file" name="covid_19D" multiple id="file_box" value="{{this.covid_19D}}" />```
</div>
</div>
</p>
<p>and edit-crew.hbs</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{{#each rows}}
<form class="row g-1 needs-validation" method="POST" action="/editcrew/{{this.id}}" encType="multipart/form-data" novalidate>
  {{> crew-form}}
</form>
{{/each}}</code>```

here is userController.js

exports.update = async(req, res) => {

  try {
    await upload(req, res);

    // --FILE HANDLING BLOCKCODE---

    var find = JSON.parse(JSON.stringify(req.files)); //  to remove Object:null prototype
    // conditional statments to hanlde the front end file existence.

    if (find.hasOwnProperty('covid_19D') == false) {
      var covid_19D = ""
    } else {
      var covid_19D = find.covid_19D[0].filename

    }

    if (find.hasOwnProperty('fitnessD') == false) {
      var fitnessD = ""
    } else {
      var fitnessD = find.fitnessD[0].filename
    }

  } catch (error) {
    console.log(error);

    if (error.code === "LIMIT_UNEXPECTED_FILE") {

      return res.send("Too many files to upload.");
    }
    // return res.send(`Error when trying upload many files: ${error}`);
  }

  // ---DATA ENTERING BLOCK CODE---

  var post = req.body;
  var first_name = post.first_name;
  var last_name = post.last_name;
  var email = post.email;
  var phone = post.phone;
  var coc = post.coc;
  var expiration = post.expiration;
  var covid_19 = post.covid_19;
  var fitness = post.fitness;
  var yellowF = post.yellowF;

  connection.query('UPDATE user SET first_name=? ,last_name=?, email=?, phone=?, coc=?, expiration=?, covid_19=?,covid_19D=? , fitness=? ,fitnessD=?  WHERE id = ?', [first_name, last_name, email, phone, coc, expiration, covid_19, covid_19D, fitness, fitnessD, req.params.id],
    (err, rows) => {

      if (!err) {
        connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) => {
          if (!err) {
            res.render('edit-crew', {
              rows,
              alert: `${first_name} has been updated.`
            });

          } else {
            console.log(err);
          }
          // console.log('The data from user table:\n', rows);
        });
      } else {
        console.log(err);
      }
      // console.log('The data from user table:\n', rows);
    });

}```
</div>
</div>
</p>
<p>And here is my <code>app.js</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require("express");
const exphbs = require("express-handlebars");
const path = require('path');
bodyParser = require("body-parser");
// to be removed when deployed in heroku

require("dotenv").config();
const cookieParser = require('cookie-parser');

// Parsing middleware
const app = express();

//to load static file
app.use(express.static("public"));
// app.use(express.static("upload"));
//Listen on port 5000
app.use(express.urlencoded({
  extended: true
})); //To parse URL-encoded bodies (as sent by HTML forms) set from false to true as per bezkoder tutorial

app.use(express.json()); //To parse the incoming requests with JSON bodies
app.use(cookieParser());

app.engine("hbs", exphbs({
  extname: ".hbs"
})); //Templating engine to change the extenion of file from .handlebar to .hbs
app.set("view engine", "hbs");

app.use("/", require('./routes/user'));
app.use('/auth', require('./routes/auth'));

app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));</code>```

Thanks in advance for any suggestion redirection on the correct path!

答:
Ok I got it!

I simply recall the stored filename from the database on the front end, and used req.body.covid_19D to post the name of the variable.

here the code snippet:

 try {
        await upload(req, res);
        // --FILE HANDLING BLOCKCODE---
        var find = JSON.parse(JSON.stringify(req.files));//  to remove Object:null prototype
        // conditional statments to hanlde the front end file existence.
        if (find.hasOwnProperty('covid_19D') == false) {
            var covid_19D = req.body.covid_19D
        } else {
            var covid_19D = find.covid_19D[0].filename

        }```

Body:
I'm using the below controller exports.update to upload data and files on my CRUD app. I'm having a big issue, and I please need help/advice.

On the client side if the upload file field e.g. covid_19D remains empty but other values are filled and a post request is submitted, the file empty field overwrites the covid_19D MySql database column, deleting previous entered filename and leaving the covid_19D MySql column value empty.

How I can go around this? If a post request is submitted on the client-side and the file field is empty, to not overwrite the previous loaded filename on the MySql column?

Here is my front-end:
crew-forms.hbs

      {{!-- covid-19 vaccination --}}

        <input class="form-control" type="text" placeholder="COVID-19 VACCINATION CERTIFICATES" aria-label="readonly input example" readonly data-bs-trigger="focus" role="button" data-bs-toggle="popover" title="Covid-19 vaccination certificate.">

        <input type="text" id="datepickercovid_19" value="{{this.covid_19}}" placeholder="iss. date (mm/dd/yyyy)" name='covid_19'>

      {{!-- input file covid_19 --}}

        <input type="file" name="covid_19D" multiple id="file_box" value="{{this.covid_19D}}" />

and edit-crew.hbs

{{#each rows}}
<form class="row g-1 needs-validation" method="POST" action="/editcrew/{{this.id}}" encType="multipart/form-data" novalidate>
  {{> crew-form}}
</form>
{{/each}}

here is userController.js

exports.update = async(req, res) => {

  try {
    await upload(req, res);

    // --FILE HANDLING BLOCKCODE---

    var find = JSON.parse(JSON.stringify(req.files)); //  to remove Object:null prototype
    // conditional statments to hanlde the front end file existence.

    if (find.hasOwnProperty('covid_19D') == false) {
      var covid_19D = ""
    } else {
      var covid_19D = find.covid_19D[0].filename

    }

    if (find.hasOwnProperty('fitnessD') == false) {
      var fitnessD = ""
    } else {
      var fitnessD = find.fitnessD[0].filename
    }

  } catch (error) {
    console.log(error);

    if (error.code === "LIMIT_UNEXPECTED_FILE") {

      return res.send("Too many files to upload.");
    }
    // return res.send(`Error when trying upload many files: ${error}`);
  }

  // ---DATA ENTERING BLOCK CODE---

  var post = req.body;
  var first_name = post.first_name;
  var last_name = post.last_name;
  var email = post.email;
  var phone = post.phone;
  var coc = post.coc;
  var expiration = post.expiration;
  var covid_19 = post.covid_19;
  var fitness = post.fitness;
  var yellowF = post.yellowF;

  connection.query('UPDATE user SET first_name=? ,last_name=?, email=?, phone=?, coc=?, expiration=?, covid_19=?,covid_19D=? , fitness=? ,fitnessD=?  WHERE id = ?', [first_name, last_name, email, phone, coc, expiration, covid_19, covid_19D, fitness, fitnessD, req.params.id],
    (err, rows) => {

      if (!err) {
        connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) => {
          if (!err) {
            res.render('edit-crew', {
              rows,
              alert: `${first_name} has been updated.`
            });

          } else {
            console.log(err);
          }
          // console.log('The data from user table:\n', rows);
        });
      } else {
        console.log(err);
      }
      // console.log('The data from user table:\n', rows);
    });

}

And here is my app.js

const express = require("express");
const exphbs = require("express-handlebars");
const path = require('path');
bodyParser = require("body-parser");
// to be removed when deployed in heroku

require("dotenv").config();
const cookieParser = require('cookie-parser');

// Parsing middleware
const app = express();

//to load static file
app.use(express.static("public"));
// app.use(express.static("upload"));
//Listen on port 5000
app.use(express.urlencoded({
  extended: true
})); //To parse URL-encoded bodies (as sent by HTML forms) set from false to true as per bezkoder tutorial

app.use(express.json()); //To parse the incoming requests with JSON bodies
app.use(cookieParser());

app.engine("hbs", exphbs({
  extname: ".hbs"
})); //Templating engine to change the extenion of file from .handlebar to .hbs
app.set("view engine", "hbs");

app.use("/", require('./routes/user'));
app.use('/auth', require('./routes/auth'));

app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));

Thanks in advance for any suggestion redirection on the correct path!


来源: stackexchange

问:
Get ids from HTML and put it inside JavaScript array

I need the array in javascript to pull the ids that were selected in the interface and when I click Install it runs a bat behind it that installs everything at once, but I'm not getting it... What I have ready is this:

function install() {
    const form = document.getElementById('install');
    form.addEventListener('submit', (event) => {
        event.preventDefault()
    });
}
function mostrar(){
    var allTags = [];
    var ids = document.body.getElementsByTagName('input');
    for (var i = 0; i< ids.length; i++) {
        allTags.push(ids[i].id);
    }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></head>
  <body>
    <div class="quiz-container" id="quiz" multiple>
      <div class="quiz-header">
        <h2 id="question">select the programs you wanted to install: </h2>
        <form action="/signup" method="post" id="install">
          <ul>
            <li>
              <input type="checkbox" name="1" id="a" class="answer" />
              <label for="a" id="a_text">Teams</label>
            </li>
            <li>
              <input type="checkbox" name="2" id="b" class="answer" />
              <label for="b" id="b_text">VPN</label>
            </li>
            <li>
              <input type="checkbox" name="3" id="c" class="answer" />
              <label for="c" id="c_text">FDC</label>
            </li>
            <li>
              <input type="checkbox" name="4" id="d" class="answer" />
              <label for="d" id="d_text">Acrobat Reader</label>
            </li>
            <li>
              <input type="checkbox" name="5" id="e" class="answer" />
              <label for="e" id="d_text">Power BI</label>
            </li>
          </ul>
        </form>
      </div>
      <button id="submit">Install</button>
    </div>
  </body></code>```

答:
To get IDs of checked input you need to loop to the all input and check with .checked attribute.

document.querySelector('#getIDs').addEventListener('click', function(){
  var allTags = [];
  document.querySelectorAll('input').forEach(function(input){
    if(input.checked){
      allTags.push(input.id)
    }
  })
  console.log('IDs:', allTags)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code></head>
  <body>
    <div class="quiz-container" id="quiz" multiple>
      <div class="quiz-header">
        <h2 id="question">select the programs you wanted to install: </h2>
        <form action="/signup" method="post" id="install">
          <ul>
            <li>
              <input type="checkbox" name="1" id="a" class="answer" />
              <label for="a" id="a_text">Teams</label>
            </li>
            <li>
              <input type="checkbox" name="2" id="b" class="answer" />
              <label for="b" id="b_text">VPN</label>
            </li>
            <li>
              <input type="checkbox" name="3" id="c" class="answer" />
              <label for="c" id="c_text">FDC</label>
            </li>
            <li>
              <input type="checkbox" name="4" id="d" class="answer" />
              <label for="d" id="d_text">Acrobat Reader</label>
            </li>
            <li>
              <input type="checkbox" name="5" id="e" class="answer" />
              <label for="e" id="d_text">Power BI</label>
            </li>
          </ul>
        </form>
      </div>
      <button id="getIDs">getIDs</button>
    </div>
  </body></code>```

ContentLicense: CC BY-SA 4.0

Body:
I need the array in javascript to pull the ids that were selected in the interface and when I click Install it runs a bat behind it that installs everything at once, but I'm not getting it... What I have ready is this:

function install() {
    const form = document.getElementById('install');
    form.addEventListener('submit', (event) => {
        event.preventDefault()
    });
}
function mostrar(){
    var allTags = [];
    var ids = document.body.getElementsByTagName('input');
    for (var i = 0; i< ids.length; i++) {
        allTags.push(ids[i].id);
    }

}

select the programs you wanted to install:

        <form action="/signup" method="post" id="install">

              <input type="checkbox" name="1" id="a" class="answer" />
              Teams

              <input type="checkbox" name="2" id="b" class="answer" />
              VPN

              <input type="checkbox" name="3" id="c" class="answer" />
              FDC

              <input type="checkbox" name="4" id="d" class="answer" />
              Acrobat Reader

              <input type="checkbox" name="5" id="e" class="answer" />
              Power BI

        </form>

      <button id="submit">Install</button>

Body:
To get IDs of checked input you need to loop to the all input and check with .checked attribute.

document.querySelector('#getIDs').addEventListener('click', function(){
  var allTags = [];
  document.querySelectorAll('input').forEach(function(input){
    if(input.checked){
      allTags.push(input.id)
    }
  })
  console.log('IDs:', allTags)
})

</head>
  <body>
    <div class="quiz-container" id="quiz" multiple>
      <div class="quiz-header">
        <h2 id="question">select the programs you wanted to install: </h2>
        <form action="/signup" method="post" id="install">
          <ul>
            <li>
              <input type="checkbox" name="1" id="a" class="answer" />
              <label for="a" id="a_text">Teams</label>
            </li>
            <li>
              <input type="checkbox" name="2" id="b" class="answer" />
              <label for="b" id="b_text">VPN</label>
            </li>
            <li>
              <input type="checkbox" name="3" id="c" class="answer" />
              <label for="c" id="c_text">FDC</label>
            </li>
            <li>
              <input type="checkbox" name="4" id="d" class="answer" />
              <label for="d" id="d_text">Acrobat Reader</label>
            </li>
            <li>
              <input type="checkbox" name="5" id="e" class="answer" />
              <label for="e" id="d_text">Power BI</label>
            </li>
          </ul>
        </form>
      </div>
      <button id="getIDs">getIDs</button>
    </div>
  </body>


问:
PHP parse_ini_file problems
I have a config.ini file that looks like this:

```<code>[database]
username = user1
password = pass1
dbname = db1
</code>```

And I want to parse it in PHP, but I'm having no luck.  The code I'm trying is:

```<code>$inifile = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . "/cfi/config.ini", true);
var_dump($inifile);
</code>```

The PHP is part of an include, thats why I tried adding $_SERVER['DOCUMENT_ROOT'] to make sure it was finding the config file.

The result of the var_dump is always bool(false).

What am I doing wrong?

EDIT:

I have added the / and it now definitely points to the config file.  But there is still a result of bool(false)

答: My problem was that I has a variable no. Changing variable name solved my problem.

ContentLicense: CC BY-SA 3.0

Title: PHP parse_ini_file problems

Body:
I have a config.ini file that looks like this:

[database]
username = user1
password = pass1
dbname = db1

And I want to parse it in PHP, but I'm having no luck.  The code I'm trying is:

$inifile = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . "/cfi/config.ini", true);
var_dump($inifile);

The PHP is part of an include, thats why I tried adding $_SERVER['DOCUMENT_ROOT'] to make sure it was finding the config file.

The result of the var_dump is always bool(false).

What am I doing wrong?

EDIT:

I have added the / and it now definitely points to the config file.  But there is still a result of bool(false)


问:
I'm having problems with Tab Navigator Key
I'm having problems when I try to render a TabBar

"Warning: Each child in a list should have a unique "key" prop.
Check the render method of MyTabBar. See https://reactjs.org/link/warning-keys for more information."

My code:

```<code>import React from "react";
import { Cores } from "../../Theme/";
import { View, TouchableOpacity, StyleSheet } from "react-native";

import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
const Tab = createBottomTabNavigator();

import Pratique from "../../Screens/Pratique";
import Home from "../../Screens/Home";
import Perfil from "../../Screens/Perfil";

import HomeIcon from "../../Assets/Barra/Inicio.svg";
import PratiqueIcon from "../../Assets/Barra/Exercicios.svg";
import PerfilIcon from "../../Assets/Barra/Perfil.svg";

function MyTabBar({ state, descriptors, navigation }) {
  return (
    <View style={styles.container}>
      {state.routes.map((route, index) => {
        const { options } = descriptors[route.key];
        const label =
          options.tabBarLabel !== undefined
            ? options.tabBarLabel
            : options.title !== undefined
            ? options.title
            : route.name;

        const isFocused = state.index === index;
        var Icon;
        switch (route.name) {
          case "Home":
            Icon = HomeIcon;
            break;
          case "Perfil":
            Icon = PerfilIcon;
            break;
          case "Pratique":
            Icon = PratiqueIcon;
            break;

          default:
            Icon = HomeIcon;
            break;
        }

        const onPress = () => {
          const event = navigation.emit({
            type: "tabPress",
            target: route.key,
          });

          if (!isFocused && !event.defaultPrevented) {
            navigation.navigate(route.name);
          }
        };

        const onLongPress = () => {
          navigation.emit({
            type: "tabLongPress",
            target: route.key,
          });
        };

        return (
          <TouchableOpacity
            accessibilityRole="button"
            accessibilityState={isFocused ? { selected: true } : {}}
            accessibilityLabel={options.tabBarAccessibilityLabel}
            testID={options.tabBarTestID}
            onPress={onPress}
            onLongPress={onLongPress}
            style={styles.touchable}
          >
            <Icon
              style={{ color: isFocused ? Cores.azulNavegar : Cores.cinza }}
            />
            <View
              style={{
                position: "absolute",
                bottom: 0,
                height: 4,
                width: "100%",
                backgroundColor: isFocused ? Cores.azulNavegar : null,
              }}
            ></View>
          </TouchableOpacity>
        );
      })}
    </View>
  );
}

export default function TabBar() {
  return (
    <Tab.Navigator
      initialRouteName="Home"
      screenOptions={{
        headerShown: false,
        statusBarHidden: true,
      }}
      tabBar={(props) => <MyTabBar {...props} />}
    >
      <Tab.Screen name="Pratique" component={Pratique} />
      <Tab.Screen name="Home" component={Home} />
      <Tab.Screen name="Perfil" component={Perfil} />
    </Tab.Navigator>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    justifyContent: "space-around",
    alignItems: "center",
    width: "100%",
    backgroundColor: Cores.branco,
  },

  touchable: {
    flex: 1,
    paddingVertical: 20,
    justifyContent: "center",
    alignItems: "center",
  },
});
</code>```

答:
everytime you use "map" or any other loop to return Component, you have to add "key" prop to wrap component ( top )

...
{state.routes.map((route, index) => {
...
return (
          <TouchableOpacity
            key={index.toString()}
            accessibilityRole="button"
            accessibilityState={isFocused ? { selected: true } : {}}
            accessibilityLabel={options.tabBarAccessibilityLabel}
            testID={options.tabBarTestID}
            onPress={onPress}
            onLongPress={onLongPress}
            style={styles.touchable}
          >
...
```
<p>just add this to your return part when you have map :)</p>
<pre class="lang-js prettyprint-override"><code>key={index.toString()}
</code>```

Body:
I'm having problems when I try to render a TabBar

"Warning: Each child in a list should have a unique "key" prop.
Check the render method of MyTabBar. See https://reactjs.org/link/warning-keys for more information."

My code:

import React from "react";
import { Cores } from "../../Theme/";
import { View, TouchableOpacity, StyleSheet } from "react-native";

import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
const Tab = createBottomTabNavigator();

import Pratique from "../../Screens/Pratique";
import Home from "../../Screens/Home";
import Perfil from "../../Screens/Perfil";

import HomeIcon from "../../Assets/Barra/Inicio.svg";
import PratiqueIcon from "../../Assets/Barra/Exercicios.svg";
import PerfilIcon from "../../Assets/Barra/Perfil.svg";

function MyTabBar({ state, descriptors, navigation }) {
  return (
    <View style={styles.container}>
      {state.routes.map((route, index) => {
        const { options } = descriptors[route.key];
        const label =
          options.tabBarLabel !== undefined
            ? options.tabBarLabel
            : options.title !== undefined
            ? options.title
            : route.name;

        const isFocused = state.index === index;
        var Icon;
        switch (route.name) {
          case "Home":
            Icon = HomeIcon;
            break;
          case "Perfil":
            Icon = PerfilIcon;
            break;
          case "Pratique":
            Icon = PratiqueIcon;
            break;

          default:
            Icon = HomeIcon;
            break;
        }

        const onPress = () => {
          const event = navigation.emit({
            type: "tabPress",
            target: route.key,
          });

          if (!isFocused && !event.defaultPrevented) {
            navigation.navigate(route.name);
          }
        };

        const onLongPress = () => {
          navigation.emit({
            type: "tabLongPress",
            target: route.key,
          });
        };

        return (
          <TouchableOpacity
            accessibilityRole="button"
            accessibilityState={isFocused ? { selected: true } : {}}
            accessibilityLabel={options.tabBarAccessibilityLabel}
            testID={options.tabBarTestID}
            onPress={onPress}
            onLongPress={onLongPress}
            style={styles.touchable}
          >
            <Icon
              style={{ color: isFocused ? Cores.azulNavegar : Cores.cinza }}
            />
            <View
              style={{
                position: "absolute",
                bottom: 0,
                height: 4,
                width: "100%",
                backgroundColor: isFocused ? Cores.azulNavegar : null,
              }}
            ></View>
          </TouchableOpacity>
        );
      })}
    </View>
  );
}

export default function TabBar() {
  return (
    <Tab.Navigator
      initialRouteName="Home"
      screenOptions={{
        headerShown: false,
        statusBarHidden: true,
      }}
      tabBar={(props) => <MyTabBar {...props} />}
    >
      <Tab.Screen name="Pratique" component={Pratique} />
      <Tab.Screen name="Home" component={Home} />
      <Tab.Screen name="Perfil" component={Perfil} />
    </Tab.Navigator>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    justifyContent: "space-around",
    alignItems: "center",
    width: "100%",
    backgroundColor: Cores.branco,
  },

  touchable: {
    flex: 1,
    paddingVertical: 20,
    justifyContent: "center",
    alignItems: "center",
  },
});

Body:
everytime you use "map" or any other loop to return Component, you have to add "key" prop to wrap component ( top )

...
{state.routes.map((route, index) => {
...
return (
          <TouchableOpacity
            key={index.toString()}
            accessibilityRole="button"
            accessibilityState={isFocused ? { selected: true } : {}}
            accessibilityLabel={options.tabBarAccessibilityLabel}
            testID={options.tabBarTestID}
            onPress={onPress}
            onLongPress={onLongPress}
            style={styles.touchable}
          >
...

just add this to your return part when you have map :)

key={index.toString()}


问:
use gpsd or cgps to return latitude and longitude then quit
I would like a dead-simple way to query my gps location from a usb dongle from the unix command line.

Right now, I know I've got a functioning software and hardware system, as evidenced by the success of the cgps command in showing me my position. I'd now like to be able to make short requests for my gps location (lat,long in decimals) from the command line. my usb serial's path is /dev/ttyUSB0 and I'm using a Global Sat dongle that outputs generic NMEA sentences

How might I accomplish this?

Thanks

答:
Putting a few of the bits of different answers together with a bit more jq work, I like this version:

```<code>$ gpspipe -w -n 10 | grep -m 1 TPV | jq -r '[.lat, .lon] | @csv'
40.xxxxxx054,-79.yyyyyy367
</code>```

Explanation:

(1) use grep -m 1 after invoking gpspipe, as used by @eadmaster's answer, because the grep will exit as soon as the first match is found. This gets you results faster instead of having to wait for 10 lines (or using two invocations of gpspipe).

(2) use jq to extract both fields simultaneously; the @csv formatter is more readable. Note the use of jq -r (raw output), so that the output is not put in quotes. Otherwise the output would be "40.xxxx,-79.xxxx" - which might be fine or better for some applications.

(3) Search for the TPV field by name for clarity. This is the "time, position, velocity" record, which is the one we want for extracting the current lat & lon. Just searching for "lat" or "lon" risks getting confused by the GST object that some GPSes may supply, and in that object, 'lat' and 'lon' are the standard deviation of the position error, not the position itself.

Body:
Putting a few of the bits of different answers together with a bit more jq work, I like this version:

$ gpspipe -w -n 10 | grep -m 1 TPV | jq -r '[.lat, .lon] | @csv'
40.xxxxxx054,-79.yyyyyy367

Explanation:

(1) use grep -m 1 after invoking gpspipe, as used by @eadmaster's answer, because the grep will exit as soon as the first match is found. This gets you results faster instead of having to wait for 10 lines (or using two invocations of gpspipe).

(2) use jq to extract both fields simultaneously; the @csv formatter is more readable. Note the use of jq -r (raw output), so that the output is not put in quotes. Otherwise the output would be "40.xxxx,-79.xxxx" - which might be fine or better for some applications.

(3) Search for the TPV field by name for clarity. This is the "time, position, velocity" record, which is the one we want for extracting the current lat & lon. Just searching for "lat" or "lon" risks getting confused by the GST object that some GPSes may supply, and in that object, 'lat' and 'lon' are the standard deviation of the position error, not the position itself.


问:
calculate into new column as percentage
Very new and learning SQL. Trying to calculate a percentage from two columns as such:

```<code>Select (total_deaths/total_cases)*100 AS death_percentage
From covid_deaths
</code>```

I’m getting the column but it’s showing as an Integer and all values are zero.

I’ve tried using CAST to make it a decimal but i don’t have the syntax right. Very noob question but seems simple enough. Do I have to declare the numeric type of all calculated columns?

答:
In addition to the answer linked by Stefan Zivkovik in a comment above, it may be good to handle division by zero.  Even if you don't ever anticipate total_cases will be zero, someone may reuse this part of the code (for instance, if total_cases is later broken into subcategories).

You probably also want to ROUND to a certain number of decimal places

```<code>SELECT
  CASE WHEN total_cases > 0 THEN
    ROUND((total_deaths::NUMERIC/total_cases)*100,1)
  END AS death_percentage
FROM covid_deaths
</code>```

By not specifying an ELSE clause, the column will be null when total_cases is zero.  If this doesn't work for your purposes, you could specify another default value (like zero) with ELSE.

Title: calculate into new column as percentage

Body:
Very new and learning SQL. Trying to calculate a percentage from two columns as such:

Select (total_deaths/total_cases)*100 AS death_percentage
From covid_deaths

I’m getting the column but it’s showing as an Integer and all values are zero.

I’ve tried using CAST to make it a decimal but i don’t have the syntax right. Very noob question but seems simple enough. Do I have to declare the numeric type of all calculated columns?

Body:
In addition to the answer linked by Stefan Zivkovik in a comment above, it may be good to handle division by zero.  Even if you don't ever anticipate total_cases will be zero, someone may reuse this part of the code (for instance, if total_cases is later broken into subcategories).

You probably also want to ROUND to a certain number of decimal places

SELECT
  CASE WHEN total_cases > 0 THEN
    ROUND((total_deaths::NUMERIC/total_cases)*100,1)
  END AS death_percentage
FROM covid_deaths

By not specifying an ELSE clause, the column will be null when total_cases is zero.  If this doesn't work for your purposes, you could specify another default value (like zero) with ELSE.


问:
Rrule UNTIL in the past but still returning a value
I am using google-rfc2445 library (com.google.ical) to parse RRULE.

In the test below the rrule UNTIL is set in the past (year 1999) and the dtStart is set as now. I am expecting 0 result but somehow getting 1 result which seems like the dtStart. I am dumbfounded why it is including an item out of the UNTIL bound. Is that the expected behavior?

```<code>@Test
    public void testRruleExpiryInPast1() {
        String rruleString = "RRULE:FREQ=DAILY;INTERVAL=1;UNTIL=19990103T000000Z";
        DateTime startDate = DateTime.now(DateTimeZone.UTC);
        System.out.println("startDate timeZone =" + startDate.getZone());
        try {
            DateTimeIterable localDateIterable = DateTimeIteratorFactory.createDateTimeIterable(rruleString, startDate, startDate.getZone(), false);
            DateTimeIterator iterator = localDateIterable.iterator();
            while (iterator.hasNext()) {
                DateTime next = iterator.next();
                System.out.println(next);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

</code>```

The above test Outputs

```<code>startDate timeZone =UTC
2022-02-06T18:52:31.000Z
</code>```

Update1:
according to this answer, ICAL in google calendar has extra event , it seem like the DTSTART will always be the first occurrence regardless of UNTIL being in the past or not. I find this strange. Now I have resorted to regex parsing the rrule string to determine whether there is UNTIL or not and if there is whether it is in the past.  :(

答:
Your use case is a little bit of a logical corner case.

Technically the RFC2245 in the section section-4.3.10 says:

The "DTSTART" property value, if specified, counts as the first occurrence.

The underlying logic being that the first instance is specified by DTSTART and that subsequent instances should be derived from the RRULE.

In your case since you are specifying UNTIL before DTSTART we are to the best of my knowledge in a grey area where the RFC does not specify how the RRULE instances should be generated.

I suspect that the Google library is sticking to the letter of the RFC and pre-pending DTSART to the list of instances without checking if it before the date specified by UNTIL since RFC does not mention this.

Body:
I am using google-rfc2445 library (com.google.ical) to parse RRULE.

In the test below the rrule UNTIL is set in the past (year 1999) and the dtStart is set as now. I am expecting 0 result but somehow getting 1 result which seems like the dtStart. I am dumbfounded why it is including an item out of the UNTIL bound. Is that the expected behavior?

@Test
    public void testRruleExpiryInPast1() {
        String rruleString = "RRULE:FREQ=DAILY;INTERVAL=1;UNTIL=19990103T000000Z";
        DateTime startDate = DateTime.now(DateTimeZone.UTC);
        System.out.println("startDate timeZone =" + startDate.getZone());
        try {
            DateTimeIterable localDateIterable = DateTimeIteratorFactory.createDateTimeIterable(rruleString, startDate, startDate.getZone(), false);
            DateTimeIterator iterator = localDateIterable.iterator();
            while (iterator.hasNext()) {
                DateTime next = iterator.next();
                System.out.println(next);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

The above test Outputs

startDate timeZone =UTC
2022-02-06T18:52:31.000Z

Update1:
according to this answer, ICAL in google calendar has extra event , it seem like the DTSTART will always be the first occurrence regardless of UNTIL being in the past or not. I find this strange. Now I have resorted to regex parsing the rrule string to determine whether there is UNTIL or not and if there is whether it is in the past.  :(


问:
PHP function to make slug (URL string)
I want to have a function to create slugs from Unicode strings, e.g. gen_slug('Andrés Cortez') should return andres-cortez. How should I do that?

答:
For standard alphanumeric english - nothing complicated.</p>
```<code>/**
 * Update the provided string to a slug-safe format.
 *
 * @param string $string
 * @return string
 */
function slugify($string)
{
    return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
}
</code>```

Title: PHP function to make slug (URL string)

Body:
For standard alphanumeric english - nothing complicated.

/**
 * Update the provided string to a slug-safe format.
 *
 * @param string $string
 * @return string
 */
function slugify($string)
{
    return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
}


问:
I am wanting to run a function in script apps that automatically looks for a word in a column and automatically archives that row to another tab
I want to automatically have a row archive to another tab if column D contains the word Deprovisioned. I am not manually editing the cell, I am copy and pasting from a CSV export so the columns come pre-filled with information. I tried the below script, but received an error saying undefined. I am not sure if this has something to do with the fact that I am not manually editing anything on the sheet?

Below is the error I get

```<code>    var s = event.source.getActiveSheet();  undefined.
</code>```

Below is the script I am using

```<code>    function onEDIT(event) {
    // assumes source data in sheet named Needed
    // target sheet of move to named Acquired
    // test column with yes/no is col 4 or D
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = event.source.getActiveSheet();
    var r = event.source.getActiveRange();
    if(s.getName() == "Copy of Zoominfo Usage" && r.getColumn() == 4 &&
    r.getValue() == "DEPROVISIONED") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("ZOOMINFO ARCHIVE");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
    }
    }

</code>```

答:
```<code>function onEdit(e) {
  const sh = e.range.getSheet();
  if (sh.getName() == "Copy of Zoominfo Usage" && e.range.columnStart == 4 && e.value == "DEPROVISIONED") {
    let tsh = e.source.getSheetByName("ZOOMINFO ARCHIVE");
    let tgt = tsh.getRange(tsh.getLastRow() + 1, 1);
    sh.getRange(e.range.rowStart, 1, 1, sh.getLastColumn()).moveTo(tgt);
    sh.deleteRow(e.range.rowStart);
  }
}
</code>```

Body:
I want to automatically have a row archive to another tab if column D contains the word Deprovisioned. I am not manually editing the cell, I am copy and pasting from a CSV export so the columns come pre-filled with information. I tried the below script, but received an error saying undefined. I am not sure if this has something to do with the fact that I am not manually editing anything on the sheet?

Below is the error I get

    var s = event.source.getActiveSheet();  undefined.

Below is the script I am using

    function onEDIT(event) {
    // assumes source data in sheet named Needed
    // target sheet of move to named Acquired
    // test column with yes/no is col 4 or D
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = event.source.getActiveSheet();
    var r = event.source.getActiveRange();
    if(s.getName() == "Copy of Zoominfo Usage" && r.getColumn() == 4 &&
    r.getValue() == "DEPROVISIONED") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("ZOOMINFO ARCHIVE");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
    }
    }


问:
NullReferenceException when recording with NAudio (in c#)
I am trying to record voice using NAudio in C# and I am stuck at two places:

1. A crash:

With a slightly modified form of code from THIS SO page, I am getting a NullReferenceException. Here is the crash log:

```<code>************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
   at NAudio.Wave.WaveIn.Callback(IntPtr waveInHandle, WaveMessage message, IntPtr userData, WaveHeader waveHeader, IntPtr reserved)
   at NAudio.Wave.WaveWindow.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code>```

and the code is:

```<code>using System;
using System.Windows.Forms;
using System.Threading;
using NAudio.Wave;

public class FOO
{
    static WaveIn s_WaveIn;

    [STAThread]
    static void Main(string[] args)
    {
        init();
        Application.Run();
    }

    public static void record()
    {
    while (true)
    {
        Console.WriteLine("Hit Enter to START Recording.\n");
        Console.ReadLine();

        s_WaveIn.StartRecording();

        Console.WriteLine("Hit Enter to STOP recording.\n");
        Console.ReadLine();

        s_WaveIn.StopRecording();
    }
    }

    public static void DeviceInit(int rate, int channels)
    {
    s_WaveIn = new WaveIn();
    s_WaveIn.WaveFormat = new WaveFormat(rate, channels);

    s_WaveIn.BufferMilliseconds = 1000;
    s_WaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(SendCaptureSamples);
    }

    public static void init()
    {
    DeviceInit(44100, 2);

    Thread t1 = new Thread(delegate() {
        record();
        });
    t1.Start();
    }

    static void SendCaptureSamples(object sender, WaveInEventArgs e)
    {
    Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded);
    }
}
</code>```

Most of the times, this happens when I start recording THIRD time. Any idea what could be causing this?

*2. Modifying rate and channels at runtime.*

In my actual code, I am resetting wave format using s_WaveIn.WaveFormat = new WaveFormat(new_rate, new_channels); before calling StartRecording(). I am not calling Dispose() because that would require resetting the DataAvailable callback, and for that, I would need another message loop. Is this approach correct or should I first call Dispose and then reinitialize s_WaveIn with new format?

Thank you.

答:
Your Main method looks odd. What is the thread for?

Just use this:

```<code>[STAThread]
static void Main(string[] args)
{
    init();
    Application.Run();
}
</code>```

Your init method also runs the application. Why?

Try changing it to:

```<code>public static void init()
{
    DeviceInit(44100, 2);

    Thread t1 = new Thread(delegate() {
        record();
    });
    t1.Start();
}
</code>```

return; is not needed at the end of a method returning void.

Body:
I am trying to record voice using NAudio in C# and I am stuck at two places:

1. A crash:

With a slightly modified form of code from THIS SO page, I am getting a NullReferenceException. Here is the crash log:

************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
   at NAudio.Wave.WaveIn.Callback(IntPtr waveInHandle, WaveMessage message, IntPtr userData, WaveHeader waveHeader, IntPtr reserved)
   at NAudio.Wave.WaveWindow.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

and the code is:

using System;
using System.Windows.Forms;
using System.Threading;
using NAudio.Wave;

public class FOO
{
    static WaveIn s_WaveIn;

    [STAThread]
    static void Main(string[] args)
    {
        init();
        Application.Run();
    }

    public static void record()
    {
    while (true)
    {
        Console.WriteLine("Hit Enter to START Recording.\n");
        Console.ReadLine();

        s_WaveIn.StartRecording();

        Console.WriteLine("Hit Enter to STOP recording.\n");
        Console.ReadLine();

        s_WaveIn.StopRecording();
    }
    }

    public static void DeviceInit(int rate, int channels)
    {
    s_WaveIn = new WaveIn();
    s_WaveIn.WaveFormat = new WaveFormat(rate, channels);

    s_WaveIn.BufferMilliseconds = 1000;
    s_WaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(SendCaptureSamples);
    }

    public static void init()
    {
    DeviceInit(44100, 2);

    Thread t1 = new Thread(delegate() {
        record();
        });
    t1.Start();
    }

    static void SendCaptureSamples(object sender, WaveInEventArgs e)
    {
    Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded);
    }
}

Most of the times, this happens when I start recording THIRD time. Any idea what could be causing this?

*2. Modifying rate and channels at runtime.*

In my actual code, I am resetting wave format using s_WaveIn.WaveFormat = new WaveFormat(new_rate, new_channels); before calling StartRecording(). I am not calling Dispose() because that would require resetting the DataAvailable callback, and for that, I would need another message loop. Is this approach correct or should I first call Dispose and then reinitialize s_WaveIn with new format?

Thank you.

Body:
Your Main method looks odd. What is the thread for?

Just use this:

[STAThread]
static void Main(string[] args)
{
    init();
    Application.Run();
}

Your init method also runs the application. Why?

Try changing it to:

public static void init()
{
    DeviceInit(44100, 2);

    Thread t1 = new Thread(delegate() {
        record();
    });
    t1.Start();
}

return; is not needed at the end of a method returning void.


问:
Why different packet loss rate result in the same result in Omnet?
In my simulation, I'm trying to use traCI to control vehicle type and traCI is invoked by receiving a beacon message sent by RSU. In addition, I add packet lost probability, as code shown below:

```<code>void MyVeinsAppCar::handleLowerMsg(cMessage* msg) {
    if( uniform(0,1) < 0.8)
    {
        EV << "\"Losing\" message " << msg << endl;
        delete msg;
    }
    else
    {
        TraCIMobility* mobility = TraCIMobilityAccess().get(getParentModule());
        TraCICommandInterface* traci = mobility->getCommandInterface();
        TraCICommandInterface::Vehicle* traciVehicle = mobility->getVehicleCommandInterface();
        if (traciVehicle->getRouteId().substr(0,4)=="!FR.")
            {
                traciVehicle->setTypeId("vtype1");
            }
        else if (traciVehicle->getRouteId().substr(0,4)=="!RF.")
            {
                traciVehicle->setTypeId("vtype0");
            }
}
</code>```

In this case, the vehicle type in sumo is initially set as default and traCI is used to change their vehicle type. When I run this simulation by setting different packet lost probability, the simulation gui will show different effects(different types of vehicles will show different colors), but the output speed are exactly the same. But my purpose is to study the influence of vehicle types on vehicle speed under different permeability.
And when I run sumo alone, I set different proportions of vehicle types in sumo's route file, the output speed will be different. The following code is where I manually set vType0 and vType1 to 50%.

```<code><routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/routes_file.xsd">
    <vType id="vtype0" laneChangeModel="LC2013" lcStrategic="150" lcKeepRight="50"/>
    <vType id="vtype1" laneChangeModel="LC2013"  lcStrategic="1000" lcKeepRight="100"/>

    <flow id="FR" begin="0.00" departLane="random" from="gneE0" to="gneE4" end="3600.00" vehsPerHour="270"/>
    <flow id="FR_C" type="vtype1" begin="0.00" departLane="random" color="magenta" from="gneE0" to="gneE4" end="3600.00" vehsPerHour="270"/>

    <flow id="RF" begin="0.00" departLane="random"  from="gneE3" to="gneE2" end="3600.00" vehsPerHour="624"/>
    <flow id="RF_C" type="vtype0" begin="0.00" departLane="random" color="red" from="gneE3" to="gneE2" end="3600.00" vehsPerHour="624"/>

</routes>
</code>```

So why is this happening? Do I need to adjust any parameters in Omnet? Thank you in advance!

答: You can specify different values for  accel and decel properties of a vehicle inside vType tag. For more information check sample route file in veins project. More details can be found on eclipse sumo website.</p>

Body:
In my simulation, I'm trying to use traCI to control vehicle type and traCI is invoked by receiving a beacon message sent by RSU. In addition, I add packet lost probability, as code shown below:

void MyVeinsAppCar::handleLowerMsg(cMessage* msg) {
    if( uniform(0,1) < 0.8)
    {
        EV << "\"Losing\" message " << msg << endl;
        delete msg;
    }
    else
    {
        TraCIMobility* mobility = TraCIMobilityAccess().get(getParentModule());
        TraCICommandInterface* traci = mobility->getCommandInterface();
        TraCICommandInterface::Vehicle* traciVehicle = mobility->getVehicleCommandInterface();
        if (traciVehicle->getRouteId().substr(0,4)=="!FR.")
            {
                traciVehicle->setTypeId("vtype1");
            }
        else if (traciVehicle->getRouteId().substr(0,4)=="!RF.")
            {
                traciVehicle->setTypeId("vtype0");
            }
}

In this case, the vehicle type in sumo is initially set as default and traCI is used to change their vehicle type. When I run this simulation by setting different packet lost probability, the simulation gui will show different effects(different types of vehicles will show different colors), but the output speed are exactly the same. But my purpose is to study the influence of vehicle types on vehicle speed under different permeability.
And when I run sumo alone, I set different proportions of vehicle types in sumo's route file, the output speed will be different. The following code is where I manually set vType0 and vType1 to 50%.

<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/routes_file.xsd">
    <vType id="vtype0" laneChangeModel="LC2013" lcStrategic="150" lcKeepRight="50"/>
    <vType id="vtype1" laneChangeModel="LC2013"  lcStrategic="1000" lcKeepRight="100"/>

    <flow id="FR" begin="0.00" departLane="random" from="gneE0" to="gneE4" end="3600.00" vehsPerHour="270"/>
    <flow id="FR_C" type="vtype1" begin="0.00" departLane="random" color="magenta" from="gneE0" to="gneE4" end="3600.00" vehsPerHour="270"/>

    <flow id="RF" begin="0.00" departLane="random"  from="gneE3" to="gneE2" end="3600.00" vehsPerHour="624"/>
    <flow id="RF_C" type="vtype0" begin="0.00" departLane="random" color="red" from="gneE3" to="gneE2" end="3600.00" vehsPerHour="624"/>

</routes>

So why is this happening? Do I need to adjust any parameters in Omnet? Thank you in advance!


问:
Introducing a second y axis into a relplot() call with multiple plots

The Problem

I have 2 dataframes which I combine and then melt with pandas.  I need to multi-plot them (as below) and the code needs to be scalable.  They consist of 2 variables which form the 'key' column below ('x' and 'y' here), across multiple 'stations' (just 2 here, but needs to be scalable).  I've used relplot() to be able to multi-plot the two variables on each graph, and different stations on separate graphs.

Is there any way to maintain this format but introduce a 2nd y axis to each plot?  'x' and 'y' need to be on different scales in my actual data.  I've seen examples where the relplot call is stored with y = 1st variable, and a 2nd lineplot call is added for the 2nd variable with ax.twinx() included in it.  So in example below, 'x' and 'y' would each have a y axis on the same graph.

How would I make that work with a melted dataframe (e.g. below) where 'key' = 2 variables and 'station' can be length n?  Or is the answer to scrap that df format and start again?

Example Code

The multi-plot as it stands:

```<code>import numpy as np
np.random.seed(123)
date_range = pd.period_range('1981-01-01','1981-01-04',freq='D')
x = np.random.randint(1, 10, (4,2))
y = np.random.randint(1, 10, (4,2))
x = pd.DataFrame(x, index = date_range, columns = ['station1','station2'])
y = pd.DataFrame(y, index = date_range + pd.to_timedelta(1, unit="D"), columns = ['station1','station2'])

#keep information where each data point comes from
x["key"], y["key"] = "x", "y"
#moving index into a column
x = x.reset_index()
y = y.reset_index()
#and changing it to datetime values that seaborn can understand
#necessary because pd.Period data is used
x["index"] = pd.to_datetime(x["index"].astype(str))
y["index"] = pd.to_datetime(y["index"].astype(str))

#combining dataframes and reshaping
df = pd.concat([x, y]).melt(["index", "key"], var_name="station", value_name="station_value")

#plotting
fg = sns.relplot(data=df, x = "index", y = "station_value", kind = "line", hue = "key", row = "station")

#shouldn't be necessary but this example had too many ticks for the interval
from matplotlib.dates import DateFormatter, DayLocator
fg.axes[0,0].xaxis.set_major_locator(DayLocator(interval=1))
fg.axes[0,0].xaxis.set_major_formatter(DateFormatter("%y-%m-%d"))

plt.show()
</code>```

答:
Not what you asked for, but you could make a grid of relplots with different y-axes without changing your df shape

```<code>fg = sns.relplot(
    data=df,
    x = "index",
    y = "station_value",
    kind = "line",
    col = "key",
    row = "station",
    facet_kws={'sharey': False, 'sharex': True},
)
</code>```

Body:
The Problem

I have 2 dataframes which I combine and then melt with pandas.  I need to multi-plot them (as below) and the code needs to be scalable.  They consist of 2 variables which form the 'key' column below ('x' and 'y' here), across multiple 'stations' (just 2 here, but needs to be scalable).  I've used relplot() to be able to multi-plot the two variables on each graph, and different stations on separate graphs.

Is there any way to maintain this format but introduce a 2nd y axis to each plot?  'x' and 'y' need to be on different scales in my actual data.  I've seen examples where the relplot call is stored with y = 1st variable, and a 2nd lineplot call is added for the 2nd variable with ax.twinx() included in it.  So in example below, 'x' and 'y' would each have a y axis on the same graph.

How would I make that work with a melted dataframe (e.g. below) where 'key' = 2 variables and 'station' can be length n?  Or is the answer to scrap that df format and start again?

Example Code

The multi-plot as it stands:

import numpy as np
np.random.seed(123)
date_range = pd.period_range('1981-01-01','1981-01-04',freq='D')
x = np.random.randint(1, 10, (4,2))
y = np.random.randint(1, 10, (4,2))
x = pd.DataFrame(x, index = date_range, columns = ['station1','station2'])
y = pd.DataFrame(y, index = date_range + pd.to_timedelta(1, unit="D"), columns = ['station1','station2'])

#keep information where each data point comes from
x["key"], y["key"] = "x", "y"
#moving index into a column
x = x.reset_index()
y = y.reset_index()
#and changing it to datetime values that seaborn can understand
#necessary because pd.Period data is used
x["index"] = pd.to_datetime(x["index"].astype(str))
y["index"] = pd.to_datetime(y["index"].astype(str))

#combining dataframes and reshaping
df = pd.concat([x, y]).melt(["index", "key"], var_name="station", value_name="station_value")

#plotting
fg = sns.relplot(data=df, x = "index", y = "station_value", kind = "line", hue = "key", row = "station")

#shouldn't be necessary but this example had too many ticks for the interval
from matplotlib.dates import DateFormatter, DayLocator
fg.axes[0,0].xaxis.set_major_locator(DayLocator(interval=1))
fg.axes[0,0].xaxis.set_major_formatter(DateFormatter("%y-%m-%d"))

plt.show()

Body:
Not what you asked for, but you could make a grid of relplots with different y-axes without changing your df shape

fg = sns.relplot(
    data=df,
    x = "index",
    y = "station_value",
    kind = "line",
    col = "key",
    row = "station",
    facet_kws={'sharey': False, 'sharex': True},
)


问:
How to approach the k-Processor Scheduling Problem?
So, I have a question. Suppose there are k processors and k*n Jobs. Now, each processor ought to do exactly n jobs, and every processor takes a particular amount of time to do a particular job. As shown below, here the column Time k refers to the time taken by processor k to do different jobs.

The task is to find the minimum time with which we can do all the jobs. Now, for k=2, I found that a greedy approach works. We can just calculate the T2-T1 for each job. This is the net loss of time if we execute the tasks in processor 2. Thus, we can then sort this in non-decreasing order and allocate the first n jobs to processor 2 and rest processor 1. I am not able to extend the solution further for higher values of k. Is there a general algorithm for this?
I would appreciate it if anyone can point to any papers for this, or guide me about the general direction. I need a exact solution though, but close enough solutions work too.

Edit: The machines run one after the another and not simultaneously. Thus, the completion time is not the minimum of time taken by all the machines, rather than it's the sum of their times.

答:
First, for k = 2 a simple greedy approach does NOT work.  To see that, just consider the special case where the cost of the job is the same in both processors.  This special case is the Partition Problem which is well-known to be NP-complete.  If 2 < k this becomes Multiway number partitioning.

The problem that you describe is known as Unrelated-machines scheduling.  The standard polynomial time approximation is from Approximation algorithms for scheduling unrelated parallel machines which gives a result that is off from optimal by no more than a factor of 2.


问:
java.net.http does not exist error on JDK11
Its a command line program. Was trying to send a POST call using java.net.http module but I keep getting the following error.

```<code>java: package java.net.http does not exist
</code>```
```<code>C:\Users\dell>java -version
java version "11.0.10" 2021-01-19 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.10+8-LTS-162)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.10+8-LTS-162, mixed mode)
</code>```

Intellij project SDK - java version 11.0.10

Code -

```<code>import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.serphouse.com/serp/live"))
                .POST(HttpRequest.BodyPublishers.ofString(content))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer xZWmYW3fJ0L0juYQrZ6br3etoNhF1iGVhwrWxRlwbhGWflzDeOR0tEPAiJQqJFxc")
                .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
</code>```

答:
I got it fixed by following the IDE suggestion which was to convert the language level to 11 and it added following plugin in pom.xml</p>
```<code>    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

Body:
Its a command line program. Was trying to send a POST call using java.net.http module but I keep getting the following error.

java: package java.net.http does not exist

C:\Users\dell>java -version
java version "11.0.10" 2021-01-19 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.10+8-LTS-162)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.10+8-LTS-162, mixed mode)

Intellij project SDK - java version 11.0.10

Code -

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.serphouse.com/serp/live"))
                .POST(HttpRequest.BodyPublishers.ofString(content))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer xZWmYW3fJ0L0juYQrZ6br3etoNhF1iGVhwrWxRlwbhGWflzDeOR0tEPAiJQqJFxc")
                .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

Body:
I got it fixed by following the IDE suggestion which was to convert the language level to 11 and it added following plugin in pom.xml

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


问:
How to use managed identity to connect to Azure Notification Hub?
In the docs they give an example of how to connect to a hub by using a connection string that contains a Shared Access Signature. So far in my app, I've been able to avoid storing secrets myself by just using managed identities. Is there a way to connect to a Notification Hub with a managed identity instead of a secret? I'd rather not do my own secret management.</p>

答: Authorization Rules (a.k.a. Access Policies) are associated with a hub and can be accessed using Azure Resource Manager calls, which I believe supports managed identity. I've thought about this but haven't tried it myself. So please report back if it works for you.</p>


问:
How to mock a response from an Angular service in a unit test
I have an Angular service that calls an api backend and returns a list of employees, in a project.
I'm writing a unit test for the component that calls the service method, and mocking the service, but the mocked responses are not being assigned in the component, so the unit test is failing every time

./employee.ts

```<code>export interface Employee {
  id: string;
  name: string;
  dateOfBirth: string;
  dateJoined: string;
}
</code>```

./employee.service.ts

```<code>@Injectable({
  providedIn: 'root',
})
export class EmployeeService {
  constructor(private http: HttpClient) { }

  getEmployees(countryId: string, branchId: string): Observable<Employee[]> {
    return this.http.get<Employee[]>(`api/employees/${countryId}/${branchId}`);
  }
}
</code>```

./app.component.ts

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [ EmployeeService ],
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  employees$!: Observable<Employee[]>;
  countryId: string = '';
  branchId: string = '';

  constructor(private employeeService: EmployeeService) {}

  search(): void {
    this.employees$ = this.employeeService.getEmployees(this.countryId, this.branchId);
  }
}
</code>```

./app.component.spec.js

```<code>describe('Unit tests for AppComponent', () => {
  const mockEmployee = {
    id: "1234",
    name: "Mock Employee Name",
    dateOfBirth: "2000-01-01",
    dateJoined: "2020-01-01"
  };

  const mockEmployees = [mockEmployee];

  let fixture: ComponentFixture<AppComponent>;
  let app: AppComponent;
  let mockEmployeeService: jasmine.SpyObj<EmployeeService>;

  beforeEach(async () => {
    mockEmployeeService = jasmine.createSpyObj('EmployeeService', ['getEmployees']);
    await TestBed.configureTestingModule({
      declarations: [ AppComponent ],
      imports: [ HttpClientTestingModule, FormsModule ],
      providers: [ {provide: EmployeeService, useValue: mockEmployeeService} ]
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    app = fixture.componentInstance;
  });

  it('should test the employees are returned correctly from the service', fakeAsync() => {
    const getEmployeesSpy = mockEmployeeService.getEmployees.and.returnValue(of(mockEmployees));

    // Search for all employees in region 1234 with no trade reference set
    app.countryId = "1234";
    app.branchId = "4321";
    app.search();
    fixture.detectChanges();

    expect(getEmployeesSpy.calls.any()).toBe(true);
    expect(app.employees$).toEqual(mockEmployees);
  });
});
</code>```

What am I missing?

答:
use waitForAsync instead of fakeAsync

replace your expects with:

```<code>expect(getEmployeesSpy).toHaveBeenCalled();
expect(app.employees$).toBeObservable(mockEmployees);

</code>```

Body:
I have an Angular service that calls an api backend and returns a list of employees, in a project.
I'm writing a unit test for the component that calls the service method, and mocking the service, but the mocked responses are not being assigned in the component, so the unit test is failing every time

./employee.ts

export interface Employee {
  id: string;
  name: string;
  dateOfBirth: string;
  dateJoined: string;
}

./employee.service.ts

@Injectable({
  providedIn: 'root',
})
export class EmployeeService {
  constructor(private http: HttpClient) { }

  getEmployees(countryId: string, branchId: string): Observable<Employee[]> {
    return this.http.get<Employee[]>(`api/employees/${countryId}/${branchId}`);
  }
}

./app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [ EmployeeService ],
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  employees$!: Observable<Employee[]>;
  countryId: string = '';
  branchId: string = '';

  constructor(private employeeService: EmployeeService) {}

  search(): void {
    this.employees$ = this.employeeService.getEmployees(this.countryId, this.branchId);
  }
}

./app.component.spec.js

describe('Unit tests for AppComponent', () => {
  const mockEmployee = {
    id: "1234",
    name: "Mock Employee Name",
    dateOfBirth: "2000-01-01",
    dateJoined: "2020-01-01"
  };

  const mockEmployees = [mockEmployee];

  let fixture: ComponentFixture<AppComponent>;
  let app: AppComponent;
  let mockEmployeeService: jasmine.SpyObj<EmployeeService>;

  beforeEach(async () => {
    mockEmployeeService = jasmine.createSpyObj('EmployeeService', ['getEmployees']);
    await TestBed.configureTestingModule({
      declarations: [ AppComponent ],
      imports: [ HttpClientTestingModule, FormsModule ],
      providers: [ {provide: EmployeeService, useValue: mockEmployeeService} ]
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    app = fixture.componentInstance;
  });

  it('should test the employees are returned correctly from the service', fakeAsync() => {
    const getEmployeesSpy = mockEmployeeService.getEmployees.and.returnValue(of(mockEmployees));

    // Search for all employees in region 1234 with no trade reference set
    app.countryId = "1234";
    app.branchId = "4321";
    app.search();
    fixture.detectChanges();

    expect(getEmployeesSpy.calls.any()).toBe(true);
    expect(app.employees$).toEqual(mockEmployees);
  });
});

What am I missing?

Body:
use waitForAsync instead of fakeAsync

replace your expects with:

expect(getEmployeesSpy).toHaveBeenCalled();
expect(app.employees$).toBeObservable(mockEmployees);


问:
Pandas Dataframe: Extract info from specific series
I have this dataframe which need to extract package info (ML, KG, PZA, LT, UN, etc) from description column, and i'm pretty new at pandas.
This is the dataframe right now

SKU
Description

1
TRIDENT 6S SANDIA 9GR

2
CANAST RABBIT F1 A 1UN

3
HAND SOAP VITAMIN E 442 ML.

I need to extract 9GR, 1UN, 442 ML, etc. and take it into another column. I need to extract what matches within a list of possible values that are going to be part of the accepted Package series so this a re the possible values

[GR, UN, LT, OZ]

Anything that matches in the description column this substrings i need to replace in the column Package and remove it from description column.

答:
You can use this regex:</p>
```<code>pkg = ['ML', 'KG', 'PZA', 'LT', 'UN', 'GR']

df['package'] = df['Description'].str.extract(fr"\b(\d+\s*(?:{'|'.join(pkg)}))\b")
print(df)

# Output
   SKU                  Description package
0    1        TRIDENT 6S SANDIA 9GR     9GR
1    2       CANAST RABBIT F1 A 1UN     1UN
2    3  HAND SOAP VITAMIN E 442 ML.  442 ML
</code>```

Body:
You can use this regex:

pkg = ['ML', 'KG', 'PZA', 'LT', 'UN', 'GR']

df['package'] = df['Description'].str.extract(fr"\b(\d+\s*(?:{'|'.join(pkg)}))\b")
print(df)

# Output
   SKU                  Description package
0    1        TRIDENT 6S SANDIA 9GR     9GR
1    2       CANAST RABBIT F1 A 1UN     1UN
2    3  HAND SOAP VITAMIN E 442 ML.  442 ML


问:
How to test vuex state and mutations correctly?
tell me how to test mutations and state correctly. I have a modal window component, it is rendered if the showModal property in the state is true. And there is an event that causes a mutation that changes the property.
How to check that after the event is called, the component is no longer rendered? Do I need to import the actual vuex storage?

```<code><template>
  <div>
   <transition name="fade" appear>
     <div ref="modal" class="modal-overlay"
       v-if="isShow"
       @click="close">
     </div>
   </transition>
 <transition name="pop" appear>
  <div class="modal"
       role="dialog"
       v-if="isShow"
  >
  <div class="layer">
      <slot name="content"></slot>
    </div>
  </div>
</transition>
</div>
</code>```

```<code>import { mapState } from 'vuex'

export default {
  name: "VModal",
  computed:{
    ...mapState({
      isShow: state => state.showModal
    })
  },
  methods:{
    close(){
      this.$store.commit('SHOW_OR_HIDE_MODAL', false)
    }
  }
}

import Vuex from "vuex"
import { mount, createLocalVue } from "@vue/test-utils"
import VModal from '../../assets/src/components/VModal'
const localVue = createLocalVue()
localVue.use(Vuex)

describe('testing modal', () => {
let mutations
let state
let store

beforeEach(() => {
    state = {
        showModal: true
    }
    mutations = {
        SHOW_OR_HIDE_MODAL: jest.fn()
    }
    store = new Vuex.Store({ state, mutations })
})
test('check close modal', async () => {
    const wrapper = mount(VModal, {
        store, localVue
    })

    await wrapper.find(".modal-overlay").trigger("click")

    await wrapper.vm.$nextTick();
    expect(wrapper.find(".modal-overlay").exists()).toBe(false)
    expect(wrapper.find(".modal").exists()).toBe(false)
 })
})
</code>```

And I have index.js with store

But in test after click I get error

I understand what I'm doing wrong, but I can't figure out how to properly test vuex, sorry for the stupid question, any help would be appreciated

答:
On your test, you are setting your state showModal to true:

```<code>beforeEach(() => {
  state = {
    showModal: true
  }
  ...
})
</code>```

So your overlay is rendered and that is why your test conditions resolves as true.

```<code><div ref="modal" class="modal-overlay"
   v-if="isShow"
   @click="close">
 </div>
enter code here
</code>```

Your 'isShow' computed value is point to the showModal = true on your test.

Body:
tell me how to test mutations and state correctly. I have a modal window component, it is rendered if the showModal property in the state is true. And there is an event that causes a mutation that changes the property.
How to check that after the event is called, the component is no longer rendered? Do I need to import the actual vuex storage?

<template>

   <transition name="fade" appear>

   </transition>
 <transition name="pop" appear>

      <slot name="content"></slot>

</transition>

import { mapState } from 'vuex'

export default {
  name: "VModal",
  computed:{
    ...mapState({
      isShow: state => state.showModal
    })
  },
  methods:{
    close(){
      this.$store.commit('SHOW_OR_HIDE_MODAL', false)
    }
  }
}

import Vuex from "vuex"
import { mount, createLocalVue } from "@vue/test-utils"
import VModal from '../../assets/src/components/VModal'
const localVue = createLocalVue()
localVue.use(Vuex)

describe('testing modal', () => {
let mutations
let state
let store

beforeEach(() => {
    state = {
        showModal: true
    }
    mutations = {
        SHOW_OR_HIDE_MODAL: jest.fn()
    }
    store = new Vuex.Store({ state, mutations })
})
test('check close modal', async () => {
    const wrapper = mount(VModal, {
        store, localVue
    })

    await wrapper.find(".modal-overlay").trigger("click")

    await wrapper.vm.$nextTick();
    expect(wrapper.find(".modal-overlay").exists()).toBe(false)
    expect(wrapper.find(".modal").exists()).toBe(false)
 })
})

And I have index.js with store

But in test after click I get error

I understand what I'm doing wrong, but I can't figure out how to properly test vuex, sorry for the stupid question, any help would be appreciated

Body:
On your test, you are setting your state showModal to true:

beforeEach(() => {
  state = {
    showModal: true
  }
  ...
})

So your overlay is rendered and that is why your test conditions resolves as true.

<div ref="modal" class="modal-overlay"
   v-if="isShow"
   @click="close">
 </div>
enter code here

Your 'isShow' computed value is point to the showModal = true on your test.


问:
Get ids from HTML and put it inside JavaScript array

I need the array in javascript to pull the ids that were selected in the interface and when I click Install it runs a bat behind it that installs everything at once, but I'm not getting it... What I have ready is this:

function install() {
    const form = document.getElementById('install');
    form.addEventListener('submit', (event) => {
        event.preventDefault()
    });
}
function mostrar(){
    var allTags = [];
    var ids = document.body.getElementsByTagName('input');
    for (var i = 0; i< ids.length; i++) {
        allTags.push(ids[i].id);
    }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></head>
  <body>
    <div class="quiz-container" id="quiz" multiple>
      <div class="quiz-header">
        <h2 id="question">select the programs you wanted to install: </h2>
        <form action="/signup" method="post" id="install">
          <ul>
            <li>
              <input type="checkbox" name="1" id="a" class="answer" />
              <label for="a" id="a_text">Teams</label>
            </li>
            <li>
              <input type="checkbox" name="2" id="b" class="answer" />
              <label for="b" id="b_text">VPN</label>
            </li>
            <li>
              <input type="checkbox" name="3" id="c" class="answer" />
              <label for="c" id="c_text">FDC</label>
            </li>
            <li>
              <input type="checkbox" name="4" id="d" class="answer" />
              <label for="d" id="d_text">Acrobat Reader</label>
            </li>
            <li>
              <input type="checkbox" name="5" id="e" class="answer" />
              <label for="e" id="d_text">Power BI</label>
            </li>
          </ul>
        </form>
      </div>
      <button id="submit">Install</button>
    </div>
  </body></code>```

答:
Move your button inside your form and add correct submit type.

```<code><button type="submit">Install</button>
</code>```

Then, in your mostrar function you can do:

```<code>var selectedTags = document.querySelectorAll('.answer:checked').forEach(function(element) {
   console.log(element.id)
});
</code>```

Body:
I need the array in javascript to pull the ids that were selected in the interface and when I click Install it runs a bat behind it that installs everything at once, but I'm not getting it... What I have ready is this:

function install() {
    const form = document.getElementById('install');
    form.addEventListener('submit', (event) => {
        event.preventDefault()
    });
}
function mostrar(){
    var allTags = [];
    var ids = document.body.getElementsByTagName('input');
    for (var i = 0; i< ids.length; i++) {
        allTags.push(ids[i].id);
    }

}

select the programs you wanted to install:

        <form action="/signup" method="post" id="install">

              <input type="checkbox" name="1" id="a" class="answer" />
              Teams

              <input type="checkbox" name="2" id="b" class="answer" />
              VPN

              <input type="checkbox" name="3" id="c" class="answer" />
              FDC

              <input type="checkbox" name="4" id="d" class="answer" />
              Acrobat Reader

              <input type="checkbox" name="5" id="e" class="answer" />
              Power BI

        </form>

      <button id="submit">Install</button>

Body:
Move your button inside your form and add correct submit type.

<button type="submit">Install</button>

Then, in your mostrar function you can do:

var selectedTags = document.querySelectorAll('.answer:checked').forEach(function(element) {
   console.log(element.id)
});


问:
Pyspark combine dataframes of different length without duplicating
I have these three dfs:

id | name
------------------------
1  | {"value": "bob"}
1  | {"value": "Robert"}
2  | {"value": "Mary"}
```
<pre class="lang-none prettyprint-override"><code>id | dob
----------------------------
1  | {"value": "21-04-1988"}
2  | {"value": null}
</code>```

id | country
--------------------
1  | {"value": "IT"}
1  | {"value": "DE"}
2  | {"value": "FR"}
2  | {"value": "ES"}
```
<p>And I want to combine them, but I don't want to duplicate information.</p>
<pre class="lang-none prettyprint-override"><code>id | name                  | dob                     |country
----------------------------------------------------------------------
1  | {"value": "bob"}      | {"value": "21-04-1988"} | {"value": "IT"}
1  | {"value": "Robert"}   | Null                    | {"value": "DE"}
2  | {"value": "Mary"}     | {"value": Null}         | {"value": "FR"}
2  | Null                  | Null                    | {"value": "ES"}
</code>```

I tried with a multiple outer join but it doesn't result in the above table.

```<code>name = spark.createDataFrame(
    [
        (1, {"value" : "bob"}),  # create your data here, be consistent in the types.
        (1, {"value" : "Robert"}),
        (2, {"value" : "Mary"})
    ],
    ["id", "name"]  # add your column names here
)

dob = spark.createDataFrame(
    [
        (1, {"value" : "21-04-1988"}),  # create your data here, be consistent in the types.
        (2, {"value" : None})
    ],
    ["id", "dob"]  # add your column names here
)

country = spark.createDataFrame(
    [
        (1, {"value" : "IT"}),  # create your data here, be consistent in the types.
        (1, {"value" : "DE"}),
        (2, {"value" : "FR"}),
        (2, {"value" : "ES"}),
    ],
    ["id", "country"]  # add your column names here
)

(name.join(dob, "id", "outer").join(country, "id", "outer")).show()
</code>```

produces this:

id  name                dob                     country
---------------------------------------------------------------
1 | {"value":"Robert"} |{"value":"21-04-1988"}  |{"value":"DE"}
1 | {"value":"Robert"} |{"value":"21-04-1988"}  |{"value":"IT"}
1 | {"value":"bob"}    |{"value":"21-04-1988"}  |{"value":"DE"}
1 | {"value":"bob"}    |{"value":"21-04-1988"}  |{"value":"IT"}
2 | {"value":"Mary"}   |{"value":null}          |{"value":"ES"}
2 | {"value":"Mary"}   |{"value":null}          |{"value":"FR"}
```

Now I understand that this is exactly how a full outer join would work - but I don't need those extra duplicate information in it (I need to contain the number of rows as much as possible).

Any clue?

答:
You can add a column id2 to all the three dataframes using row_number() for example then use it along with id as the join condition:

```<code>from pyspark.sql import functions as F, Window

w = Window.partitionBy("id").orderBy(F.lit(None)) # change this if you have some column to use for ordering

name = name.withColumn("id2", F.row_number().over(w))
dob = dob.withColumn("id2", F.row_number().over(w))
country = country.withColumn("id2", F.row_number().over(w))

result = (name.join(dob, ["id", "rn"], "full")
          .join(country, ["id", "rn"], "full")
          .drop("rn")
          )

result.show(truncate=False)
#+---+-----------------+---------------------+-------------+
#|id |name             |dob                  |country      |
#+---+-----------------+---------------------+-------------+
#|1  |{value -> bob}   |{value -> 21-04-1988}|{value -> IT}|
#|1  |{value -> Robert}|null                 |{value -> DE}|
#|2  |{value -> Mary}  |{value -> null}      |{value -> FR}|
#|2  |null             |null                 |{value -> ES}|
#+---+-----------------+---------------------+-------------+
</code>```

Body:
I have these three dfs:

id | name
------------------------
1  | {"value": "bob"}
1  | {"value": "Robert"}
2  | {"value": "Mary"}

id | dob
----------------------------
1  | {"value": "21-04-1988"}
2  | {"value": null}

id | country
--------------------
1  | {"value": "IT"}
1  | {"value": "DE"}
2  | {"value": "FR"}
2  | {"value": "ES"}

And I want to combine them, but I don't want to duplicate information.

id | name                  | dob                     |country
----------------------------------------------------------------------
1  | {"value": "bob"}      | {"value": "21-04-1988"} | {"value": "IT"}
1  | {"value": "Robert"}   | Null                    | {"value": "DE"}
2  | {"value": "Mary"}     | {"value": Null}         | {"value": "FR"}
2  | Null                  | Null                    | {"value": "ES"}

I tried with a multiple outer join but it doesn't result in the above table.

name = spark.createDataFrame(
    [
        (1, {"value" : "bob"}),  # create your data here, be consistent in the types.
        (1, {"value" : "Robert"}),
        (2, {"value" : "Mary"})
    ],
    ["id", "name"]  # add your column names here
)

dob = spark.createDataFrame(
    [
        (1, {"value" : "21-04-1988"}),  # create your data here, be consistent in the types.
        (2, {"value" : None})
    ],
    ["id", "dob"]  # add your column names here
)

country = spark.createDataFrame(
    [
        (1, {"value" : "IT"}),  # create your data here, be consistent in the types.
        (1, {"value" : "DE"}),
        (2, {"value" : "FR"}),
        (2, {"value" : "ES"}),
    ],
    ["id", "country"]  # add your column names here
)

(name.join(dob, "id", "outer").join(country, "id", "outer")).show()

produces this:

id  name                dob                     country
---------------------------------------------------------------
1 | {"value":"Robert"} |{"value":"21-04-1988"}  |{"value":"DE"}
1 | {"value":"Robert"} |{"value":"21-04-1988"}  |{"value":"IT"}
1 | {"value":"bob"}    |{"value":"21-04-1988"}  |{"value":"DE"}
1 | {"value":"bob"}    |{"value":"21-04-1988"}  |{"value":"IT"}
2 | {"value":"Mary"}   |{"value":null}          |{"value":"ES"}
2 | {"value":"Mary"}   |{"value":null}          |{"value":"FR"}

Now I understand that this is exactly how a full outer join would work - but I don't need those extra duplicate information in it (I need to contain the number of rows as much as possible).

Any clue?

Body:
You can add a column id2 to all the three dataframes using row_number() for example then use it along with id as the join condition:

from pyspark.sql import functions as F, Window

w = Window.partitionBy("id").orderBy(F.lit(None)) # change this if you have some column to use for ordering

name = name.withColumn("id2", F.row_number().over(w))
dob = dob.withColumn("id2", F.row_number().over(w))
country = country.withColumn("id2", F.row_number().over(w))

result = (name.join(dob, ["id", "rn"], "full")
          .join(country, ["id", "rn"], "full")
          .drop("rn")
          )

result.show(truncate=False)
#+---+-----------------+---------------------+-------------+
#|id |name             |dob                  |country      |
#+---+-----------------+---------------------+-------------+
#|1  |{value -> bob}   |{value -> 21-04-1988}|{value -> IT}|
#|1  |{value -> Robert}|null                 |{value -> DE}|
#|2  |{value -> Mary}  |{value -> null}      |{value -> FR}|
#|2  |null             |null                 |{value -> ES}|
#+---+-----------------+---------------------+-------------+


问:
select * only return one value
I want select multiple (all) values from table Account.

```<code>string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();
</code>```

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

答:
You need a while-loop;</p>

```<code>while(reader.Read()) {
           Console.WriteLine("{0}", reader[0]);
        }
</code>```

Title: select * only return one value

Body:
I want select multiple (all) values from table Account.

string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

Body:
You need a while-loop;

while(reader.Read()) {
           Console.WriteLine("{0}", reader[0]);
        }


问:
How can I check if a boolean from a different model is true for a user of a team?
I have the following model I want to use to add rights to users that are part of a team:

```<code>class Rights(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Teams, on_delete=models.CASCADE)
    read = models.BooleanField(default=True)
    write = models.BooleanField(default=False)
    edit = models.BooleanField(default=False)
</code>```

Some Users need to be able to make new entries. Some are not allowed to have that possibility. So, if some user sends a request, how can I check if one or more of these boolean values are true or false for this specific user?

答:
You can obtain the Rights object that point to myuser and myteam, and then inspect the read, write and/or edit fields:

```<code>right = Rights.objects.get(<strong>user=<em>myuser</em>, team=<em>myteam</em></strong>)
right.read  # bool, True or False
right.write  # bool, True or False
right.edit  # bool, True or False</code>```

You can ensure that for each user/team combination, there is at most one record with:

```<code>from django.conf import settings

class Right(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    team = models.ForeignKey(Teams, on_delete=models.CASCADE)
    read = models.BooleanField(default=True)
    write = models.BooleanField(default=False)
    edit = models.BooleanField(default=False)

    class Meta:
        constraints = [
            models.<strong>UniqueConstraint(fields=('user', 'team')</strong>, name='unique_per_user_team'<strong>)</strong>
        ]</code>```

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Note: normally a Django model is given a singular name, so Right instead of <s>Rights</s>.

Body:
I have the following model I want to use to add rights to users that are part of a team:

class Rights(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Teams, on_delete=models.CASCADE)
    read = models.BooleanField(default=True)
    write = models.BooleanField(default=False)
    edit = models.BooleanField(default=False)

Some Users need to be able to make new entries. Some are not allowed to have that possibility. So, if some user sends a request, how can I check if one or more of these boolean values are true or false for this specific user?

Body:
You can obtain the Rights object that point to myuser and myteam, and then inspect the read, write and/or edit fields:

right = Rights.objects.get(user=myuser, team=myteam)
right.read  # bool, True or False
right.write  # bool, True or False
right.edit  # bool, True or False

You can ensure that for each user/team combination, there is at most one record with:

from django.conf import settings

class Right(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    team = models.ForeignKey(Teams, on_delete=models.CASCADE)
    read = models.BooleanField(default=True)
    write = models.BooleanField(default=False)
    edit = models.BooleanField(default=False)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=('user', 'team'), name='unique_per_user_team')
        ]

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Note: normally a Django model is given a singular name, so Right instead of <s>Rights</s>.


问:
How to safeguard image URL?
Have lots of images stored at Azure Blob Storage. Frontend Angular display them like:

```<code><div *ngFor="let img of list;">
  <img src="/AzPath/{{img}}">
</div>
</code>```

Using CanActivate safeguarding route inside Angular:

```<code>import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable({  providedIn: 'root'})
export class AuthGuardServiceService implements CanActivate {
  constructor(public router: Router) { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean
{
...
}
</code>```

withCredentials: true in proxy.conf.js to send in cookies as session is managed by database. Also Azure firewall rule for Storage Account only allows certain IP.

I noticed the GET request to nodejs (Azure Function) for image src URL don't send in cookies, but I prefer not to access database with session cookie for performance. I can think of is a signed URL which is also validated by node.

What's needed is to prevent authenticated users altering the src to access other images not supposed to see. For example user A is permitted to see A-1.png but is not B-1.png. My thought for a signedURL is node should check if this URL is tempered. I'm opened to any idea not limited to signed URL, all input is appreciated, with code sample is a PLUS.

Angular v12, nodejs v14

答:
I think you just want to not make the images public to the web, right? You can apply one of the following methods and I believe either one will work for you:

1- work with a reverse proxy. Your front end will use the reverse proxy url, and it will be responsible to serve the real image to you. As a drawback, you can't leverage CDN to serve the images for you.

2-Work with Managed identities and Storage Account firewall rules, this way, only your backend can access the images and you won't need to worry about the image url. You can read more about it in here

Title: How to safeguard image URL?

Body:
Have lots of images stored at Azure Blob Storage. Frontend Angular display them like:

Using CanActivate safeguarding route inside Angular:

import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable({  providedIn: 'root'})
export class AuthGuardServiceService implements CanActivate {
  constructor(public router: Router) { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean
{
...
}

withCredentials: true in proxy.conf.js to send in cookies as session is managed by database. Also Azure firewall rule for Storage Account only allows certain IP.

I noticed the GET request to nodejs (Azure Function) for image src URL don't send in cookies, but I prefer not to access database with session cookie for performance. I can think of is a signed URL which is also validated by node.

What's needed is to prevent authenticated users altering the src to access other images not supposed to see. For example user A is permitted to see A-1.png but is not B-1.png. My thought for a signedURL is node should check if this URL is tempered. I'm opened to any idea not limited to signed URL, all input is appreciated, with code sample is a PLUS.

Angular v12, nodejs v14


问:
Alfresco 7.1.1 thumbnail not getting generated (Windows)
We have installed Alfresco 7.1.1 Enterprise version. Alfresco is working fine and we are able to preview documents in Share. However it is not generating the thumbnails for these documents.

When we tried to test the document transformation from the admin console, it shows the following error.

```<code>1             pdf  png  TestTransform.pdf 23.1 KB Local:pdfToImageViaPng
1             workspace://SpacesStore/2ead5401-59f6-49ef-8065-03a1bad1ee97
1.1           pdf  png  TestTransform.pdf 23.1 KB Local:pdfrenderer
1.1                     Failed 01090029 pdfrenderer returned a 400 status All in One
              Transformer - Transformer exit code was not 0: \nCannot run program
      \"H:\\Alfresco-Transform-Service\\alfresco-pdf-renderer\": CreateProcess
 error=5, Access is denied http://localhost:8090/transform targetExtension=png
sourceEncoding=UTF-8 sourceMimetype=application/pdf sourceExtension=pdf targetMimetype=image/png
1                       Failed 01090030 Content conversion failed
1             Finished in 51 ms
</code>```

We also has given modify and read & execute permissions to the H:\Alfresco-Transform-Service\alfresco-pdf-renderer\alfresco-pdf-renderer.exe file. We even tried to run the tomcat, start-transform-core-aio.jar and activeMQ as an Admin but still it gives the same error.

We have also installed the GhostScripts, however it is not mentioned anywhere on the Alfresco's website. :-(

Any help will be appreciated.. thanks

答: It turns out that the server machine needed to be restarted after the Windows upgrade. After restarting the server machine it started working.</p>

Body:
We have installed Alfresco 7.1.1 Enterprise version. Alfresco is working fine and we are able to preview documents in Share. However it is not generating the thumbnails for these documents.

When we tried to test the document transformation from the admin console, it shows the following error.

1             pdf  png  TestTransform.pdf 23.1 KB Local:pdfToImageViaPng
1             workspace://SpacesStore/2ead5401-59f6-49ef-8065-03a1bad1ee97
1.1           pdf  png  TestTransform.pdf 23.1 KB Local:pdfrenderer
1.1                     Failed 01090029 pdfrenderer returned a 400 status All in One
              Transformer - Transformer exit code was not 0: \nCannot run program
      \"H:\\Alfresco-Transform-Service\\alfresco-pdf-renderer\": CreateProcess
 error=5, Access is denied http://localhost:8090/transform targetExtension=png
sourceEncoding=UTF-8 sourceMimetype=application/pdf sourceExtension=pdf targetMimetype=image/png
1                       Failed 01090030 Content conversion failed
1             Finished in 51 ms

We also has given modify and read & execute permissions to the H:\Alfresco-Transform-Service\alfresco-pdf-renderer\alfresco-pdf-renderer.exe file. We even tried to run the tomcat, start-transform-core-aio.jar and activeMQ as an Admin but still it gives the same error.

We have also installed the GhostScripts, however it is not mentioned anywhere on the Alfresco's website. :-(

Any help will be appreciated.. thanks