问:
HTML5 video flashes and makes additional requests for the same video
I have a pop-up modal React component that renders tabs. At the top of the modal are tabs where users can select to show certain information within that tab. One of the tabs render a video via this snippet of code.

```<code><video autoPlay loop muted playsInline>
    <source src="some-video-file.webm" type="video/webm" />
    <source src="some-video-file.mp4" type="video/mp4" />
</video>
</code>```

My problems are:

When a user first clicks on the tab with this video, there will not be a video and instead, will  end up with a blank spot where the video is suppose to be for a few seconds.

When a user clicks on another tab and clicks back to this video, the same thing will happen and the same request for that video is made.

I was wondering if it were possible to:

Preload the video so when the component is rendered, there will be no flash

Prevent subsequent, redundant request for the same video

答:
React is taking the video out of the DOM when you switch tabs most likely. If you could just hide it on tab switch, it would not have to re-fetch the files.

Also,  you could try this to stop the flash, as it would load much faster since it only loads the first frame as well as some other meta data.

```<code><video autoPlay loop muted playsInline>
    <source src="some-video-file.webm" type="video/webm" preload="metadata" />
    <source src="some-video-file.mp4" type="video/mp4" preload="metadata" />
</video>
</code>```

Body:
I have a pop-up modal React component that renders tabs. At the top of the modal are tabs where users can select to show certain information within that tab. One of the tabs render a video via this snippet of code.

<video autoPlay loop muted playsInline>
    <source src="some-video-file.webm" type="video/webm" />
    <source src="some-video-file.mp4" type="video/mp4" />
</video>

My problems are:

When a user first clicks on the tab with this video, there will not be a video and instead, will  end up with a blank spot where the video is suppose to be for a few seconds.

When a user clicks on another tab and clicks back to this video, the same thing will happen and the same request for that video is made.

I was wondering if it were possible to:

Preload the video so when the component is rendered, there will be no flash

Prevent subsequent, redundant request for the same video

Body:
React is taking the video out of the DOM when you switch tabs most likely. If you could just hide it on tab switch, it would not have to re-fetch the files.

Also,  you could try this to stop the flash, as it would load much faster since it only loads the first frame as well as some other meta data.

<video autoPlay loop muted playsInline>
    <source src="some-video-file.webm" type="video/webm" preload="metadata" />
    <source src="some-video-file.mp4" type="video/mp4" preload="metadata" />
</video>


来源: stackexchange

问:
Future-proofing data types(i.e creating structs with only one member in hopes they can be expanded later, when needed)
Say I want to create a list of variables/objects to store something very specific(say the coordinate for where an enemy needs to spawn in a videogame), at first I would only need a simple point in space to store this information but later on I may want to add the enemy type and other data specific to each element of this list. Is it good practice to write a whole new class or struct with only just the initial data member I need in hopes that whenever I need to update the list with more data per element I can just add members to this previously redundant struct/class? Furthermore, is packaging an already existing type into a new one in the spirit of being more descriptive something that actually helps code readability?</p>

答:
Sounds like a classic case for some good old object orientated programming.

So the idea would basically be that you have your simple struct/class with, as mentioned in your example, coordinates. If you would want to add another enemy with some extra attributes to be stored you would go ahead and create a new class/struct that inherits from the very basic class. That way you get all the attributes the basic class had in your new class plus you can define new ones.

That way you have a good structure in your code and it is easy to understand what is going on. Scalability and reusability also profit greatly from this, which is why this concept is state-of-the-art.

This might sound a little confusing at first, but I recommend to read up on inheritance and object oriented programming in general. I promise it is not too hard once you get used to the thinking patterns.

ContentLicense: CC BY-SA 4.0


问:
Transposing `memoryview` in pure Python
Is there a pure Python way of transposing a memoryview?

Python memoryviews can represent more than just a 1-dimensional chunk of bytes. They can represent multidimensional layouts, noncontiguous memory, complex element types, and more. For example, in the following code:

```<code>In [1]: import numpy

In [2]: x = numpy.array([[1, 2], [3, 4]])

In [3]: y = x.T

In [4]: a = memoryview(x)

In [5]: b = memoryview(y)
</code>```

a and b are 2-by-2 multidimensional memoryviews:

```<code>In [6]: a.shape
Out[6]: (2, 2)

In [7]: b.shape
Out[7]: (2, 2)
</code>```

and b represents a transpose of a, so a[i, j] and b[j, i] alias the same memory (which is cell i, j of the original x array):

```<code>In [8]: a[0, 1] = 5

In [9]: b[1, 0]
Out[9]: 5

In [10]: x
Out[10]:
array([[1, 5],
       [3, 4]])
</code>```

NumPy arrays support easy transposes, but NumPy arrays aren't the only sources of multidimensional memoryviews. For example, you can cast a single-dimensional memoryview:

```<code>In [11]: bytearr = bytearray([1, 2, 3, 4])

In [12]: mem = memoryview(bytearr).cast('b', (2, 2))

In [13]: mem.shape
Out[13]: (2, 2)

In [14]: mem[1, 0] = 5

In [15]: bytearr
Out[15]: bytearray(b'\x01\x02\x05\x04')
</code>```

The memoryview format is flexible enough to represent a transpose of mem, like what b was to a in our earlier example, but there doesn't seem to be an easy transpose method in the memoryview API. Is there a pure-Python way of transposing arbitrary multidimensional memoryviews?

Title: Transposing `memoryview` in pure Python

Body:
Is there a pure Python way of transposing a memoryview?

Python memoryviews can represent more than just a 1-dimensional chunk of bytes. They can represent multidimensional layouts, noncontiguous memory, complex element types, and more. For example, in the following code:

In [1]: import numpy

In [2]: x = numpy.array([[1, 2], [3, 4]])

In [3]: y = x.T

In [4]: a = memoryview(x)

In [5]: b = memoryview(y)

a and b are 2-by-2 multidimensional memoryviews:

In [6]: a.shape
Out[6]: (2, 2)

In [7]: b.shape
Out[7]: (2, 2)

and b represents a transpose of a, so a[i, j] and b[j, i] alias the same memory (which is cell i, j of the original x array):

In [8]: a[0, 1] = 5

In [9]: b[1, 0]
Out[9]: 5

In [10]: x
Out[10]:
array([[1, 5],
       [3, 4]])

NumPy arrays support easy transposes, but NumPy arrays aren't the only sources of multidimensional memoryviews. For example, you can cast a single-dimensional memoryview:

In [11]: bytearr = bytearray([1, 2, 3, 4])

In [12]: mem = memoryview(bytearr).cast('b', (2, 2))

In [13]: mem.shape
Out[13]: (2, 2)

In [14]: mem[1, 0] = 5

In [15]: bytearr
Out[15]: bytearray(b'\x01\x02\x05\x04')

The memoryview format is flexible enough to represent a transpose of mem, like what b was to a in our earlier example, but there doesn't seem to be an easy transpose method in the memoryview API. Is there a pure-Python way of transposing arbitrary multidimensional memoryviews?

Body:
This might help you:

>>> import numpy as np
>>> import array
>>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
>>> m = memoryview(a)
>>> m_copy =  np.array(m)[np.newaxis]
>>> m_copy
array([[-11111111,  22222222, -33333333,  44444444]])
>>> m_copy.T
array([[-11111111],
       [ 22222222],
       [-33333333],
       [ 44444444]])

Without using numpy:

import array
a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
print(a)

#output:
array('l', [-11111111, 22222222, -33333333, 44444444])

m = memoryview(a)
a = [[x for x in m]]
result = list(map(list, zip(*a)))
print(result)

#output:
[[-11111111], [22222222], [-33333333], [44444444]]


问:
NodeJS + MongoDB _message: 'book validation failed'
I just start learning NodeJS and MongoDB. Now ı am working on a small project to learn basic stuff. But ı am getting a error, in this project ı try to insert data to mongodb which is,

userid like;
"5ed6bfe86034a81dbc7226aa" created from random numbers and letters.

But ı can not insert id to mongodb ı got an error. Here is my codes.

Firstly here is my model which is "Book.js"

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BookSchema = new Schema({
   title: {
      type: String,
      required: true,
   },

   userid: Schema.Types.ObjectId, //ı defined here no problem.

   published: {
      type: Boolean,
      default: false
   },
</code>```

So, in routes folder my "book.js" like this;

```<code>var express = require('express');
var router = express.Router();

//Models
const Book = require('../models/Book');
const User = require('../models/Users');

/* GET book page. */
router.post('/new', function(req, res, next) {
  const book = new Book({
    title: 'Node JS',

    userid: BigInt, //ı got error here.
//what ı should write?

    meta: {
      votes: 12,
      favs: 90
    },
    category: "History"

  });
  book.save((err, data) => {
    if (err)
      console.log(err);

    res.json(data);
  });
});
</code>```

so when ı run my server and try to post data to mongodb with using postman ı got an error.

Like this; _message: 'book validation failed',

and more information: Error: book validation failed: userid: Cast to ObjectId failed for value "[Function: BigInt]" at path "userid"

Now, how can ı define "userid" variable? why ı got an error? what ı should write to define userid for mongodb to post data successfully? Thanks in advance.

答:
I think you need to store the _id created in user schema

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BookSchema = new Schema({
   title: {
      type: String,
      required: true,
   },

   userid: {
type:Schema.Types.ObjectId,
ref:User,
required:true
},
   published: {
      type: Boolean,
      default: false
   },
</code>```

Then you need to fetch the user id and then store it to Book collection. By specifying ref keyword you can use populate method provided by mongoose to fetch the user info using book schema.

Example program to fetch and save _id

```<code>exports.postaddFoods=(req,res,next)=>{
  const foodname=req.body.foodname;
  const image=req.body.image;
  const shopname=req.shop.shopName;
  const price=req.body.price;
  Shop.findOne({shopName:shopname})
  .then(sid=>{
    const food= new Food({
      foodName:foodname,
      image:image,
      shopName:shopname,
      price:price,
      shopId:sid._id
    });
    return food.save()

  })
</code>```

Body:
I just start learning NodeJS and MongoDB. Now ı am working on a small project to learn basic stuff. But ı am getting a error, in this project ı try to insert data to mongodb which is,

userid like;
"5ed6bfe86034a81dbc7226aa" created from random numbers and letters.

But ı can not insert id to mongodb ı got an error. Here is my codes.

Firstly here is my model which is "Book.js"

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BookSchema = new Schema({
   title: {
      type: String,
      required: true,
   },

   userid: Schema.Types.ObjectId, //ı defined here no problem.

   published: {
      type: Boolean,
      default: false
   },

So, in routes folder my "book.js" like this;

var express = require('express');
var router = express.Router();

//Models
const Book = require('../models/Book');
const User = require('../models/Users');

/* GET book page. */
router.post('/new', function(req, res, next) {
  const book = new Book({
    title: 'Node JS',

    userid: BigInt, //ı got error here.
//what ı should write?

    meta: {
      votes: 12,
      favs: 90
    },
    category: "History"

  });
  book.save((err, data) => {
    if (err)
      console.log(err);

    res.json(data);
  });
});

so when ı run my server and try to post data to mongodb with using postman ı got an error.

Like this; _message: 'book validation failed',

and more information: Error: book validation failed: userid: Cast to ObjectId failed for value "[Function: BigInt]" at path "userid"

Now, how can ı define "userid" variable? why ı got an error? what ı should write to define userid for mongodb to post data successfully? Thanks in advance.

Body:
I think you need to store the _id created in user schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BookSchema = new Schema({
   title: {
      type: String,
      required: true,
   },

   userid: {
type:Schema.Types.ObjectId,
ref:User,
required:true
},
   published: {
      type: Boolean,
      default: false
   },

Then you need to fetch the user id and then store it to Book collection. By specifying ref keyword you can use populate method provided by mongoose to fetch the user info using book schema.

Example program to fetch and save _id

exports.postaddFoods=(req,res,next)=>{
  const foodname=req.body.foodname;
  const image=req.body.image;
  const shopname=req.shop.shopName;
  const price=req.body.price;
  Shop.findOne({shopName:shopname})
  .then(sid=>{
    const food= new Food({
      foodName:foodname,
      image:image,
      shopName:shopname,
      price:price,
      shopId:sid._id
    });
    return food.save()

  })


问:
Calling unix shell script remotely from C#
In my current project, i need to call a Unix shell script from the C# application. I also need to get the response back whether the script has been execute successfully or any error has occurred.

The C# program is running on a Windows machine. I need to connect to a Unix machine and execute the script.

Can anyone let me know how this can be done using C#?

答:
Will this solve your problem?

sharpSsh - A Secure Shell (SSH) library for .NET

Update

Refer to the developer's site for SharpSSH for more information on how to use the tool.

Update 2

change link of developer site to archived link.

ContentLicense: CC BY-SA 3.0


问:
How do I avoid NaN?
I understand it's because the program thinks I'm dividing by O, but I'm not sure how to fix it in the program. The program works fine, though. It outputs the average the way I want it to, but I would like it to output <0.0> when there are no integers being sent from the main method.

```<code>public class Statistics {

private int count;
private int sum;
//private double average;

public Statistics() {
    this.count = 0;

}

public void addNumber(int number) {
    sum += number;

    count++;
}

public int getCount() {
    return this.count;
}

public int sum() {

    return sum;
}

public double average() {
    double average=0;
    average = this.count/(double)sum;
    return average;
}

public static void main(String[] args) {
    Statistics statistics = new Statistics();
    //statistics.addNumber(3);
    //statistics.addNumber(5);
   // statistics.addNumber(1);
    //statistics.addNumber(2);
   System.out.println("Count: " + statistics.getCount());
    System.out.println("Sum: " + statistics.sum());
    System.out.println("Average: " + statistics.average());
}
</code>```

}

How can I re-write this average section to avoid that?

答:
Just add an if statement to handle this edge case.</p>
```<code>public double average() {
    double average=0;
    //added if statement to avoid diving by 0
    if(count==0){return 0.0;}
    average = this.count/(double)sum;
    return average;
}
</code>```

Title: How do I avoid NaN?

Body:
I understand it's because the program thinks I'm dividing by O, but I'm not sure how to fix it in the program. The program works fine, though. It outputs the average the way I want it to, but I would like it to output <0.0> when there are no integers being sent from the main method.

public class Statistics {

private int count;
private int sum;
//private double average;

public Statistics() {
    this.count = 0;

}

public void addNumber(int number) {
    sum += number;

    count++;
}

public int getCount() {
    return this.count;
}

public int sum() {

    return sum;
}

public double average() {
    double average=0;
    average = this.count/(double)sum;
    return average;
}

public static void main(String[] args) {
    Statistics statistics = new Statistics();
    //statistics.addNumber(3);
    //statistics.addNumber(5);
   // statistics.addNumber(1);
    //statistics.addNumber(2);
   System.out.println("Count: " + statistics.getCount());
    System.out.println("Sum: " + statistics.sum());
    System.out.println("Average: " + statistics.average());
}

}

How can I re-write this average section to avoid that?

Body:
Just add an if statement to handle this edge case.

public double average() {
    double average=0;
    //added if statement to avoid diving by 0
    if(count==0){return 0.0;}
    average = this.count/(double)sum;
    return average;
}


问:
loop input and listbox
im studying vba and i need to write a code that the users enters the sales of the week "Each day individualy" and show it in an listbox im using this as an last resource i dont need the entire code i just need to known how i can make it happen </p>

答:
```<code>Dim dias() As String{"Domingo", "Lunes", "Martes","Miercoles", "Jueves","Viernes","Sabado"}
Dim ventas As Double
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    MakeArray()
End Sub
Private Sub MakeArray()
    For ventas = 0 To 6
        InputBox("Escriba las ventas finales de los dias correspondientes")
    Next
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    For total = 0 To 6 Step 1
        ListBox1.Items.Add(dias + ventas)
    Next
End Sub
</code>```

End Class

the variables are in spanish but this is what im trying to do

Title: loop input and listbox

Body:
Dim dias() As String{"Domingo", "Lunes", "Martes","Miercoles", "Jueves","Viernes","Sabado"}
Dim ventas As Double
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    MakeArray()
End Sub
Private Sub MakeArray()
    For ventas = 0 To 6
        InputBox("Escriba las ventas finales de los dias correspondientes")
    Next
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    For total = 0 To 6 Step 1
        ListBox1.Items.Add(dias + ventas)
    Next
End Sub

End Class

the variables are in spanish but this is what im trying to do


问:
Schema mismatch - Spark DataFrame written to Delta
When writing a dataframe to delta format, the resulting delta does not seem to follow the schema of the dataframe that was written. Specifically, the 'nullable' property of a field seems to be always 'true' in the resulting delta regardless of the source dataframe schema. Is this expected or am I making a mistake here? Is there a way to get the schema of the written delta to match exactly with the source df?</p>

```<code>scala> df.schema
res2: org.apache.spark.sql.types.StructType = StructType(StructField(device_id,StringType,false), StructField(val1,StringType,true), StructField(val2,StringType,false), StructField(dt,StringType,true))

scala> df.write.format("delta").save("D:/temp/d1")

scala> spark.read.format("delta").load("D:/temp/d1").schema
res5: org.apache.spark.sql.types.StructType = StructType(StructField(device_id,StringType,true), StructField(val1,StringType,true), StructField(val2,StringType,true), StructField(dt,StringType,true))
</code>```

答: The problem is that a lot of users thought that their schema was not nullable, and wrote null data. Then they couldn't read the data back as their parquet files were corrupted. In order to avoid this, we always assume the table schema is nullable in Delta. In Spark 3.0, when creating a table, you will be able to specify columns as NOT NULL. This way, Delta will actually prevent null values from being written, because Delta will check that the columns are in fact not null when writing it.</p>

Body:
When writing a dataframe to delta format, the resulting delta does not seem to follow the schema of the dataframe that was written. Specifically, the 'nullable' property of a field seems to be always 'true' in the resulting delta regardless of the source dataframe schema. Is this expected or am I making a mistake here? Is there a way to get the schema of the written delta to match exactly with the source df?

scala> df.schema
res2: org.apache.spark.sql.types.StructType = StructType(StructField(device_id,StringType,false), StructField(val1,StringType,true), StructField(val2,StringType,false), StructField(dt,StringType,true))

scala> df.write.format("delta").save("D:/temp/d1")

scala> spark.read.format("delta").load("D:/temp/d1").schema
res5: org.apache.spark.sql.types.StructType = StructType(StructField(device_id,StringType,true), StructField(val1,StringType,true), StructField(val2,StringType,true), StructField(dt,StringType,true))


问:
I got a TypeError: mongoose.model is not a function. How do I fix it?
I tried to run it but I get a type error, am I missing something.

```<code>let CustomerSchema = new mongoose.connect({
useNewUrlParser: true,
name: String,
email: {
    type: String,
    required: true,
    unique: true
}
</code>```

})

module.exports = mongoose.model('Customer', CustomerSchema);

答:
have you imported the lib yet?</p>

```<code>const mongoose = require('mongoose');
</code>```

Body:
I tried to run it but I get a type error, am I missing something.

let CustomerSchema = new mongoose.connect({
useNewUrlParser: true,
name: String,
email: {
    type: String,
    required: true,
    unique: true
}

})

module.exports = mongoose.model('Customer', CustomerSchema);

Body:
have you imported the lib yet?

const mongoose = require('mongoose');


问:
Oracle: Why do I have to use TO_DATE to pull my data?
When trying to filter on EXPIRE_DATE, it seems I have to use TO_DATE. Why do I have to use TO_DATE? The EXPIRE_DATE data type in the database is ALREADY set to date. Here is the code that works.

```<code>SELECT * FROM MY_TABLE
  WHERE EXPIRE_DATE >= TO_DATE('2020/01/13','yyyy/mm/dd')
  AND EXPIRE_DATE <= TO_DATE('2020/04/19','yyyy/mm/dd')
</code>```

I tried to use BETWEEN without TO_DATE and just use my dates but I received an error.

To recap, even though the data type for this is ALREADY date, it seems I have to use TO_DATE to pull my data when I want to filter. Is there something I am missing? Here is my error when I try filter my data without using TO_DATE.

答:
You don't need to use TO_DATE, instead you can use a DATE literal:

SELECT *
FROM   MY_TABLE
WHERE  EXPIRE_DATE >= DATE '2020/01/13'
AND    EXPIRE_DATE <= DATE '2020/04/19'
```

<p>Or, if your <code>NLS_DATE_FORMAT</code> session parameter matches <code>YYYY/MM/DD</code> then you can insert the values as strings and rely on implicit string conversion (don't do this though):</p>

<pre class="lang-sql prettyprint-override"><code>ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY/MM/DD';

SELECT *
FROM   MY_TABLE
WHERE  EXPIRE_DATE >= '2020/01/13'
AND    EXPIRE_DATE <= '2020/04/19'
</code>```

But it is not good practice to rely on the NLS_DATE_FORMAT as ANY user can change their own value at ANY time so your query can randomly fail when users start changing these values.

Body:
When trying to filter on EXPIRE_DATE, it seems I have to use TO_DATE. Why do I have to use TO_DATE? The EXPIRE_DATE data type in the database is ALREADY set to date. Here is the code that works.

SELECT * FROM MY_TABLE
  WHERE EXPIRE_DATE >= TO_DATE('2020/01/13','yyyy/mm/dd')
  AND EXPIRE_DATE <= TO_DATE('2020/04/19','yyyy/mm/dd')

I tried to use BETWEEN without TO_DATE and just use my dates but I received an error.

To recap, even though the data type for this is ALREADY date, it seems I have to use TO_DATE to pull my data when I want to filter. Is there something I am missing? Here is my error when I try filter my data without using TO_DATE.

Body:
You don't need to use TO_DATE, instead you can use a DATE literal:

SELECT *
FROM   MY_TABLE
WHERE  EXPIRE_DATE >= DATE '2020/01/13'
AND    EXPIRE_DATE <= DATE '2020/04/19'

Or, if your NLS_DATE_FORMAT session parameter matches YYYY/MM/DD then you can insert the values as strings and rely on implicit string conversion (don't do this though):

ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY/MM/DD';

SELECT *
FROM   MY_TABLE
WHERE  EXPIRE_DATE >= '2020/01/13'
AND    EXPIRE_DATE <= '2020/04/19'

But it is not good practice to rely on the NLS_DATE_FORMAT as ANY user can change their own value at ANY time so your query can randomly fail when users start changing these values.


问:
JAVA: What are the advantages of an InvocationHandler over an implementation of an Interface?
In class today, we were talking about reflection in Java programming. A part of the lesson today was about using InvocationHandlers in Java, rather than just implementing an interface.
When I asked the teacher what the advantages were of using an invocation handler, there wasn't a clear answer.
So let's say we have an interface Plugin

```<code>public interface Plugin {
    void calculate(double a, double b);
    String getCommand();
}
</code>```

you can easily implement this interface in a class Multiply

```<code>public class Multiply implements Plugin {
    @Override
    public void calculate(double a, double b){
         return a * b;
    }

    @Override
    public String getCommand(){
         return "*";
    }
}
</code>```

Then why would I prefer another implementation using an InvocationHandler?

```<code> public class MyMock {
     public static Object createMock(Class myClass) {
         InvocationHandler handler = new MyInvocationHandler();
         Object result = Proxy.newProxyInstance(myClass.getClassLoader(), new Class[]{myClass}, handler);
         return result;
     }
 }
</code>```

Thanks in advance :)

答:
As per a more specific or real-world example, you may run into these kind of reflection usages more using a third-party or open-source API. A very popular example of this would be minecraft, specifically Bukkit/Spigot.

This api is used to write plugins, which the main server then loads and runs. This means you're not 100% in control of some of the code that exists in that codebase, inviting solutions using reflection. Specifically, when you want to intercept calls being made in the API (or even another plugin's API, e.g. Vault for those familiar), you may look to use a Proxy.

We'll stick with the minecraft example, but we're parting from bukkit's api here (and pretending it's not accepting PRs). Say there's a part of the API that just doesn't quite work the way you need.

```<code>public interface Player {
    //This method handles all damage! Hooray!
    public void damagePlayer(Player source, double damage);
}
</code>```

This is great, but if we want to code something where we could find out if a player was damaged (maybe to make cool effects?), we'd need to modify the source (not possible for distributed plugins), or we'd need to find a way to figure out when #damagePlayer has been called and with what values. So in comes a Proxy:

```<code>public class PlayerProxy implements IvocationHandler {

    private final Player src;

    public PlayerProxy(Player src) {
        this.src = src;
    }

    public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
        //Proceed to call the original Player object to adhere to the API
        Object back = m.invoke(this.src, args);
        if (m.getName().equals("damagePlayer") && args.length == 2) {
            //Add our own effects!
            //Alternatively, add a hook so you can register multiple things here, and avoid coding directly inside a Proxy
            if (/* 50% random chance */) {
                //double damage!
                args[1] = (double) args[1] * 2;
                //or perhaps use `source`/args[0] to add to a damage count?
            }
        }
    }
}
</code>```

With our Proxy, we've effectively created a fake Player class, one which will simply call the methods in place for Player. If our PlayerProxy is invoked with myPlayerProxy.someOtherMethod(...), then it will happily pass along a call to myPlayerProxy.src.someOtherMethod(...) via reflection (the m#invoke in the method above).

Simply put, you hot-potato the objects in the library to suit your needs:

```<code>//we'll use this to demonstrate "replacing" the player variables inside of the server
Map<String, Player> players = /* a reflected instance of the server's Player objects, mapped by name. Convenient! */;
players.replaceAll((name, player) ->
    (PlayerProxy) Proxy.newProxyInstance(/* class loader */, new Class<?>[]{Player.class}, new PlayerProxy(player)));
</code>```

InvocationHandler can handle multiple interfaces too. By using a generic Object to pass along the invocations, you can then listen to a variety of different methods in the API all within the same Proxy instance.

Body:
In class today, we were talking about reflection in Java programming. A part of the lesson today was about using InvocationHandlers in Java, rather than just implementing an interface.
When I asked the teacher what the advantages were of using an invocation handler, there wasn't a clear answer.
So let's say we have an interface Plugin

public interface Plugin {
    void calculate(double a, double b);
    String getCommand();
}

you can easily implement this interface in a class Multiply

public class Multiply implements Plugin {
    @Override
    public void calculate(double a, double b){
         return a * b;
    }

    @Override
    public String getCommand(){
         return "*";
    }
}

Then why would I prefer another implementation using an InvocationHandler?

 public class MyMock {
     public static Object createMock(Class myClass) {
         InvocationHandler handler = new MyInvocationHandler();
         Object result = Proxy.newProxyInstance(myClass.getClassLoader(), new Class[]{myClass}, handler);
         return result;
     }
 }

Thanks in advance :)

Body:
As per a more specific or real-world example, you may run into these kind of reflection usages more using a third-party or open-source API. A very popular example of this would be minecraft, specifically Bukkit/Spigot.

This api is used to write plugins, which the main server then loads and runs. This means you're not 100% in control of some of the code that exists in that codebase, inviting solutions using reflection. Specifically, when you want to intercept calls being made in the API (or even another plugin's API, e.g. Vault for those familiar), you may look to use a Proxy.

We'll stick with the minecraft example, but we're parting from bukkit's api here (and pretending it's not accepting PRs). Say there's a part of the API that just doesn't quite work the way you need.

public interface Player {
    //This method handles all damage! Hooray!
    public void damagePlayer(Player source, double damage);
}

This is great, but if we want to code something where we could find out if a player was damaged (maybe to make cool effects?), we'd need to modify the source (not possible for distributed plugins), or we'd need to find a way to figure out when #damagePlayer has been called and with what values. So in comes a Proxy:

public class PlayerProxy implements IvocationHandler {

    private final Player src;

    public PlayerProxy(Player src) {
        this.src = src;
    }

    public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
        //Proceed to call the original Player object to adhere to the API
        Object back = m.invoke(this.src, args);
        if (m.getName().equals("damagePlayer") && args.length == 2) {
            //Add our own effects!
            //Alternatively, add a hook so you can register multiple things here, and avoid coding directly inside a Proxy
            if (/* 50% random chance */) {
                //double damage!
                args[1] = (double) args[1] * 2;
                //or perhaps use `source`/args[0] to add to a damage count?
            }
        }
    }
}

With our Proxy, we've effectively created a fake Player class, one which will simply call the methods in place for Player. If our PlayerProxy is invoked with myPlayerProxy.someOtherMethod(...), then it will happily pass along a call to myPlayerProxy.src.someOtherMethod(...) via reflection (the m#invoke in the method above).

Simply put, you hot-potato the objects in the library to suit your needs:

//we'll use this to demonstrate "replacing" the player variables inside of the server
Map<String, Player> players = /* a reflected instance of the server's Player objects, mapped by name. Convenient! */;
players.replaceAll((name, player) ->
    (PlayerProxy) Proxy.newProxyInstance(/* class loader */, new Class<?>[]{Player.class}, new PlayerProxy(player)));

InvocationHandler can handle multiple interfaces too. By using a generic Object to pass along the invocations, you can then listen to a variety of different methods in the API all within the same Proxy instance.


问:
debug=true in web.config = BAD thing?
We're seeing lots of virtual memory fragmentation and out of memory errors and then it hits the 3GB limit.

The compilation debug is set to true in the web.config but I get different answers from everyone i ask, does debug set to true cause each aspx to compile into random areas of ram thus fragmenting that ram and eventually causing out of memory problems?

答:
Scott Guthrie (manager of the ASP.NET development team) has an interesting post about it.

The most important points why you should not leave debug="true" are:

The compilation of ASP.NET pages takes longer (since some batch optimizations are disabled)

Code can execute slower (since some additional debug paths are enabled)

Much more memory is used within the application at runtime

Scripts and images downloaded from the WebResources.axd handler are not cached by the browser, resulting in more requests between
  client and server

He also mentions the flag <deployment retail=”true”/> in machine.config, which allows to globally override the debug="true" flag of all applications running on a machine (e.g. on a production server).

Update: deploying web apps with debug="true" is still bad, as you can read in Scott Hanselman's recent blog post:

Here's why debug="true" is bad. Seriously, we're not kidding.

Overrides request execution timeout making it effectively infinite

Disables both page and JIT compiler optimizations

In 1.1, leads to excessive memory usage by the CLR for debug information tracking

In 1.1, turns off batch compilation of dynamic pages, leading to 1 assembly per page.

For VB.NET code, leads to excessive usage of WeakReferences (used for edit and continue support).

An important note: Contrary to what is sometimes believed, setting
  retail="true" in a  element is not a direct antidote to
  having debug="true"!

OwnerDisplayName: MateloT

LastEditorDisplayName: ScarletGarden

ContentLicense: CC BY-SA 2.5

Title: debug=true in web.config = BAD thing?

OwnerDisplayName: Martin

LastEditorDisplayName: Martin


问:
Java: searching inside zips inside zips
I've only fairly recently begun working with zip files in java.  All seems to be going to plan pretty well so far but I have got one last roadblock: nested zips.

I'm trying to search for files with a particular extension so they can be read as text files.   So far I can quite happily read files inside zip file but I know that there are some files inside zips nested inside other zips.

Is there a way to search create a ZipFile object out of a ZipEntry without needing to decompress the file?

No code sample since it's not directly a code problem.

K.Barad

答: ZipInputStream wraps a stream in a filter that unzips the data.  So when you find a ZipEntry that's a nested zip file, you need to wrap the stream you're using in a new ZipInputStream to translate the data.  This can be done to whatever depth you need.  </p>

Title: Java: searching inside zips inside zips


问:
How to remove specific part of legend (seaborn, scatterplot)
I am using a seaborn scatterplot and just started using different point sizes.

```<code>sns.scatterplot(x='X [um]', y='Y [um]', hue='label', size='size', data=data)
</code>```

All works perfectly but I'd like to remove the 'size' from the legend seen in picture:

The upper part with CH1, etc. shall remain the same but I'd want the lower part where the sizes are listed to vanish.

答:
I use the get_legend_handles_labels() functionality to index the labels. Using indexing, I ensure that the final printed image only contains the first 13 labels in your legend.</p>

```<code> g = sns.scatterplot(x='X [um]', y='Y [um]', hue='label', size='size', data=data)
    h,l = g.get_legend_handles_labels()
    plt.legend(h[0:13],l[0:13],bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.show(g)
</code>```

Body:
I am using a seaborn scatterplot and just started using different point sizes.

sns.scatterplot(x='X [um]', y='Y [um]', hue='label', size='size', data=data)

All works perfectly but I'd like to remove the 'size' from the legend seen in picture:

The upper part with CH1, etc. shall remain the same but I'd want the lower part where the sizes are listed to vanish.

Body:
I use the get_legend_handles_labels() functionality to index the labels. Using indexing, I ensure that the final printed image only contains the first 13 labels in your legend.

 g = sns.scatterplot(x='X [um]', y='Y [um]', hue='label', size='size', data=data)
    h,l = g.get_legend_handles_labels()
    plt.legend(h[0:13],l[0:13],bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.show(g)


问:
missing private key in the distribution certificate on keychain
I have the following problem which I could not find a solution for anywhere. Basically, we have a company developer account (not enterprise) and so in order to submit our app, I requested from our team lead to send me the distribution certificate and create and send me a distribution provisioning profile.

With the developer profile, everything works good, but when I installed the cert and the provisioning profile, I did not see the distribution profile on Xcode, and nor do I have a private key under the dist cert in the keychain.

Does anyone know how to solve this? I read in diff places that I will need to revoke the certificate and create a new one, but I can't really do that since we have a bunch of apps in the company and I can't revoke it for everyone.

答:
Just to shed some light on this.

After I deleted my p12 certificate from Keychain. I re-downloaded my own certificate from Apple developer portal.

I was only able to download the certificate. But to sign you need the private key as well. So you either:

export both private key and certificate from Keychain to get it.

Upload a Certificate Signing Request and generate new certificates

That certificate by itself has no value for signing purposes. My guess is that the private key is created by keychain the moment you 'request a certificate from a certificate authority' but isn't shown to you until you add its matching certificate.


问:
How to move elements in a bootstrap grid div
CSS:

```<code>  border: 5px solid red;
}

#menu li{
  font-size: 25px;
  display:inline;
}
</code>```

HTML:

```<code><div class="container-fluid">
  <div class="row">
    <div class="col-lg-2" id="menu">
      <ul class ="Menuitems">
        <li>The Hub</li>
          <li>FAQ</li>
        </ul>
      </div>
</code>```

I am attempting to move the text in the li tags to the centre of the div. I cannot figure out the CSS to do so and I don't wish to use "position relative" "top: 5px" because it is bad practise and will mess up the responsive design element of the project. Text align is also not possible as the div is not large when it is full screen, see code pen for information

https://codepen.io/mdot700/pen/bGEGwLa

答:
Found this with bootstrap

Source : https://www.codeply.com/go/bp/6COUMfNrEU

```<code><div class="d-flex">
  <ul class="list-inline mx-auto justify-content-center">
    <li class="list-block-item">Item 1</li>
    <li class="list-block-item">Item 2</li>
    <li class="list-block-item">Item 3</li>
    <li class="list-block-item">Item 4</li>
    <li class="list-block-item">Item 5</li>
  </ul>
</div>
</code>```

Body:
CSS:

  border: 5px solid red;
}

#menu li{
  font-size: 25px;
  display:inline;
}

HTML:

The Hub

FAQ

I am attempting to move the text in the li tags to the centre of the div. I cannot figure out the CSS to do so and I don't wish to use "position relative" "top: 5px" because it is bad practise and will mess up the responsive design element of the project. Text align is also not possible as the div is not large when it is full screen, see code pen for information

https://codepen.io/mdot700/pen/bGEGwLa

Body:
Found this with bootstrap

Source : https://www.codeply.com/go/bp/6COUMfNrEU

<div class="d-flex">
  <ul class="list-inline mx-auto justify-content-center">
    <li class="list-block-item">Item 1</li>
    <li class="list-block-item">Item 2</li>
    <li class="list-block-item">Item 3</li>
    <li class="list-block-item">Item 4</li>
    <li class="list-block-item">Item 5</li>
  </ul>
</div>


问:
React native state not updating function
React native state not updating. Location in alert returns empty.
Help me please</p>

```<code>function Home({ route, navigation }) {

const [location, setLocation] = useState('');

const _appStart = () => {
_location();
}

const _location = () => {
setLocation("Konum Ekle");
alert(location);
}

React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
_appStart();
});
</code>```

答:
try this

const _location = useCallback(()=>{
    setLocation('Hi')
  },console.warn(location)
)
```

<p>instead of</p>

<pre class="lang-js prettyprint-override"><code>const _location = () => {
  setLocation("Konum Ekle");
  alert(location);
}
</code>```

Basically setState is asynchronous. So call your alert in callback of setLocation, so once setLocation is complete your alert will comes in action.

Body:
React native state not updating. Location in alert returns empty.
Help me please

function Home({ route, navigation }) {

const [location, setLocation] = useState('');

const _appStart = () => {
_location();
}

const _location = () => {
setLocation("Konum Ekle");
alert(location);
}

React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
_appStart();
});

Body:
try this

const _location = useCallback(()=>{
    setLocation('Hi')
  },console.warn(location)
)

instead of

const _location = () => {
  setLocation("Konum Ekle");
  alert(location);
}

Basically setState is asynchronous. So call your alert in callback of setLocation, so once setLocation is complete your alert will comes in action.


问:
Running perl-script kpcli via cron failed
I'd like to run a script using kpcli (http://kpcli.sourceforge.net/) via cronjob. All works fine when running it interactively.

When running it the following minimum example via cronjob I get the following error-message.

```<code>46 22 * * *     myuser /usr/local/bin/kpcli --command "vers"
</code>```

Here the error message

```<code>No usable Term::ReadLine::* modules found.
This list was tried:
 * Term::ReadLine::Gnu
 * Term::ReadLine::Perl
 * Term::ReadLine::Perl5
For more information, read the documentation: perldoc kpcli
</code>```

Here is the output when running it via command line

```<code>kpcli: 3.4
Perl: v5.26.1
Operating system: linux ("Ubuntu 18.04.4 LTS")
ReadLine being used: Term::ReadLine::Gnu

Pivotal Perl Modules for kpcli
 * File::KeePass: 2.03
 * Term::ShellUI: 0.92
 * Term::ReadKey: 2.37
 * Term::ReadLine: 1.16
 * Capture::Tiny: 0.48
 * Clipboard: 0.13
 * Math::Random::ISAAC: 1.003
 * Term::ReadLine::Gnu: 1.35
 * Authen::OATH: not installed (optional)
 * Sub::Install: not installed (optional)
</code>```

I also tried to set the variable

```<code>PERL5LIB=/usr/lib/x86_64-linux-gnu/perl5/5.26
</code>```

But nothing changed :(

What's wrong?

答:
The PERL5LIB is a user's environment variable; the system's utility cron knows nothing about it.

Further, what you invoke from crontab mostly runs "out of" your home directory; this can depend on the system but it is generally not from where the script is.  So then that place is the script's working directory.

Clearly the module Term::ReadLine::Gnu is installed in a non-standard location and when the script runs via cron it altogether cannot find that module (and perhaps yet others).

There are various ways about this

Set PERL5LIB right on the command line in the crontab

```<code>  SHELL=/bin/bash
  MAILTO=your@email.address

  * * * * * PERL5LIB=/path/as/needed  /full/path/script.pl arguments
</code>```

The environment variables I set in the beginning are often already set to reasonable values (but they may not be). Consider what other environment may be needed, if any.  See your system's documentation  for crontab(5) and test

Change to a directory from which the script is known to work

```<code>  * * * * * (cd /path/to/where/it/works; ./script.pl arguments)
</code>```

Make the script itself change to the desired working directory by adding to it

```<code>  use FindBin qw($RealBin);
  BEGIN {
      chdir $RealBin or die "Can't chdir to $RealBin: $!";
  };
</code>```

This must be done before any use statements that need the script to already be in the particular directory; perhaps all those that refer to non-standard locations.

The solution where the order of compile-time statements matters can be fragile here. On the other hand, in that way the working directory is set up right in the script and sometimes that is precisely what is needed.

There is certainly a rationale for doing both, change the working directory and set PERL5LIB

```<code>* * * * * (cd /full/path; PERL5LIB=path1:path2:...  ./script.pl arguments)
</code>```

Body:
I'd like to run a script using kpcli (http://kpcli.sourceforge.net/) via cronjob. All works fine when running it interactively.

When running it the following minimum example via cronjob I get the following error-message.

46 22 * * *     myuser /usr/local/bin/kpcli --command "vers"

Here the error message

No usable Term::ReadLine::* modules found.
This list was tried:
 * Term::ReadLine::Gnu
 * Term::ReadLine::Perl
 * Term::ReadLine::Perl5
For more information, read the documentation: perldoc kpcli

Here is the output when running it via command line

kpcli: 3.4
Perl: v5.26.1
Operating system: linux ("Ubuntu 18.04.4 LTS")
ReadLine being used: Term::ReadLine::Gnu

Pivotal Perl Modules for kpcli
 * File::KeePass: 2.03
 * Term::ShellUI: 0.92
 * Term::ReadKey: 2.37
 * Term::ReadLine: 1.16
 * Capture::Tiny: 0.48
 * Clipboard: 0.13
 * Math::Random::ISAAC: 1.003
 * Term::ReadLine::Gnu: 1.35
 * Authen::OATH: not installed (optional)
 * Sub::Install: not installed (optional)

I also tried to set the variable

PERL5LIB=/usr/lib/x86_64-linux-gnu/perl5/5.26

But nothing changed :(

What's wrong?

Body:
The PERL5LIB is a user's environment variable; the system's utility cron knows nothing about it.

Further, what you invoke from crontab mostly runs "out of" your home directory; this can depend on the system but it is generally not from where the script is.  So then that place is the script's working directory.

Clearly the module Term::ReadLine::Gnu is installed in a non-standard location and when the script runs via cron it altogether cannot find that module (and perhaps yet others).

There are various ways about this

Set PERL5LIB right on the command line in the crontab

  SHELL=/bin/bash
  MAILTO=your@email.address

  * * * * * PERL5LIB=/path/as/needed  /full/path/script.pl arguments

The environment variables I set in the beginning are often already set to reasonable values (but they may not be). Consider what other environment may be needed, if any.  See your system's documentation  for crontab(5) and test

Change to a directory from which the script is known to work

  * * * * * (cd /path/to/where/it/works; ./script.pl arguments)

Make the script itself change to the desired working directory by adding to it

  use FindBin qw($RealBin);
  BEGIN {
      chdir $RealBin or die "Can't chdir to $RealBin: $!";
  };

This must be done before any use statements that need the script to already be in the particular directory; perhaps all those that refer to non-standard locations.

The solution where the order of compile-time statements matters can be fragile here. On the other hand, in that way the working directory is set up right in the script and sometimes that is precisely what is needed.

There is certainly a rationale for doing both, change the working directory and set PERL5LIB

* * * * * (cd /full/path; PERL5LIB=path1:path2:...  ./script.pl arguments)


问:
In R how do I create a variable whose contents are based on what is in other variables?
I have a data set which contains a list of treatments (Treatment variable) and then another person has categorised these treatments based on their mechanism of action (Mechanism variable). I want to add another mechanism of action category (Hypothermia) and I am struggling to do so.

I have made a small data frame as an example of some of the treatments and their mechanism categories.

```<code>Treatment <- c("Hypothermia", "CNS-1102", "Hypocapnia", "Dextrorphan", "Mannitol", "Caffeinol")
Mechanism <- c("Other", "Excitotoxicity", "Blood flow", "Excitotoxicity", "Fluid regulation", "Other")
df <- data.frame(Treatment, Mechanism)
</code>```

I'm interested in hypothermia so I want to make a new variable (called Mechanism_extra) which is a copy of Mechanism except it classifies "Hypothermia" as its own category instead of classing "Hypothermia" cases under the "Other" category. My actual data set contains ~8000 entries so I can't just do this manually.
I have tried to do this with mutate from dplyr and with ifelse, but my output just doesn't work.

```<code>df <- mutate(df, Mechanism_extra = ifelse(df$Treatment == "Hypothermia", "Hypothermia", df$Mechanism))
df$Mechanism_extra
</code>```

With the above code I'm trying to say "make a new variable called Mechanism_extra, look at the drugs in Treatment and if you see Hypothermia then put Hypothermia into the new variable, if it doesn't say Hypothermia then just write down the original mechanism of action". However my output looks like this:

[1] "Hypothermia" "2"           "1"           "2"           "3"           "4"

When I want it to look like this:

[1] "Hypothermia" "Excitotoxicity"  "Blood flow"   "Excitotoxicity"  "Fluid regulation"  "Other"

Why are there numbers? Where am I going wrong?

答:
You can make it a tibble instead of a data.frame using dplyr and that will work.

```<code>library(dplyr)

Treatment <- c("Hypothermia", "CNS-1102", "Hypocapnia", "Dextrorphan", "Mannitol", "Caffeinol")
Mechanism <- c("Other", "Excitotoxicity", "Blood flow", "Excitotoxicity", "Fluid regulation", "Other")
df <- tibble(Treatment, Mechanism) # changed this

df %>%
  mutate(Mechanism_extra = if_else(Treatment == "Hypothermia", "Hypothermia", Mechanism))
</code>```

Which is this:

```<code># A tibble: 6 x 3
  Treatment   Mechanism        Mechanism_extra
  <chr>       <chr>            <chr>
1 Hypothermia Other            Hypothermia
2 CNS-1102    Excitotoxicity   Excitotoxicity
3 Hypocapnia  Blood flow       Blood flow
4 Dextrorphan Excitotoxicity   Excitotoxicity
5 Mannitol    Fluid regulation Fluid regulation
6 Caffeinol   Other            Other
</code>```

Body:
I have a data set which contains a list of treatments (Treatment variable) and then another person has categorised these treatments based on their mechanism of action (Mechanism variable). I want to add another mechanism of action category (Hypothermia) and I am struggling to do so.

I have made a small data frame as an example of some of the treatments and their mechanism categories.

Treatment <- c("Hypothermia", "CNS-1102", "Hypocapnia", "Dextrorphan", "Mannitol", "Caffeinol")
Mechanism <- c("Other", "Excitotoxicity", "Blood flow", "Excitotoxicity", "Fluid regulation", "Other")
df <- data.frame(Treatment, Mechanism)

I'm interested in hypothermia so I want to make a new variable (called Mechanism_extra) which is a copy of Mechanism except it classifies "Hypothermia" as its own category instead of classing "Hypothermia" cases under the "Other" category. My actual data set contains ~8000 entries so I can't just do this manually.
I have tried to do this with mutate from dplyr and with ifelse, but my output just doesn't work.

df <- mutate(df, Mechanism_extra = ifelse(df$Treatment == "Hypothermia", "Hypothermia", df$Mechanism))
df$Mechanism_extra

With the above code I'm trying to say "make a new variable called Mechanism_extra, look at the drugs in Treatment and if you see Hypothermia then put Hypothermia into the new variable, if it doesn't say Hypothermia then just write down the original mechanism of action". However my output looks like this:

[1] "Hypothermia" "2"           "1"           "2"           "3"           "4"

When I want it to look like this:

[1] "Hypothermia" "Excitotoxicity"  "Blood flow"   "Excitotoxicity"  "Fluid regulation"  "Other"

Why are there numbers? Where am I going wrong?

Body:
You can make it a tibble instead of a data.frame using dplyr and that will work.

library(dplyr)

Treatment <- c("Hypothermia", "CNS-1102", "Hypocapnia", "Dextrorphan", "Mannitol", "Caffeinol")
Mechanism <- c("Other", "Excitotoxicity", "Blood flow", "Excitotoxicity", "Fluid regulation", "Other")
df <- tibble(Treatment, Mechanism) # changed this

df %>%
  mutate(Mechanism_extra = if_else(Treatment == "Hypothermia", "Hypothermia", Mechanism))

Which is this:

# A tibble: 6 x 3
  Treatment   Mechanism        Mechanism_extra
  <chr>       <chr>            <chr>
1 Hypothermia Other            Hypothermia
2 CNS-1102    Excitotoxicity   Excitotoxicity
3 Hypocapnia  Blood flow       Blood flow
4 Dextrorphan Excitotoxicity   Excitotoxicity
5 Mannitol    Fluid regulation Fluid regulation
6 Caffeinol   Other            Other


问:
send mail to non-registered user (email list) in a queue
I am trying to program a Laravel mailing list with a queue Try to send emails to Non-users, I did a good job with registered users and this is my code:

```<code>        foreach ($emails as  $i=>$item){
            $user = User::where('email',$item)->first();
            if ($i % $mailsCount == 0)$count++;
            if ($user){
                $thisBody = ElzahabyDynamicLaravelString($user,$body,$this->sign);
                $thisSubject = ElzahabyDynamicLaravelString($user,$subject,$this->sign);
                $when = Carbon::now()->addMinutes($every*$count);
                Mail::to($user)
                    ->later($when,new EmailForQueuing($user,$thisBody,$thisSubject,$request->emailTemplate));
            }
        }
</code>```

You can notice later() method, which is responsible for the queue.  but this only works with Mail::to method which only works for registered users.

So, any idea how to send a mailing list with a queue to non-registered emails.

Thanks in advance.

Edit 1

EmailForQueuing() method is a simple Mailable class

答:
the problem was in the Mail::to() method is that it requires name and email.
But I was just sending the email, and I don't have any names!

so
what I did is:

make an object includes [emails(required),name(required),any other thing(optional)]

```<code>$user = (object)[
    'email' => $email,
    'name' => substr($email, 0, strpos($email, '@')), // here we take the name form email (string before "@")
];
</code>```

then send it normally:

```<code>$when = Carbon::now()->addMinutes($every*$count);
Mail::to($user)->later($when,new EmailForQueuing($user,$thisBody,$thisSubject,$request->emailTemplate));
</code>```

Body:
I am trying to program a Laravel mailing list with a queue Try to send emails to Non-users, I did a good job with registered users and this is my code:

        foreach ($emails as  $i=>$item){
            $user = User::where('email',$item)->first();
            if ($i % $mailsCount == 0)$count++;
            if ($user){
                $thisBody = ElzahabyDynamicLaravelString($user,$body,$this->sign);
                $thisSubject = ElzahabyDynamicLaravelString($user,$subject,$this->sign);
                $when = Carbon::now()->addMinutes($every*$count);
                Mail::to($user)
                    ->later($when,new EmailForQueuing($user,$thisBody,$thisSubject,$request->emailTemplate));
            }
        }

You can notice later() method, which is responsible for the queue.  but this only works with Mail::to method which only works for registered users.

So, any idea how to send a mailing list with a queue to non-registered emails.

Thanks in advance.

Edit 1

EmailForQueuing() method is a simple Mailable class

Body:
the problem was in the Mail::to() method is that it requires name and email.
But I was just sending the email, and I don't have any names!

so
what I did is:

make an object includes [emails(required),name(required),any other thing(optional)]

$user = (object)[
    'email' => $email,
    'name' => substr($email, 0, strpos($email, '@')), // here we take the name form email (string before "@")
];

then send it normally:

$when = Carbon::now()->addMinutes($every*$count);
Mail::to($user)->later($when,new EmailForQueuing($user,$thisBody,$thisSubject,$request->emailTemplate));


问:
Is there any tools to help me refactor a method call from using position-based to name-based parameters
I wish to transform code like:

```<code>var p = new Person("Ian", "Smith", 40, 16)
</code>```

To:

```<code>var p = new Person(surname: "Ian", givenName:"Smith", weight:40, age:16)
</code>```

As a first step in making the code more readable,  I am willing to use a 3rd party refactoring tool if need be.

(Please do not tell me to use parameter objects and factor methods etc, these may come later once I can at least read the code!)

答:
Refactor v2001 vol 1.3 claims to be able to do it.

ReSharper has it in it's issues database, but have not commited doing it yet.

Body:
I wish to transform code like:

var p = new Person("Ian", "Smith", 40, 16)

To:

var p = new Person(surname: "Ian", givenName:"Smith", weight:40, age:16)

As a first step in making the code more readable,  I am willing to use a 3rd party refactoring tool if need be.

(Please do not tell me to use parameter objects and factor methods etc, these may come later once I can at least read the code!)


问:
stumped with recaptcha verification step
I hate asking for help.. but I've spent I dunno how many hours trying to figure out how to implement the verification step for this form with recaptcha.

I understand the I need define the private key somewhere, but most of the other guides are using "isset" functions and I just don't at which part of the php to do it.

At the moment, the button shows up and is checkable.. but when I click submit, it sends regardless of whether the box was checked. (Just explaining in case that's helpful.)

Thanks, sorry.

```<code><?php

$to = 'example@caraudioinc.com';
$subject = 'CarAudioInc.com Form Message';

$errName = $errEmail = $errMessage = "";
$name = $email = $pNum = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $pNum = test_input($_POST["pNum"]);
  $message = test_input($_POST["message"]);

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["name"])) {
    $errName = "*Name field is required.";
    } else {
    $name = test_input($_POST["name"]);

        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $errName = "Invaild name.";
        }
    }

    if (empty($_POST["email"])) {
    $errEmail = "*Email field is required.";
        } else {
    $email = test_input($_POST["email"]);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid E-mail.";
        }
    }

    if (empty($_POST["message"])) {
    $errMessage = "*Message field is required.";
        } else {
    $message = test_input($_POST["message"]);
    }

$body = <<<EMAIL

Message from: $name

$message

Phone: $pNum
Email: $email

EMAIL;

$header = "From: $email";

if (!$errName && !$errEmail && !$errMessage ) {
    if($_POST) {

        mail($to, $subject, $body, $header);

        header('Location: /sent');
    }

    }
}
?>

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=1152">
<script src="https://www.google.com/recaptcha/api.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-100617570-1" ></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-100617570-1');
</script>

<!--Google meta tags -->
<title>Car Audio Inc | Contact</title>

<!--fb meta tags -->
<link rel="canonical" href="https://www.caraudioinc.com/contact" />
<link href="css/multiColumnTemplate.css" hreflang="en" rel="stylesheet" type="text/css">
<link rel="icon" href="images/favicon.png" type="image/png">
</head>

<body>
<div class="container">

  <header>
     <div class="primary_header">

    <nav class="secondary_header" id="menu">
      <ul>
     <li><a href="/">HOME</a></li>
        <li><a href="about">ABOUT</a></li>
          <li><a href="services">SERVICES</a></li>
        <li class="current"><a href="contact">CONTACT</a></li>
      </ul>
    </nav>

  </header>

 <div class="contactForm">
  <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"><br>

    <label for="name">Name  </label><span class="error"><?php echo $errName; ?></span><br>
    <input type="text" id="name" name="name" value="<?php echo $name;?>"><br><br>

      <label for="email">Email  </label><span class="error"><?php echo $errEmail; ?></span><br>
    <input type="email" id="email" name="email" value="<?php echo $email;?>"><br><br>

      <label for="pNum">Phone Number (optional)<br></label>
    <input type="tel" id="pNum" name="pNum" value="<?php echo $pNum;?>"><br><br>

      <label for="message">Message  </label><span class="error"><?php echo $errMessage; ?></span><br>
    <textarea id="message" name="message" style="height:100px"><?php echo $message;?></textarea>

     <div class="g-recaptcha" data-sitekey="6LcR-DQUAAAAAB2cXajVPi7lpFEZ_z8vZrS97ZXo"></div><br>

    <input type="submit" value="Submit">
    </form>

  <footer class="secondary_header footer">
    <div class="copyright">© Car Audio Inc 2020, All Rights Reserved.</div>

  </footer>

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

答:
I finally figured it out.

Posting the answer for future n00bs like me, hope it helps someone:

```<code><?php

$to = 'example@caraudioinc.com';
$subject = 'Car Audio Inc Form Message';

$errName = $errEmail = $errMessage = $errCaptcha = "";
$name = $email = $pNum = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $pNum = test_input($_POST["pNum"]);
  $message = test_input($_POST["message"]);

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["name"])) {
    $errName = "*Name field is required.";
    } else {
    $name = test_input($_POST["name"]);

        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $errName = "Invaild name.";
        }
    }

    if (empty($_POST["email"])) {
    $errEmail = "*Email field is required.";
        } else {
    $email = test_input($_POST["email"]);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid E-mail.";
        }
    }

    if (empty($_POST["message"])) {
    $errMessage = "*Message field is required.";
        } else {
    $message = test_input($_POST["message"]);
    }

    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
  {
        $secret = 'insert-your-private-key-here';
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);

  } else {
            $errCaptcha = '*reCAPTCHA failed.';
        }

$body = <<<EMAIL

Message from: $name

$message

Phone: $pNum
Email: $email

EMAIL;

$header = "From: $email";

if (!$errName && !$errEmail && !$errMessage && $responseData->success) {
    if($_POST) {

        mail($to, $subject, $body, $header);

        header('Location: /sent');
    }

    }
}
?>

</code>```

Body:
I hate asking for help.. but I've spent I dunno how many hours trying to figure out how to implement the verification step for this form with recaptcha.

I understand the I need define the private key somewhere, but most of the other guides are using "isset" functions and I just don't at which part of the php to do it.

At the moment, the button shows up and is checkable.. but when I click submit, it sends regardless of whether the box was checked. (Just explaining in case that's helpful.)

Thanks, sorry.

<?php

$to = 'example@caraudioinc.com';
$subject = 'CarAudioInc.com Form Message';

$errName = $errEmail = $errMessage = "";
$name = $email = $pNum = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $pNum = test_input($_POST["pNum"]);
  $message = test_input($_POST["message"]);

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["name"])) {
    $errName = "*Name field is required.";
    } else {
    $name = test_input($_POST["name"]);

        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $errName = "Invaild name.";
        }
    }

    if (empty($_POST["email"])) {
    $errEmail = "*Email field is required.";
        } else {
    $email = test_input($_POST["email"]);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid E-mail.";
        }
    }

    if (empty($_POST["message"])) {
    $errMessage = "*Message field is required.";
        } else {
    $message = test_input($_POST["message"]);
    }

$body = <<<EMAIL

Message from: $name

$message

Phone: $pNum
Email: $email

EMAIL;

$header = "From: $email";

if (!$errName && !$errEmail && !$errMessage ) {
    if($_POST) {

        mail($to, $subject, $body, $header);

        header('Location: /sent');
    }

    }
}
?>

<!doctype html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=1152">

<title>Car Audio Inc | Contact</title>

<link rel="canonical" href="https://www.caraudioinc.com/contact" />
<link href="css/multiColumnTemplate.css" hreflang="en" rel="stylesheet" type="text/css">
<link rel="icon" href="images/favicon.png" type="image/png">

HOME

ABOUT

SERVICES

CONTACT

  <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

    Name  <?php echo $errName; ?>

    <input type="text" id="name" name="name" value="<?php echo $name;?>">

      Email  <?php echo $errEmail; ?>

    <input type="email" id="email" name="email" value="<?php echo $email;?>">

      Phone Number (optional)

    <input type="tel" id="pNum" name="pNum" value="<?php echo $pNum;?>">

      Message  <?php echo $errMessage; ?>

    <textarea id="message" name="message" style="height:100px"><?php echo $message;?></textarea>

    <input type="submit" value="Submit">
    </form>

© Car Audio Inc 2020, All Rights Reserved.

Body:
I finally figured it out.

Posting the answer for future n00bs like me, hope it helps someone:

<?php

$to = 'example@caraudioinc.com';
$subject = 'Car Audio Inc Form Message';

$errName = $errEmail = $errMessage = $errCaptcha = "";
$name = $email = $pNum = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $pNum = test_input($_POST["pNum"]);
  $message = test_input($_POST["message"]);

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["name"])) {
    $errName = "*Name field is required.";
    } else {
    $name = test_input($_POST["name"]);

        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $errName = "Invaild name.";
        }
    }

    if (empty($_POST["email"])) {
    $errEmail = "*Email field is required.";
        } else {
    $email = test_input($_POST["email"]);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid E-mail.";
        }
    }

    if (empty($_POST["message"])) {
    $errMessage = "*Message field is required.";
        } else {
    $message = test_input($_POST["message"]);
    }

    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
  {
        $secret = 'insert-your-private-key-here';
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);

  } else {
            $errCaptcha = '*reCAPTCHA failed.';
        }

$body = <<<EMAIL

Message from: $name

$message

Phone: $pNum
Email: $email

EMAIL;

$header = "From: $email";

if (!$errName && !$errEmail && !$errMessage && $responseData->success) {
    if($_POST) {

        mail($to, $subject, $body, $header);

        header('Location: /sent');
    }

    }
}
?>


问:
How do I set a default image to a canvas?
I have a PNG image (in my database) that I want to load into my page in my canvas. I have no idea how to do it. I couldn't figure out how to load the image as a ImageBitmap or anything compatible with canvas. How do I give canvas the bytes and tell it that it's using the png format/set the mime to png?</p>

答:
HTML

```<code><img id="myImage" src="imageSrc">
<canvas id ="myCanvas" width="width" height="height"></canvas>
</code>```

JS

```<code>var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("myImage");
ctx.drawImage(img, 0, 0);
</code>```

This is the simplest way. The drawImage() method can take multiple image sources, not just an HTML image element. For example, you do not need to put the image in the DOM as I demonstrated. I recommend you read the documentation: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage

Body:
HTML

<img id="myImage" src="imageSrc">
<canvas id ="myCanvas" width="width" height="height"></canvas>

JS

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("myImage");
ctx.drawImage(img, 0, 0);

This is the simplest way. The drawImage() method can take multiple image sources, not just an HTML image element. For example, you do not need to put the image in the DOM as I demonstrated. I recommend you read the documentation: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage


问:
How do I avoid NaN?
I understand it's because the program thinks I'm dividing by O, but I'm not sure how to fix it in the program. The program works fine, though. It outputs the average the way I want it to, but I would like it to output <0.0> when there are no integers being sent from the main method.

```<code>public class Statistics {

private int count;
private int sum;
//private double average;

public Statistics() {
    this.count = 0;

}

public void addNumber(int number) {
    sum += number;

    count++;
}

public int getCount() {
    return this.count;
}

public int sum() {

    return sum;
}

public double average() {
    double average=0;
    average = this.count/(double)sum;
    return average;
}

public static void main(String[] args) {
    Statistics statistics = new Statistics();
    //statistics.addNumber(3);
    //statistics.addNumber(5);
   // statistics.addNumber(1);
    //statistics.addNumber(2);
   System.out.println("Count: " + statistics.getCount());
    System.out.println("Sum: " + statistics.sum());
    System.out.println("Average: " + statistics.average());
}
</code>```

}

How can I re-write this average section to avoid that?

答:
First of all, your average function is not working right. avg = sum / count but your function does avg = count / sum. For printing when count is zero, check it with an if.

public double average() {
    // If there is nothing to average return zero
    if (this.count == 0) return 0.0;

    double average = 0;
    average = this.sum / (double)this.count;
    return average;
}
```

Title: How do I avoid NaN?

Body:
I understand it's because the program thinks I'm dividing by O, but I'm not sure how to fix it in the program. The program works fine, though. It outputs the average the way I want it to, but I would like it to output <0.0> when there are no integers being sent from the main method.

public class Statistics {

private int count;
private int sum;
//private double average;

public Statistics() {
    this.count = 0;

}

public void addNumber(int number) {
    sum += number;

    count++;
}

public int getCount() {
    return this.count;
}

public int sum() {

    return sum;
}

public double average() {
    double average=0;
    average = this.count/(double)sum;
    return average;
}

public static void main(String[] args) {
    Statistics statistics = new Statistics();
    //statistics.addNumber(3);
    //statistics.addNumber(5);
   // statistics.addNumber(1);
    //statistics.addNumber(2);
   System.out.println("Count: " + statistics.getCount());
    System.out.println("Sum: " + statistics.sum());
    System.out.println("Average: " + statistics.average());
}

}

How can I re-write this average section to avoid that?


问:
android internet connection
I am using the following code to see if user have internet connection (WIFI or 3G or Edge).
Why does some users get "No internet connection" when they do have it?</p>

```<code>try{
  ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            State wifi = connec.getNetworkInfo(1).getState();

  if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
    connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
    wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING ) {
    ///HAVE CONNECTION CODE////
            }else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||   connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED   ) {
    ///NO CONNECTION CODE///
  }
} catch (Throwable t){
///NO CONNECTION CODE///
}
</code>```

答:
My guess would be that connec.getNetworkInfo(0) and connec.getNetworkInfo(1) aren't always valid for the wifi/3g network interfaces. Try checking the 'TypeName' of the interfaces. I use this code...

```<code>public boolean HaveNetworkConnection() {
    boolean HaveConnectedWifi = false;
    boolean HaveConnectedMobile = false;

    ConnectivityManager connManager = (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = connManager.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        Log.d("HaveNetworkConnection()", ni.toString());
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                HaveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                HaveConnectedMobile = true;
    }
    return HaveConnectedWifi || HaveConnectedMobile;
}
</code>```

Title: android internet connection

Body:
I am using the following code to see if user have internet connection (WIFI or 3G or Edge).
Why does some users get "No internet connection" when they do have it?

try{
  ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            State wifi = connec.getNetworkInfo(1).getState();

  if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
    connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
    wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING ) {
    ///HAVE CONNECTION CODE////
            }else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||   connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED   ) {
    ///NO CONNECTION CODE///
  }
} catch (Throwable t){
///NO CONNECTION CODE///
}

Body:
My guess would be that connec.getNetworkInfo(0) and connec.getNetworkInfo(1) aren't always valid for the wifi/3g network interfaces. Try checking the 'TypeName' of the interfaces. I use this code...

public boolean HaveNetworkConnection() {
    boolean HaveConnectedWifi = false;
    boolean HaveConnectedMobile = false;

    ConnectivityManager connManager = (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = connManager.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        Log.d("HaveNetworkConnection()", ni.toString());
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                HaveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                HaveConnectedMobile = true;
    }
    return HaveConnectedWifi || HaveConnectedMobile;
}


问:
Using chart.js, how do I align bars instead of centering them when there are only a few bars to display?
As some background: I have a horizontal bar chart with a dynamic number of bars. I have set min and max bar widths for each of the datasets.

By default, chart.js aligns the bars in the center of chart. Instead I would like to align the bars to the left (or in the top as I am using a horizontal bar chart).

Thinking of the bars as HTML elements, this would be the equivalent of applying the css: float:left to each bar. Is there anyway to do this in chart.js? I still want the axes to extend to the end of the container, it just looks funny to have only a couple bars with a ton of space in between them (I also don't want really fat bars).

Thanks for any help!

Note: This is a duplicate of 56361398

EDIT: See codepen for example (one bar is centered in the chart, I would like it aligned to the left, next to the y axis).

答:
I have checked the settings and there is no setting to left-align the bar charts. I doubt it is easy to implement since Chart.JS is a canvas under the hood.

Also, technically speaking the chart is in fact "left-aligned" however it is just one slim bar. The bar could very well use the whole bar space in red:

The best workaround is to create empty labels that will later be populated if needed.

If you need to add more bars just check if a label name is "" (empty) and then overwrite it. Otherwise push the new label.

Example: https://codepen.io/adelriosantiago/pen/vYLYXPx?editors=0110


问:
Choose a table to copy from a Word file into an Excel file
I have a word file with 7 tables and I want to copy one of them into an excel file. But I’d like to choose each time I run the macro which table I want to copy as I’ll have different word files with different number of tables and a different table to copy.

By now I have this code that copies the word table you have selected at that moment:

```<code>    Dim wrdTbl As Table
    Dim RowCount As Long, ColCount As Long, i As Long, j As Long
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object

    Set wrdTbl = Selection.Tables(1)
    ColCount = wrdTbl.Columns.Count
    RowCount = wrdTbl.Rows.Count

    Set oXLApp = CreateObject("Excel.Application")

    oXLApp.Visible = False

    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xlsx")
    Set oXLws = oXLwb.Sheets(1)

    For i = 1 To RowCount
        For j = 1 To ColCount
            Debug.Print wrdTbl.Cell(i, j).Range.Text

           With oXLws
                .Cells(1, 1).Value = wrdTbl.Cell(i, j).Range.Text
            End With
        Next
    Next
    oXLwb.Close savechanges:=True
    Set oXLws = Nothing
    Set oXLwb = Nothing
    oXLApp.Quit
    Set oXLApp = Nothing

    MsgBox "DONE"
End Sub
</code>```

PS: Another thing I don’t understand is why I get a strange mark in each cell of the table when I get to copy it to Excel. I get like that “[]” which I do not understand why it appears because it is not in the word table. Sorry for the bad quality of the photo, I had to do it with my phone.

答:
You could, for example, replace:

```<code>Set wrdTbl = Selection.Tables(1)
</code>```

with:

```<code>Set wrdTbl = ActiveDocument.Tables(InputBox("Table # to copy? There are " & ActiveDocument.Tables.Count & " tables to choose from."))
</code>```

To eliminate the end-of-cell marker from Word you could use:

.Cells(1, 1).Value = Split(wrdTbl.Cell(i, j).Range.Text, vbCr)(0)

Body:
I have a word file with 7 tables and I want to copy one of them into an excel file. But I’d like to choose each time I run the macro which table I want to copy as I’ll have different word files with different number of tables and a different table to copy.

By now I have this code that copies the word table you have selected at that moment:

    Dim wrdTbl As Table
    Dim RowCount As Long, ColCount As Long, i As Long, j As Long
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object

    Set wrdTbl = Selection.Tables(1)
    ColCount = wrdTbl.Columns.Count
    RowCount = wrdTbl.Rows.Count

    Set oXLApp = CreateObject("Excel.Application")

    oXLApp.Visible = False

    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xlsx")
    Set oXLws = oXLwb.Sheets(1)

    For i = 1 To RowCount
        For j = 1 To ColCount
            Debug.Print wrdTbl.Cell(i, j).Range.Text

           With oXLws
                .Cells(1, 1).Value = wrdTbl.Cell(i, j).Range.Text
            End With
        Next
    Next
    oXLwb.Close savechanges:=True
    Set oXLws = Nothing
    Set oXLwb = Nothing
    oXLApp.Quit
    Set oXLApp = Nothing

    MsgBox "DONE"
End Sub

PS: Another thing I don’t understand is why I get a strange mark in each cell of the table when I get to copy it to Excel. I get like that “[]” which I do not understand why it appears because it is not in the word table. Sorry for the bad quality of the photo, I had to do it with my phone.

Body:
You could, for example, replace:

Set wrdTbl = Selection.Tables(1)

with:

Set wrdTbl = ActiveDocument.Tables(InputBox("Table # to copy? There are " & ActiveDocument.Tables.Count & " tables to choose from."))

To eliminate the end-of-cell marker from Word you could use:

.Cells(1, 1).Value = Split(wrdTbl.Cell(i, j).Range.Text, vbCr)(0)


问:
How to submit/update form without submit click in rails?
generated a recruitment model that has one_to_many association with attendance model. now i want to submit/update form whenever user changes attendance dropdown. here is my code-

```<code>  <table>
    <thead>
      <tr>
        <th>Name</th>

        <% (1..(Time.days_in_month Time.now.strftime("%m").to_i)).each do |date| %>
              <th><%= date %></th>
        <% end %>

      </tr>
    </thead>

    <tbody>
      <% @recruitment.each do |recruitment| %>
        <tr>
            <td><%= recruitment.name %></td>

            <% (1..(Time.days_in_month Time.now.strftime("%m").to_i)).each do |date| %>
                  <td>

                    <%= form_for Attendance.new do |f| %>
                        <div>
                          <div class="wrapper-class">
                              <%= f.select :status, [['P', 1], ['A', 2], ['H', 3]]%>
                          </div>

                          <div>
                            <%= f.hidden_field :attendance_date, value: (Time.now.strftime("%Y").to_s+"-"+Time.now.strftime("%m").to_s+"-"+date.to_s)%>
                          </div>

                            <%=f.hidden_field :recruitment_id, value: recruitment.id%>
                          </div>
                          <div>
                            <%= f.submit 'Submit', :class => 'button primary small float-right' %>
                          </div>

                    <% end %>
                  </td>
            <% end %>

</code>```

i dont want to click submit on every time i change input select.

i tried this-

```<code>  <%= f.select :status, [['P', 1], ['A', 2], ['H', 3]], :onchange => 'this.form.submit()' %>
</code>```

but this is not working.

答:
I suspect if you inspect the HTML code this is generating, you won't see an onchange attribute for your select field.

Like this

The select method is expecting a hash of options before it gets to html_options, so to fix this, we do

```<code><%= f.select :status, [['P', 1], ['A', 2], ['H', 3]], {}, :onchange => 'this.form.submit()' %>
</code>```

If you need to specify any other HTML options such as a class or style, you would do so like this

```<code><%= f.select :status, [['P', 1], ['A', 2], ['H', 3]], {}, { onchange: 'this.form.submit()', class: 'some-css-class' } %>
</code>```

Note the curly-brackets around the onchange and class attributes.

Relevant documentation: https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Body:
generated a recruitment model that has one_to_many association with attendance model. now i want to submit/update form whenever user changes attendance dropdown. here is my code-

        Name

        <% (1..(Time.days_in_month Time.now.strftime("%m").to_i)).each do |date| %>
              <%= date %>
        <% end %>

      <% @recruitment.each do |recruitment| %>

            <%= recruitment.name %>

            <% (1..(Time.days_in_month Time.now.strftime("%m").to_i)).each do |date| %>

                    <%= form_for Attendance.new do |f| %>

                              <%= f.select :status, [['P', 1], ['A', 2], ['H', 3]]%>

                            <%= f.hidden_field :attendance_date, value: (Time.now.strftime("%Y").to_s+"-"+Time.now.strftime("%m").to_s+"-"+date.to_s)%>

                            <%=f.hidden_field :recruitment_id, value: recruitment.id%>

                            <%= f.submit 'Submit', :class => 'button primary small float-right' %>

                    <% end %>

            <% end %>

i dont want to click submit on every time i change input select.

i tried this-

  <%= f.select :status, [['P', 1], ['A', 2], ['H', 3]], :onchange => 'this.form.submit()' %>

but this is not working.

Body:
I suspect if you inspect the HTML code this is generating, you won't see an onchange attribute for your select field.

Like this

The select method is expecting a hash of options before it gets to html_options, so to fix this, we do

<%= f.select :status, [['P', 1], ['A', 2], ['H', 3]], {}, :onchange => 'this.form.submit()' %>

If you need to specify any other HTML options such as a class or style, you would do so like this

<%= f.select :status, [['P', 1], ['A', 2], ['H', 3]], {}, { onchange: 'this.form.submit()', class: 'some-css-class' } %>

Note the curly-brackets around the onchange and class attributes.

Relevant documentation: https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select


问:
list comprehension to create n unique copies of a dictionary
I have two lists of dictionary keys:  a list of 'outer' dictionary keys, and a list of 'inner' dictionary keys:

```<code>outer_keys = ['out1', 'out2', 'out3', 'out4' ]
inner_keys = ['in1', 'in2', 'in3' ]
</code>```

I am trying to use a list comprehension to programmatically generate nested dictionaries resembling the following structure:

```<code>{'out1': {'in1': Decimal('0.00'), 'in2': Decimal('0.00'), 'in3': Decimal('0.00')},
 'out2': {'in1': Decimal('0.00'), 'in2': Decimal('0.00'), 'in3': Decimal('0.00')},
 'out3': {'in1': Decimal('0.00'), 'in2': Decimal('0.00'), 'in3': Decimal('0.00')},
 'out4': {'in1': Decimal('0.00'), 'in2': Decimal('0.00'), 'in3': Decimal('0.00')}
}
</code>```

My first attempt was the following:

```<code>from decimal import Decimal
outer_keys = ['out1', 'out2', 'out3', 'out4' ]
inner_keys = ['in1', 'in2', 'in3' ]

z = dict(zip(outer_keys, [dict(zip(inner_keys, [Decimal('0.00') for _ in inner_keys])) for _ in outer_keys]))
</code>```

This works properly, in the sense that the 'inner' dictionaries referenced by the 'outer' keys are all unique:

```<code>>>> z['out1']['in1'] is z['out2']['in1']
False
</code>```

However, the assignment to z is fairly difficult to follow.  So I tried breaking it up into two assignments to simplify it:

```<code>x = dict(zip(inner_keys, [Decimal('0.00') for _ in inner_keys]))
y = dict(zip(outer_keys, [x for _ in outer_keys]))
</code>```

This no longer works because the values of the 'outer' keys 'out1', ..., 'out4' all reference the same dictionary.

```<code>>>> y['out1']['in1'] is y['out2']['in1']
True
</code>```

So assigning to an item in one inner dictionary changes the corresponding value in them all:

```<code>>>> y['out1']['in1']
Decimal('0.00')
>>> y['out2']['in1']
Decimal('0.00')
>>> y['out1']['in1']=Decimal('1.00')
>>> y['out2']['in1']
Decimal('1.00')
>>>
</code>```

I've tried using everything I can think of in place of x in the list comprehension in the assignment to y (including, e.g., copy.deepcopy(x) and a list-slice like [x][:][0], but no matter what I do, I cannot get python to create a unique copy of the dictionary referenced by x for each outer key value.  Except of course by going back to the original lengthy and unreadable assignment to z.

I'm also having trouble understanding why [Decimal('0.00') for _ in inner_keys] generates three unique Decimal objects, but [x for _ in outer_keys] generates four references to a single dict.  And how to write a list comprehension which will generate n unique copies of the dict x.

Edit 1:  It seems I wasn't careful enough in checking whether some of things I tried were actually working.  As @MichaelButscher correctly points out in his comment below, using x.copy() rather than x in the assignment to y will resolve my issue, as so it seems did copy.deepcopy(x) even though I didn't realize it was working.

So that is certainly one way I could fix this.

I also like the dict comprehension solution that @Ahmed I. Elsayed posted below.

Both of these are much cleaner than my original complicated assignment to z

答:
Python offers dict comprehensions (and set comps too!)

```<code># IDLE ( I reformatted )

my_dict = { key: inner_keys for key in outer_keys }
my_dict

{
 'out1': ['in1', 'in2', 'in3'],
 'out2': ['in1', 'in2', 'in3'],
 'out3': ['in1', 'in2', 'in3'],
 'out4': ['in1', 'in2', 'in3']
}
</code>```

if you want to apply something to the second list like you've used Decimal, Multiple ways

```<code>my_dict = { key: [i.upper() for i in inner_keys ] for key in outer_keys }
my_dict

{
 'out1': ['IN1', 'IN2', 'IN3'],
 'out2': ['IN1', 'IN2', 'IN3'],
 'out3': ['IN1', 'IN2', 'IN3'],
 'out4': ['IN1', 'IN2', 'IN3']
}
</code>```

or

```<code>my_dict = { key: map(str.upper, inner_keys) for key in outer_keys }
# same output as above, trimmed for readability
</code>```

customize as needed, or ask in the comments here.

I'd like to credit where I learnt dictcomps, The first time I saw them were in the awesome book Fluent Python by the genius Luciano Ramalho.

Body:
I have two lists of dictionary keys:  a list of 'outer' dictionary keys, and a list of 'inner' dictionary keys:

outer_keys = ['out1', 'out2', 'out3', 'out4' ]
inner_keys = ['in1', 'in2', 'in3' ]

I am trying to use a list comprehension to programmatically generate nested dictionaries resembling the following structure:

{'out1': {'in1': Decimal('0.00'), 'in2': Decimal('0.00'), 'in3': Decimal('0.00')},
 'out2': {'in1': Decimal('0.00'), 'in2': Decimal('0.00'), 'in3': Decimal('0.00')},
 'out3': {'in1': Decimal('0.00'), 'in2': Decimal('0.00'), 'in3': Decimal('0.00')},
 'out4': {'in1': Decimal('0.00'), 'in2': Decimal('0.00'), 'in3': Decimal('0.00')}
}

My first attempt was the following:

from decimal import Decimal
outer_keys = ['out1', 'out2', 'out3', 'out4' ]
inner_keys = ['in1', 'in2', 'in3' ]

z = dict(zip(outer_keys, [dict(zip(inner_keys, [Decimal('0.00') for _ in inner_keys])) for _ in outer_keys]))

This works properly, in the sense that the 'inner' dictionaries referenced by the 'outer' keys are all unique:

>>> z['out1']['in1'] is z['out2']['in1']
False

However, the assignment to z is fairly difficult to follow.  So I tried breaking it up into two assignments to simplify it:

x = dict(zip(inner_keys, [Decimal('0.00') for _ in inner_keys]))
y = dict(zip(outer_keys, [x for _ in outer_keys]))

This no longer works because the values of the 'outer' keys 'out1', ..., 'out4' all reference the same dictionary.

>>> y['out1']['in1'] is y['out2']['in1']
True

So assigning to an item in one inner dictionary changes the corresponding value in them all:

>>> y['out1']['in1']
Decimal('0.00')
>>> y['out2']['in1']
Decimal('0.00')
>>> y['out1']['in1']=Decimal('1.00')
>>> y['out2']['in1']
Decimal('1.00')
>>>

I've tried using everything I can think of in place of x in the list comprehension in the assignment to y (including, e.g., copy.deepcopy(x) and a list-slice like [x][:][0], but no matter what I do, I cannot get python to create a unique copy of the dictionary referenced by x for each outer key value.  Except of course by going back to the original lengthy and unreadable assignment to z.

I'm also having trouble understanding why [Decimal('0.00') for _ in inner_keys] generates three unique Decimal objects, but [x for _ in outer_keys] generates four references to a single dict.  And how to write a list comprehension which will generate n unique copies of the dict x.

Edit 1:  It seems I wasn't careful enough in checking whether some of things I tried were actually working.  As @MichaelButscher correctly points out in his comment below, using x.copy() rather than x in the assignment to y will resolve my issue, as so it seems did copy.deepcopy(x) even though I didn't realize it was working.

So that is certainly one way I could fix this.

I also like the dict comprehension solution that @Ahmed I. Elsayed posted below.

Both of these are much cleaner than my original complicated assignment to z

Body:
Python offers dict comprehensions (and set comps too!)

# IDLE ( I reformatted )

my_dict = { key: inner_keys for key in outer_keys }
my_dict

{
 'out1': ['in1', 'in2', 'in3'],
 'out2': ['in1', 'in2', 'in3'],
 'out3': ['in1', 'in2', 'in3'],
 'out4': ['in1', 'in2', 'in3']
}

if you want to apply something to the second list like you've used Decimal, Multiple ways

my_dict = { key: [i.upper() for i in inner_keys ] for key in outer_keys }
my_dict

{
 'out1': ['IN1', 'IN2', 'IN3'],
 'out2': ['IN1', 'IN2', 'IN3'],
 'out3': ['IN1', 'IN2', 'IN3'],
 'out4': ['IN1', 'IN2', 'IN3']
}

or

my_dict = { key: map(str.upper, inner_keys) for key in outer_keys }
# same output as above, trimmed for readability

customize as needed, or ask in the comments here.

I'd like to credit where I learnt dictcomps, The first time I saw them were in the awesome book Fluent Python by the genius Luciano Ramalho.


问:
How log springboot commit transaction
I create 2 methods with annotation

```<code>@Trasactional
</code>```

so now how can I log the begin and commit in my transactions? I wanna to see everthing inside one transactions, when Start another insede a existing

something like this:

```<code>Begin1
//sqls
Begin 2

//sqls
commit 2
//sqls
Begin 3
commit 3

//sqls

//sqls
commit1
</code>```

tks

答:
Adding this property to your application.properties should do the trick</p>

```<code>logging.level.org.springframework.transaction=DEBUG
</code>```

Title: How log springboot commit transaction

Body:
I create 2 methods with annotation

@Trasactional

so now how can I log the begin and commit in my transactions? I wanna to see everthing inside one transactions, when Start another insede a existing

something like this:

Begin1
//sqls
Begin 2

//sqls
commit 2
//sqls
Begin 3
commit 3

//sqls

//sqls
commit1

tks

Body:
Adding this property to your application.properties should do the trick

logging.level.org.springframework.transaction=DEBUG


问:
How to enable custom PHP laravel logging for Azure log analytics
We have developed a PHP application and hosted the same in Azure Webapp with Linux as the operating system.

Currently the log files are getting generated inside the wwwroot/storage/logs as shown in attached ssh console app screenshot.

We have enabled the Custom logs for the App Service from Log Analytics as shown in log analytics screenshot. (I was unable to understand whether path should be given from home or site so I added both).

When I tried to query the custom log in the Azure Log it is returning empty data. Please find the attached screenshot for reference log image

Please help me in understanding what is the mistake.

Thank you.

答:
Your app needs to be running in a VM to use Custom Log Analytics in that manner. Just ensure you've properly installed and configured the OMS agent according the steps documented in https://learn.microsoft.com/en-us/azure/azure-monitor/platform/data-sources-custom-logs.

Since you're using an App Service, there isn't Custom Log Analytics available. There is, however, Log Analytics integration for App Services which is currently in preview and supports the following types:

AppServiceHTTPLogs

AppServiceConsoleLogs

AppServiceAppLogs

AppServiceFileAuditLogs

AppServiceAuditLogs

You can also leverage this SDK to write your custom log messages to application insights.


问:
Use UWP methods from .Net Standard library
I know there is a way to use UWP methods from WPF apps.

My question is whether there is a way to use those methods from a .Net Standard library. Just adding the references mentioned here doesn't help. It doesn't recognize them.

答:
Individual Platforms (.NET Framework, .NET Core, UWP, Mono) can reference .NET Standard libraries. But .NET Standard libraries cannot reference other libraries built specifically for a platform (.NET Framework, UWP etc). </p>

<p>Which makes sense since .NET Standard libraries themselves are supposed to be platform agnostic, so you shouldn't be able to add a library that would only work on a single platform. </p>

Body:
Individual Platforms (.NET Framework, .NET Core, UWP, Mono) can reference .NET Standard libraries. But .NET Standard libraries cannot reference other libraries built specifically for a platform (.NET Framework, UWP etc).

Which makes sense since .NET Standard libraries themselves are supposed to be platform agnostic, so you shouldn't be able to add a library that would only work on a single platform.