问:
Django models sqlmigrate - too few arguments
Here are my Django models, which have multiple many to many relationships.

```<code>class Theme(models.Model):
        theme_name = Models.CharField(max_length=20)
        theme_ind = Models.CharField(max_length=1)

class Topics(models.Model):
        topic_name = Models.CharField(max_length=20)

class Language(models.Model):
        lang_name = models.CharField(max_length=10)

class Article(models.Model):
        name = Models.CharField(max_length=10)
        url = Models.CharField(max_length=50)
        lang_id = models.ManyToManyField(Language, related_name='theme')
        theme_id = models.OneToOneField(Theme, related_name='theme')
        topic_id = models.ManyToManyField(Topics, related_name='topic')
</code>```

Question:
When I run:

```<code>python  manage.py sqlmigrate polls
</code>```

I get this error:

```<code>manage.py sqlmigrate: error: too few arguements.
</code>```

答:
to get all migrations in order you could use showmigrations -p

and you could add it to Javier solution for generating all the SQL statement in order

```<code>import os
import django
from io import StringIO
from django.core.management import call_command
from django.apps import apps
import re

# Remove all the terminal colors, less parsing later.
os.environ['DJANGO_COLORS'] = 'nocolor'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
django.setup()

out = StringIO()
call_command('showmigrations', '-p', stdout=out)

# Clean up the line, and remove all applied migrations
migrations = [line.strip() for line in out.getvalue().split('\n')]

migration_regex = re.compile('^\[[X ]\]  ([^.]*).(.*)$')

with open('sql_script.sql', 'w') as out_file:

    for migration in migrations:
        searched_migration = re.search(migration_regex, migration)
        if searched_migration:
            app_name = searched_migration.group(1)
            migration_name = searched_migration.group(2)
            app_path = apps.get_app_config(app_name).module.__file__
            call_command('sqlmigrate', app_name, migration_name, stdout=out_file)

</code>```

Body:
Here are my Django models, which have multiple many to many relationships.

class Theme(models.Model):
        theme_name = Models.CharField(max_length=20)
        theme_ind = Models.CharField(max_length=1)

class Topics(models.Model):
        topic_name = Models.CharField(max_length=20)

class Language(models.Model):
        lang_name = models.CharField(max_length=10)

class Article(models.Model):
        name = Models.CharField(max_length=10)
        url = Models.CharField(max_length=50)
        lang_id = models.ManyToManyField(Language, related_name='theme')
        theme_id = models.OneToOneField(Theme, related_name='theme')
        topic_id = models.ManyToManyField(Topics, related_name='topic')

Question:
When I run:

python  manage.py sqlmigrate polls

I get this error:

manage.py sqlmigrate: error: too few arguements.

Body:
to get all migrations in order you could use showmigrations -p

and you could add it to Javier solution for generating all the SQL statement in order

import os
import django
from io import StringIO
from django.core.management import call_command
from django.apps import apps
import re

# Remove all the terminal colors, less parsing later.
os.environ['DJANGO_COLORS'] = 'nocolor'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
django.setup()

out = StringIO()
call_command('showmigrations', '-p', stdout=out)

# Clean up the line, and remove all applied migrations
migrations = [line.strip() for line in out.getvalue().split('\n')]

migration_regex = re.compile('^\[[X ]\]  ([^.]*).(.*)$')

with open('sql_script.sql', 'w') as out_file:

    for migration in migrations:
        searched_migration = re.search(migration_regex, migration)
        if searched_migration:
            app_name = searched_migration.group(1)
            migration_name = searched_migration.group(2)
            app_path = apps.get_app_config(app_name).module.__file__
            call_command('sqlmigrate', app_name, migration_name, stdout=out_file)


来源: stackexchange

问:
What is the difference between JSF, Servlet and JSP?
I have some questions. These are :

How are JSP and Servlet related to each other?

Is JSP some kind of Servlet?

How are JSP and JSF related to each other?

Is JSF some kind of Pre-Build UI based JSP like ASP.NET-MVC?

答: JSP stands for JavaServer Pages while JSF stands for JavaServer Faces. JSP is a technology that helps developers develop dynamic web pages using technologies like HTML, XML and similar other languages. JSF is a framework that helps developers develop user interfaces for server-side applications. Both these technologies are based on Java and they are primarily used for web-based applications. JSP is more like ASP or PHP except the fact that it is based on Java which means it uses Java programming language. Both the technologies are developed by Sun Microsystems. It is interesting to note that JSP 1.x versions used JSP as the default system for templating but JSP 2.x uses Facelets instead of JSP.</p>

ContentLicense: CC BY-SA 4.0


问:
How can I extract a dictionary into Excel?
I'm trying to extract the following dictionary using a pandas data frame into Excel:

```<code>results = {'ZF_DTSPP': [735.0500558302846,678.5413714617252,772.0300704610595,722.254907241738,825.2955175305726], 'ZF_DTSPPG': [732.0500558302845,637.4786326591071,655.8462451037873,721.404907241738,821.8455175305724]}
</code>```

This is my code:

```<code>df = pd.DataFrame(data=results, index=[5, 2])
df = (df.T)
print(df)
df.to_excel('dict1.xlsx')
</code>```

Somehow I always receive following error:

"ValueError: Shape of passed values is (5, 2), indices imply (2, 2)".

What can I do? How do I need to adapt the index?

Is there a way to compare the different values of "ZF_DTSPP" and "ZF_DTSPPG" directly with python?

答:
You can use pd.DataFrame.from_dict as shown in pandas-from-dict, then your code:

```<code>df = pd.DataFrame.from_dict(results)
</code>```

Body:
I'm trying to extract the following dictionary using a pandas data frame into Excel:

results = {'ZF_DTSPP': [735.0500558302846,678.5413714617252,772.0300704610595,722.254907241738,825.2955175305726], 'ZF_DTSPPG': [732.0500558302845,637.4786326591071,655.8462451037873,721.404907241738,821.8455175305724]}

This is my code:

df = pd.DataFrame(data=results, index=[5, 2])
df = (df.T)
print(df)
df.to_excel('dict1.xlsx')

Somehow I always receive following error:

"ValueError: Shape of passed values is (5, 2), indices imply (2, 2)".

What can I do? How do I need to adapt the index?

Is there a way to compare the different values of "ZF_DTSPP" and "ZF_DTSPPG" directly with python?

Body:
You can use pd.DataFrame.from_dict as shown in pandas-from-dict, then your code:

df = pd.DataFrame.from_dict(results)


问:
How can i change a text of a button without changing it's icon
i have a "Pause" button with a pause_circle_outline materialize icon, and when it clicked i want to change the text to "Resume" and changing the icon to play_circle_outline, but when i try to change the text it changed the text and deletes the icon. here is my code snippet example:

jQuery(document).ready(function($){

  $(document.getElementById("pause_btn")).click(function(){
      document.getElementById("pause_btn").innerText = "Resume"
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <script src = "Sources/js/select_require.js"></script>
    <script src = "Sources/js/routes.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <body>
    Pause<i class="material-icons right">pause_circle_outline</i>
  </body>
</html></code>```

答:
.innerText is a sort of "safe"* way to access a node's innerHTML, which in your case includes both the Pause-text, as well as the  tag.

A way to solve this is to add a span to hold the text. spans don't do anything (as they are inline elements and are by default formatted/shown as a simple text element), but they help by making the text node selectable by document.querySelector!

Example:

var playing = true

window.addEventListener("load", () => {
  document.querySelector("#pause_btn").addEventListener("click", () => {
      playing = !playing
      if(playing) {
        document.querySelector("#pause_btn span").innerText = "Pause"
        document.querySelector("#pause_btn i").innerText = "pause_circle_outline"
      } else {
        document.querySelector("#pause_btn span").innerText = "Resume"
        document.querySelector("#pause_btn i").innerText = "play_circle_outline"
      }
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <body>

      <span>Pause</span>
      <i class="material-icons right">pause_circle_outline</i>

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

I also added some extra code to make it clickable multiple times!

*: By safe, in this context, I mean that it's safe from a security issue called XSS. Generally it's better to use innerText when you don't explicitly need to change the HTML itself, but if you do: Make sure that there's NO way a user can input something that gets put into the innerHTML. What I initially meant was simply that writing to either innerHTML and innerText will always overwrite whatever contents the element has, and that innerText is generally the safer of the two.

Body:
i have a "Pause" button with a pause_circle_outline materialize icon, and when it clicked i want to change the text to "Resume" and changing the icon to play_circle_outline, but when i try to change the text it changed the text and deletes the icon. here is my code snippet example:

jQuery(document).ready(function($){

  $(document.getElementById("pause_btn")).click(function(){
      document.getElementById("pause_btn").innerText = "Resume"
  });
})

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    Pausepause_circle_outline

Body:
.innerText is a sort of "safe"* way to access a node's innerHTML, which in your case includes both the Pause-text, as well as the <i.../> tag.

A way to solve this is to add a span to hold the text. spans don't do anything (as they are inline elements and are by default formatted/shown as a simple text element), but they help by making the text node selectable by document.querySelector!

Example:

var playing = true

window.addEventListener("load", () => {
  document.querySelector("#pause_btn").addEventListener("click", () => {
      playing = !playing
      if(playing) {
        document.querySelector("#pause_btn span").innerText = "Pause"
        document.querySelector("#pause_btn i").innerText = "pause_circle_outline"
      } else {
        document.querySelector("#pause_btn span").innerText = "Resume"
        document.querySelector("#pause_btn i").innerText = "play_circle_outline"
      }
  });
})

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <body>
    <a class="waves-effect waves-light btn" id="pause_btn">
      <span>Pause</span>
      <i class="material-icons right">pause_circle_outline</i>
    </a>
  </body>
</html>

I also added some extra code to make it clickable multiple times!

*: By safe, in this context, I mean that it's safe from a security issue called XSS. Generally it's better to use innerText when you don't explicitly need to change the HTML itself, but if you do: Make sure that there's NO way a user can input something that gets put into the innerHTML. What I initially meant was simply that writing to either innerHTML and innerText will always overwrite whatever contents the element has, and that innerText is generally the safer of the two.


问:
QUERY speed with limit and milion records
Hi i have a 7milion records db table for testing query speed.

I tested up my 2 queries which are the same query with different limit parametres:

query 1 -

```<code>SELECT    *
FROM      table
LIMIT     20, 50;
</code>```

query 2 -

```<code>SELECT    *
FROM      table
LIMIT     6000000, 6000030;
</code>```

query exec times are:

query 1 - 0.006 sec

query 2 - 5.500 sec

In both of these queries, I am fetching same number of records, but in the second case it's taking more time. Can someone please explain the reasons behind this?

答: I think the slowdown is tied to the fact you are using limits with offsets and are querying the table with no additional context for indexing.  Its possible the first is just faster because it can get to the offset quicker.</p>

ContentLicense: CC BY-SA 3.0

Body:
Hi i have a 7milion records db table for testing query speed.

I tested up my 2 queries which are the same query with different limit parametres:

query 1 -

SELECT    *
FROM      table
LIMIT     20, 50;

query 2 -

SELECT    *
FROM      table
LIMIT     6000000, 6000030;

query exec times are:

query 1 - 0.006 sec

query 2 - 5.500 sec

In both of these queries, I am fetching same number of records, but in the second case it's taking more time. Can someone please explain the reasons behind this?


问:
Map array values to string keys in a if statement javascript
I have a list that i want to display in a dropdown. The onchange in handled by

```<code>const handleChange = (event) => {
    onFilterChange(filterName, event.target.value);
    }
 };
</code>```

event.target.value is what is pulling the information.

My dropdown list items are listItems = ['greaterthan', 'lesserthan, 'equal'], which are string keys that are fed into event.target.value.

My issue is that i want listItems to be an array of symbols( >, <, =) instead of words. But my components only works with the word keys.

I want to create an if statement in the handler that maps the word value to the signs array.

ex.

```<code>const listItems = ['>','<','=']

const handleChange = (event) => {
        onFilterChange(filterName, event.target.value);
        if (event.target.value === '>') {
          // then use key value of greaterthan
        } if (event.target.value === '<') {
          // then use key value of lesserthan
        } if (event.target.value === '=') {
          // then use key value of equal
        }
      }
</code>```

;

I'm feeding it into a select component by using

```<code><Select>
{listItems.map((listItem) => <MenuItem value={listItem}>{listItem}</MenuItem>)}
</Select>
</code>```

Thank you for your help.

答:
You can create am object map to retrieve the respective ids :</p>
```<code>listItems = {
  ['>']: 'greaterthan',
  ['<']: 'lesserthan',
  ['=']: 'equal'
}

const handleChange = (event) => {
        onFilterChange(filterName, event.target.value);
        if (event.target.value === listItems['>']) {
          // then use key value of greaterthan
        } if (event.target.value === listItems['<']) {
          // then use key value of lesserthan
        } if (event.target.value === listItems['=']) {
          // then use key value of equal
        }
}
</code>```

Body:
I have a list that i want to display in a dropdown. The onchange in handled by

const handleChange = (event) => {
    onFilterChange(filterName, event.target.value);
    }
 };

event.target.value is what is pulling the information.

My dropdown list items are listItems = ['greaterthan', 'lesserthan, 'equal'], which are string keys that are fed into event.target.value.

My issue is that i want listItems to be an array of symbols( >, <, =) instead of words. But my components only works with the word keys.

I want to create an if statement in the handler that maps the word value to the signs array.

ex.

const listItems = ['>','<','=']

const handleChange = (event) => {
        onFilterChange(filterName, event.target.value);
        if (event.target.value === '>') {
          // then use key value of greaterthan
        } if (event.target.value === '<') {
          // then use key value of lesserthan
        } if (event.target.value === '=') {
          // then use key value of equal
        }
      }

;

I'm feeding it into a select component by using

<Select>
{listItems.map((listItem) => <MenuItem value={listItem}>{listItem}</MenuItem>)}
</Select>

Thank you for your help.

Body:
You can create am object map to retrieve the respective ids :

listItems = {
  ['>']: 'greaterthan',
  ['<']: 'lesserthan',
  ['=']: 'equal'
}

const handleChange = (event) => {
        onFilterChange(filterName, event.target.value);
        if (event.target.value === listItems['>']) {
          // then use key value of greaterthan
        } if (event.target.value === listItems['<']) {
          // then use key value of lesserthan
        } if (event.target.value === listItems['=']) {
          // then use key value of equal
        }
}


问:
Selecting entire variable with double click
In PhpStorm, when you double click on a variable, say $_helloWorld, it just selects a part of the variable. For example, when you double click on World and it will select just that instead of the entire variable.

I want it to select the entire variable $_helloWorld when I double click on any part of it.

Does anyone know how to do it?

答:
For the folks who are using Mac, this is what you got to do:

Step 1: Select preferences option in PhpStorm Menu

Step 2: Once the window appears get the Smart Keys settings like so, which will be inside the following menu

Editor > General > Smart Keys

Step 3: Uncheck the checkbox next to Honor "CamelHumps" words settings when selecting on double click


问:
Streaming video in a folder with ffmpeg
I have configured RTMP to work with Nginx on ubuntu server following the guide from https://www.youtube.com/watch?v=Js1OlvRNsdI
I have tested the setup and everything is working perfectly to the end but then I have a folder containing movies and I want them to be streamed or played independently via a web player, for example, JWPlayer and I have failed to get that implementation online. Is there anyone with an idea of how to go about it?</p>

答:
Do you get a folder contains a set of movies, and you want to stream them as a stream, or each file as a stream?

Whatever you could do this by FFmpeg:

for file in $(ls movies/*.mp4); do
  ffmpeg -re -i $file -c copy -f flv rtmp://server/app/stream
done
```

If want to stream each file as a stream, try to start multiple ffmpeg to do this.

Title: Streaming video in a folder with ffmpeg

Body:
Do you get a folder contains a set of movies, and you want to stream them as a stream, or each file as a stream?

Whatever you could do this by FFmpeg:

for file in $(ls movies/*.mp4); do
  ffmpeg -re -i $file -c copy -f flv rtmp://server/app/stream
done

If want to stream each file as a stream, try to start multiple ffmpeg to do this.


问:
BlogEngine.Net - "Unable to generate a temporary class" error
I just uploaded a new instance of blogengine.net to a subdomain on my host and I am getting the following error:

Unable to generate a temporary class
  (result=1). error CS2001: Source file
  'C:\WINDOWS\TEMP\jn5ced1y.0.cs' could
  not be found error CS2008: No inputs
  specified

I do have  VPS plan on my host, do I need to ask for specific permissions?

On previous installs (older versions) of BE I never had this problem - did I do something wrong?

Thank you.

答: Sounds like a permissions issue on the TEMP directory. I've had the same issue locally on my development machine and took the naughty EVERYONE/ALL route to resolve.</p>

OwnerDisplayName: naspinski

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Brian Rasmussen

OwnerDisplayName: Garry


问:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'
I am building My first MVC application, I have a table in database containing 3 columns:

Id → primary key

Username

password

When I am clicking on edit link edit a record, its throwing following exception:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'MvcApplication1.Controllers.UserController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
  Parameter name: parameters

Here is my edit code:

```<code>public ActionResult Edit(int id, User collection)
{
    UserDBMLDataContext db = new UserDBMLDataContext();
    var q = from abc in db.User_Login_Details
            where abc.Id == id
            select abc;

    IList lst = q.ToList();

    User_Login_Details userLook = (User_Login_Details)lst[0];

    userLook.Username = collection.UserName;
    userLook.Password = collection.Password;
    db.SubmitChanges();
    return RedirectToAction("Index");
}
</code>```

答:
@Html.ActionLink(item.Name, "Edit", new { id = item.Id })
here notice that parameters given to the ActionLink() is in order.

first parameter is for the text field to show on-page.

second one is for action URL.

List one is for ID reference.

Body:
I am building My first MVC application, I have a table in database containing 3 columns:

Id → primary key

Username

password

When I am clicking on edit link edit a record, its throwing following exception:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'MvcApplication1.Controllers.UserController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
  Parameter name: parameters

Here is my edit code:

public ActionResult Edit(int id, User collection)
{
    UserDBMLDataContext db = new UserDBMLDataContext();
    var q = from abc in db.User_Login_Details
            where abc.Id == id
            select abc;

    IList lst = q.ToList();

    User_Login_Details userLook = (User_Login_Details)lst[0];

    userLook.Username = collection.UserName;
    userLook.Password = collection.Password;
    db.SubmitChanges();
    return RedirectToAction("Index");
}


问:
Cant output answer buttons and sort them in my project
im trying to make a quizz project fetching api of quiz with answers and questions im so in the api
there is array of wrong answers(3) and one correct answer i try to output them as buttons and i outtput the 3 wrong answers so i thought i would push the correct answer into the wrong answers array and then randomly sort them and output as answers but i get the errot that array of answers isnt iterable can anyone help me to solve this problem and tell me if im going in the right direction or not ?</p>
```<code>
import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res=>{

      setQuiz(res.data.results[0])

       setAnswer([...quiz.incorrect_answers, quiz.correct_answer])
    })
    .catch(err=>{
      console.log(err);
    })

  },[])

  return (
    <div className="App">
   <h1>{quiz.question}</h1>
   {answer && answer?.map(answers =>
   <button key={answers}>{answers}</button>)

   }
    </div>

  );
}

export default App;
</code>```

答:
Here's an approach you can use:

```<code>function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
// This here is a function to shuffle the array for you

const [quiz,setQuiz] = useState(null)
// use a null value for the quiz, null checking will be done in the h1 render component
const [correct_answer,setAnswerCorrect] = useState([])
// from the result, the correct answer is a string
const [incorrect_answers,setAnswersIncorrect] = useState([])
// and the incorrect answers are in form of an array
// that's why the separation
let all_answers = [];
useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{

        setQuiz(res.data.results[0])

        setAnswerCorrect([res.data.results[0].correct_answer])
        setAnswersIncorrect(res.data.results[0].incorrect_answers);
        // first update all the values
    })
    .catch(err=>{
    console.log(err);
    })

},[])
</code>```

Then from here check whether the question has loaded first, if not, show that the question is loading:

```<code><h1>{quiz ? quiz.question : 'Question loading...'}</h1>
// check whether the question has loaded before outputting it
{
    all_answers = correct_answer && incorrect_answers ? shuffleArray(correct_answer.concat(incorrect_answers)) : ''
// join the two arrays, for the correct and incorrect answers then shuffle the values
}
{
    all_answers?.map(answers =>
    <button key={answers}>{answers}</button>)
}
</code>```

Body:
im trying to make a quizz project fetching api of quiz with answers and questions im so in the api
there is array of wrong answers(3) and one correct answer i try to output them as buttons and i outtput the 3 wrong answers so i thought i would push the correct answer into the wrong answers array and then randomly sort them and output as answers but i get the errot that array of answers isnt iterable can anyone help me to solve this problem and tell me if im going in the right direction or not ?

import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res=>{

      setQuiz(res.data.results[0])

       setAnswer([...quiz.incorrect_answers, quiz.correct_answer])
    })
    .catch(err=>{
      console.log(err);
    })

  },[])

  return (

{quiz.question}

   {answer && answer?.map(answers =>
   <button key={answers}>{answers}</button>)

   }

  );
}

export default App;

Body:
Here's an approach you can use:

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
// This here is a function to shuffle the array for you

const [quiz,setQuiz] = useState(null)
// use a null value for the quiz, null checking will be done in the h1 render component
const [correct_answer,setAnswerCorrect] = useState([])
// from the result, the correct answer is a string
const [incorrect_answers,setAnswersIncorrect] = useState([])
// and the incorrect answers are in form of an array
// that's why the separation
let all_answers = [];
useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{

        setQuiz(res.data.results[0])

        setAnswerCorrect([res.data.results[0].correct_answer])
        setAnswersIncorrect(res.data.results[0].incorrect_answers);
        // first update all the values
    })
    .catch(err=>{
    console.log(err);
    })

},[])

Then from here check whether the question has loaded first, if not, show that the question is loading:

<h1>{quiz ? quiz.question : 'Question loading...'}</h1>
// check whether the question has loaded before outputting it
{
    all_answers = correct_answer && incorrect_answers ? shuffleArray(correct_answer.concat(incorrect_answers)) : ''
// join the two arrays, for the correct and incorrect answers then shuffle the values
}
{
    all_answers?.map(answers =>
    <button key={answers}>{answers}</button>)
}


问:
Javascript code analysis and constants
Given there is no cross browser const in Javascript and most of the work-arounds are more complex than I care for, I am just going to go with the naming convention of THIS_IS_A_CONSTANT.  All well and good, but what occurred to me is that if there was way to get my IDE (VS.NET 2010 with Resharper 6) to give me a warning on any Javascript code that makes an assignment to a variable with that naming convention except in the variable declaration this would handle most of the potential issues around the lack of real constants in Javascript (at least for my needs).

So does anyone know of a good way to generate such warnings?  In-IDE would be the best thing but other solutions are fine as well.  I have looked for something like FX-Cop for Javascript; jslint doesn't seem to allow the creation of new rules but maybe I didn't look deep enough.  I may also suggest this as a feature in Resharper (assuming I am not missing a way to make it do so already).

Thanks,
Matthew

答:
So you want to find any assigment of the form:

```<code>id = exp ;
</code>```

where id doesn't contain the substring CONSTANT and exp is a numeric constant?

Our Source Code Search Engine (SCSE) can do this pretty directly.  The SCSE reads source code for a large set of files for many languages (including JavaScript), breaks it into tokens ignoring whitespace, and indexes it all to enable fast search for token sequences.  Any hits are displayed in a hit window and can be clicked to see the actual file text in context.

Your particular query would be stated:

```<code>  (I - I=*CONSTANT*) '=' N ( ';' | O | K | I)
</code>```

This hunts for any assignment in which the target identifier doesn't contain the string constant (see wildcard stars around the match string), assigned  a constant *N*umber is not followed by a ';' or an *O*perator, *K*word or *I*dentifier (all this extra stuff is because JavaScript might not have a semicolon to terminate the statement).   It probably picks up some cases it should not but
these are easily inspected.

Title: Javascript code analysis and constants

Body:
So you want to find any assigment of the form:

id = exp ;

where id doesn't contain the substring CONSTANT and exp is a numeric constant?

Our Source Code Search Engine (SCSE) can do this pretty directly.  The SCSE reads source code for a large set of files for many languages (including JavaScript), breaks it into tokens ignoring whitespace, and indexes it all to enable fast search for token sequences.  Any hits are displayed in a hit window and can be clicked to see the actual file text in context.

Your particular query would be stated:

  (I - I=*CONSTANT*) '=' N ( ';' | O | K | I)

This hunts for any assignment in which the target identifier doesn't contain the string constant (see wildcard stars around the match string), assigned  a constant *N*umber is not followed by a ';' or an *O*perator, *K*word or *I*dentifier (all this extra stuff is because JavaScript might not have a semicolon to terminate the statement).   It probably picks up some cases it should not but
these are easily inspected.


问:
How to change color Image into black/white in jetpack compose
I want to show color image in black/white, how to do it using colorFilter in android jetpack compose?</p>
```<code>    Image(
        painter = painter, contentDescription = null,
        modifier = Modifier
            .fillMaxSize(),
        contentScale = scale,
        colorFilter = null
    )

</code>```

答:
You can also use ColorFilter.tint(color = ...)

```<code>Image(
        painter = painter, contentDescription = null,
        modifier = Modifier
            .fillMaxSize(),
        contentScale = scale,
        colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
    )
</code>```

Body:
I want to show color image in black/white, how to do it using colorFilter in android jetpack compose?

    Image(
        painter = painter, contentDescription = null,
        modifier = Modifier
            .fillMaxSize(),
        contentScale = scale,
        colorFilter = null
    )

Body:
You can also use ColorFilter.tint(color = ...)

Image(
        painter = painter, contentDescription = null,
        modifier = Modifier
            .fillMaxSize(),
        contentScale = scale,
        colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground)
    )


问:
angular slickgrid latest version(Current) pagination not showing properly
This is my code. I am using version 4.1.1

```<code>AngularSlickgridModule.forRoot({

          registerExternalResources: [new ExcelExportService()],
          enableAutoResize: true,
          enableGridMenu: true,
          enableExcelExport:true,
          autoHeight: true,
          alwaysShowVerticalScroll: false,
          autoResize: {
            rightPadding: 10,
            container: '#grid-container',
            bottomPadding: 20,
            minHeight: 250,
            maxWidth: 900,
            minWidth: 200
          },

          enableFiltering: true,
          enablePagination: true,
          pagination: {
            pageSizes: [],
            pageSize: 10,
            totalItems: 0,
          },
}),

</code>```

Page size in showing in 10,25,50....100

But I need custom pagination. So I added pageSizes: [10,50,100,1000],

But it showing default pages (except 10) and  1000,2000...

and also not in sort order. Is I'm doing wrong ?

EDIT :  After chhange to below code it showing like this..it also showing default page size of slickgrid..

```<code> pagination: {
        pageSizes: [10, 200, 250, 500, 5000],
        pageSize: 10
      },
</code>```

答:
You have a typo in your page sizes, it won't work with decimal numbers and your pageSize must be a valid number that is included in pageSizes but isn't in your case because of the decimal number, it works fine in the lib as shown by Example 30

this.gridOptions = {
  enablePagination: true,
  pagination: {
    pageSize: 10,
    pageSizes: [10, 200, 250, 500, 5000]
  },
};
```

EDIT

There was actually a bug identified to set pagination via global configuration and that was fixed and released under a patch version 4.1.2 of Angular-Slickgrid

Body:
This is my code. I am using version 4.1.1

AngularSlickgridModule.forRoot({

          registerExternalResources: [new ExcelExportService()],
          enableAutoResize: true,
          enableGridMenu: true,
          enableExcelExport:true,
          autoHeight: true,
          alwaysShowVerticalScroll: false,
          autoResize: {
            rightPadding: 10,
            container: '#grid-container',
            bottomPadding: 20,
            minHeight: 250,
            maxWidth: 900,
            minWidth: 200
          },

          enableFiltering: true,
          enablePagination: true,
          pagination: {
            pageSizes: [],
            pageSize: 10,
            totalItems: 0,
          },
}),

Page size in showing in 10,25,50....100

But I need custom pagination. So I added pageSizes: [10,50,100,1000],

But it showing default pages (except 10) and  1000,2000...

and also not in sort order. Is I'm doing wrong ?

EDIT :  After chhange to below code it showing like this..it also showing default page size of slickgrid..

 pagination: {
        pageSizes: [10, 200, 250, 500, 5000],
        pageSize: 10
      },

Body:
You have a typo in your page sizes, it won't work with decimal numbers and your pageSize must be a valid number that is included in pageSizes but isn't in your case because of the decimal number, it works fine in the lib as shown by Example 30

this.gridOptions = {
  enablePagination: true,
  pagination: {
    pageSize: 10,
    pageSizes: [10, 200, 250, 500, 5000]
  },
};

EDIT

There was actually a bug identified to set pagination via global configuration and that was fixed and released under a patch version 4.1.2 of Angular-Slickgrid


问:
imap_unordered, but with a lazy flattened generator
I've got a problem that can already be solved by multiprocessing.Pool but the solution is not very optimal. Namely, what I have is have a rather small set of inputs each of which maps to a large dataset. While I can use imap_unordered with a function returning a list, this is far from efficient, because each of the large datasets must be returned as a list.

My function could return them as a generator for lower latency instead, but I cannot return a generator from a subprocess.

A dummy example:

```<code>import time
import multiprocessing

def generate(x):
    for j in range(x, x + 10):
        yield j
        time.sleep(1)

def wrapper(x):
    return list(generate(x))

with multiprocessing.Pool(10) as pool:
    for ready in pool.imap_unordered(wrapper, range(0, 100, 10)):
        for item in set(ready):  # to show that order does not matter:
            print(item)
</code>```

The problem is that while the entire run now takes only 10th of the time of running sequentially, I still need to wait 10 seconds for the very first result, which could be available right away by:

```<code>def generate(x):
    for j in range(x, x + 10):
        yield j
        time.sleep(1)

for ready in map(generate, range(0, 100, 10):
    for item in set(ready):
        print(item)
</code>```

Which will print first item without delay, but takes 100 seconds to run.

What I cannot do is to subdivide the problem further, the generators in the subprocesses need to be evaluated lazily by the consumer:

```<code>def generate(x):
    for j in range(x, x + 10):
        yield j
        time.sleep(1)

with multiprocessing.Pool(10) as pool:
    for item in pool.??flatmap_unordered??(generate, range(0, 100, 10)):
        print(item)
</code>```

which would print the first item right away, yet takes only ~10 seconds to run!

How could I achieve that?

答:
There seems to be no builtin way for a Pool to incrementally collect generated items. However, it is reasonably straightforward to write your own "flat map" helper.

The general idea is to have a wrapper in the pool processes that runs the iterator and pushes each individual item to a queue. In the main process, there just is a plain loop that gets and yields each item.

```<code>import functools
import multiprocessing

def flatmap(pool: multiprocessing.Pool, func, iterable, chunksize=None):
    """A flattening, unordered equivalent of Pool.map()"""
    # use a queue to stream individual results from processes
    queue = multiprocessing.Manager().Queue()
    # reuse task management and mapping of Pool
    pool.map_async(
        functools.partial(_flat_mappper, queue, func),
        iterable,
        chunksize,
        # callback: push a signal that everything is done
        lambda _: queue.put(None),
        lambda err: queue.put((None, err))
    )
    # yield each result as it becomes available
    while True:
        item = queue.get()
        if item is None:
            break
        result, err = item
        if err is None:
            yield result
        else:
            raise err

def _flat_mappper(queue: multiprocessing.Queue, func, *args):
    """Helper to run `(*args) -> iter` and stream results to a queue"""
    for item in func(*args):
        queue.put((item, None))
</code>```

If desired, one could patch the Pool type itself to have flatmap as a method instead of a function.

The flatmap helper can be directly used to accumulate results across the generators. For the example case, it finishes in a bit more than 10 seconds.

import time

def generate(x):
    for j in range(x, x + 10):
        yield j
        time.sleep(1)

if __name__ == "__main__":
    with multiprocessing.Pool(10) as pool:
        for item in flatmap(pool, generate, range(0, 100, 10)):
            print(item)
```

Body:
I've got a problem that can already be solved by multiprocessing.Pool but the solution is not very optimal. Namely, what I have is have a rather small set of inputs each of which maps to a large dataset. While I can use imap_unordered with a function returning a list, this is far from efficient, because each of the large datasets must be returned as a list.

My function could return them as a generator for lower latency instead, but I cannot return a generator from a subprocess.

A dummy example:

import time
import multiprocessing

def generate(x):
    for j in range(x, x + 10):
        yield j
        time.sleep(1)

def wrapper(x):
    return list(generate(x))

with multiprocessing.Pool(10) as pool:
    for ready in pool.imap_unordered(wrapper, range(0, 100, 10)):
        for item in set(ready):  # to show that order does not matter:
            print(item)

The problem is that while the entire run now takes only 10th of the time of running sequentially, I still need to wait 10 seconds for the very first result, which could be available right away by:

def generate(x):
    for j in range(x, x + 10):
        yield j
        time.sleep(1)

for ready in map(generate, range(0, 100, 10):
    for item in set(ready):
        print(item)

Which will print first item without delay, but takes 100 seconds to run.

What I cannot do is to subdivide the problem further, the generators in the subprocesses need to be evaluated lazily by the consumer:

def generate(x):
    for j in range(x, x + 10):
        yield j
        time.sleep(1)

with multiprocessing.Pool(10) as pool:
    for item in pool.??flatmap_unordered??(generate, range(0, 100, 10)):
        print(item)

which would print the first item right away, yet takes only ~10 seconds to run!

How could I achieve that?

Body:
There seems to be no builtin way for a Pool to incrementally collect generated items. However, it is reasonably straightforward to write your own "flat map" helper.

The general idea is to have a wrapper in the pool processes that runs the iterator and pushes each individual item to a queue. In the main process, there just is a plain loop that gets and yields each item.

import functools
import multiprocessing

def flatmap(pool: multiprocessing.Pool, func, iterable, chunksize=None):
    """A flattening, unordered equivalent of Pool.map()"""
    # use a queue to stream individual results from processes
    queue = multiprocessing.Manager().Queue()
    # reuse task management and mapping of Pool
    pool.map_async(
        functools.partial(_flat_mappper, queue, func),
        iterable,
        chunksize,
        # callback: push a signal that everything is done
        lambda _: queue.put(None),
        lambda err: queue.put((None, err))
    )
    # yield each result as it becomes available
    while True:
        item = queue.get()
        if item is None:
            break
        result, err = item
        if err is None:
            yield result
        else:
            raise err

def _flat_mappper(queue: multiprocessing.Queue, func, *args):
    """Helper to run `(*args) -> iter` and stream results to a queue"""
    for item in func(*args):
        queue.put((item, None))

If desired, one could patch the Pool type itself to have flatmap as a method instead of a function.

The flatmap helper can be directly used to accumulate results across the generators. For the example case, it finishes in a bit more than 10 seconds.

import time

def generate(x):
    for j in range(x, x + 10):
        yield j
        time.sleep(1)

if __name__ == "__main__":
    with multiprocessing.Pool(10) as pool:
        for item in flatmap(pool, generate, range(0, 100, 10)):
            print(item)


答:
Have you tried putting the icon along with the text to the innerHTML?

jQuery(document).ready(function($){

  $(document.getElementById("pause_btn")).click(function(){
      document.getElementById("pause_btn").innerHTML = 'Resumepause_circle_outline'
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <script src = "Sources/js/select_require.js"></script>
    <script src = "Sources/js/routes.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <body>
    Pause<i class="material-icons right">pause_circle_outline</i>
  </body>
</html></code>```

Title: How can i change a text of a button without changing it's icon

Body:
Have you tried putting the icon along with the text to the innerHTML?

jQuery(document).ready(function($){

  $(document.getElementById("pause_btn")).click(function(){
      document.getElementById("pause_btn").innerHTML = 'Resume<i class="material-icons right">pause_circle_outline</i>'
  });
})

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <script src = "Sources/js/select_require.js"></script>
    <script src = "Sources/js/routes.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <body>
    <a class="waves-effect waves-light btn" id="pause_btn">Pause<i class="material-icons right">pause_circle_outline</i></a>
  </body>
</html>


问:
CouchDB Filtered Replication
Trying out filters for replication, I stumbled upon a problem.
While my filter is working as an entry in the _replicator database, I doesn't when using cURL.

The filter in the design document is:

```<code>{
    "_id": "_design/partial",
    "filters": {
        "mobile": "function(doc, req) {
            if (doc._attachments) {
                var result = new Boolean(true);
                for (attachment in doc._attachments) {
                    if (attachment.content_type == 'image/jpeg') {
                        return true;
                    }
                    if (doc._attachments.length > 1024) {
                        result = false;
                    }
                }
                return result;
            } else {
                return true;
            }
        }"
    }
}
</code>```

The cURL line:

curl -X POST http://admin:pass@192.168.178.13:5985/_replicate -d '{\"source\":\"http://admin:pass@192.168.2:5984/docs2\",\"target\":\"docs2_partial\",\"filter\":\"partial/mobile\",\"create_target\":true}' -H "Content-Type: application/json"

I created _design/partial document on both target and source, but all documents are being replicated. Even the one with an attached binary bigger than 1 MB.
Any help is appreciated!

The cURL reply is:

```<code>{"ok":true,"session_id":"833ff96d21278a24532d116f57c45f31","source_last_seq":32,"replication_id_version":2,"history":[{"session_id":"833ff96d21278a24532d116f57c45f31","start_time":"Wed, 17 Aug 2011 21:43:46 GMT","end_time":"Wed, 17 Aug 2011 21:44:22 GMT","start_last_seq":0,"end_last_seq":32,"recorded_seq":32,"missing_checked":0,"missing_found":28,"docs_read":28,"docs_written":28,"doc_write_failures":0}]}
</code>```

Using either " instead of \" or " instead of ' the result is:

```<code>{"error":"bad_request","reason":"invalid UTF-8 JSON: [...]}
</code>```

答:
Now I think perhaps the logic of your filter function simply has a bug. Here is how I read your filter policy:

All docs that have no attachments pass

All docs that have an image/jpeg attachment pass

Docs with more than 1,024 attachments fail

In any other case, the docs pass

That sounds like perhaps an incorrect policy. Another way to restate this policy is "Docs with more than 1024 attachments fail, everything else passes." However since you wrote so much code, I suspect my summary is not the true policy.

Another quick note, on what looks like a bug. Given:

```<code>for (attachment in doc._attachments) { /* ... */ }
</code>```

The attachment variable will be things like "index.html" or "me.jpeg", i.e. filenames. To get the attachment content-type, you need:

```<code>var type;

// This is WRONG
type = attachment.content_type; // type set to undefined

// This is RIGHT
type = doc._attachments[attachment].content_type; // type set to "text/html" etc.
</code>```

To avoid this bug, you could change your code to make things more clear:

```<code>for (attachment_filename in doc._attachments) { /* ... */ }
</code>```

Next, doc._attachments.length will tell you the number of attachments in the document, not for example the length of the current attachment. It is odd that you test for that inside the loop, because the expression will never change. Are you trying to test for attachment size instead?

Title: CouchDB Filtered Replication

Body:
Trying out filters for replication, I stumbled upon a problem.
While my filter is working as an entry in the _replicator database, I doesn't when using cURL.

The filter in the design document is:

{
    "_id": "_design/partial",
    "filters": {
        "mobile": "function(doc, req) {
            if (doc._attachments) {
                var result = new Boolean(true);
                for (attachment in doc._attachments) {
                    if (attachment.content_type == 'image/jpeg') {
                        return true;
                    }
                    if (doc._attachments.length > 1024) {
                        result = false;
                    }
                }
                return result;
            } else {
                return true;
            }
        }"
    }
}

The cURL line:

curl -X POST http://admin:pass@192.168.178.13:5985/_replicate -d '{\"source\":\"http://admin:pass@192.168.2:5984/docs2\",\"target\":\"docs2_partial\",\"filter\":\"partial/mobile\",\"create_target\":true}' -H "Content-Type: application/json"

I created _design/partial document on both target and source, but all documents are being replicated. Even the one with an attached binary bigger than 1 MB.
Any help is appreciated!

The cURL reply is:

{"ok":true,"session_id":"833ff96d21278a24532d116f57c45f31","source_last_seq":32,"replication_id_version":2,"history":[{"session_id":"833ff96d21278a24532d116f57c45f31","start_time":"Wed, 17 Aug 2011 21:43:46 GMT","end_time":"Wed, 17 Aug 2011 21:44:22 GMT","start_last_seq":0,"end_last_seq":32,"recorded_seq":32,"missing_checked":0,"missing_found":28,"docs_read":28,"docs_written":28,"doc_write_failures":0}]}

Using either " instead of \" or " instead of ' the result is:

{"error":"bad_request","reason":"invalid UTF-8 JSON: [...]}

Body:
Now I think perhaps the logic of your filter function simply has a bug. Here is how I read your filter policy:

All docs that have no attachments pass

All docs that have an image/jpeg attachment pass

Docs with more than 1,024 attachments fail

In any other case, the docs pass

That sounds like perhaps an incorrect policy. Another way to restate this policy is "Docs with more than 1024 attachments fail, everything else passes." However since you wrote so much code, I suspect my summary is not the true policy.

Another quick note, on what looks like a bug. Given:

for (attachment in doc._attachments) { /* ... */ }

The attachment variable will be things like "index.html" or "me.jpeg", i.e. filenames. To get the attachment content-type, you need:

var type;

// This is WRONG
type = attachment.content_type; // type set to undefined

// This is RIGHT
type = doc._attachments[attachment].content_type; // type set to "text/html" etc.

To avoid this bug, you could change your code to make things more clear:

for (attachment_filename in doc._attachments) { /* ... */ }

Next, doc._attachments.length will tell you the number of attachments in the document, not for example the length of the current attachment. It is odd that you test for that inside the loop, because the expression will never change. Are you trying to test for attachment size instead?


问:
Outlook Add-In: how to simulate automatic reply with external service?

Background

I previously asked this question: Outlook Add-In: how to automatically reply based on custom logic?

As the answerers @EugeneAstafiev and @OutlookAdd-insTeam-MSFT noted, Outlook web add-ins can only run on a currently selected item. This does not work for an automatic reply use case, since automatic replies should send on receiving a new email, regardless of whether the user has selected it.

Question

Despite this, I know add-ins can categorize incoming mail, e.g. move/copy them to different folders. Would it be possible to detect incoming mail in that sense and then have the add-in call out to an external service to send an automatic reply in that way?

Example

For example:

Add-in copies incoming email to folder.

Add-in hits external API endpoint.

External service sends auto reply email (perhaps using SMTP or similar?).

Clarifications

I'm not looking to use the built-in automatic replies feature in Outlook, since that has very limited options. (Roughly speaking, it can only send one message to all senders or one to contacts and another to non-contacts.) I want this simulated automatic reply to be sent based on custom logic, e.g. whether the external service has verified the sender's email.

Is this possible? If so, any recommendations on how best to implement it?

Thank you!

答:
Currently, the feature to invoke outlook add-ins without any item context is not a part of the product.

We track Outlook add-in feature requests on our Tech Community Page. Please submit your request there and choose the appropriate label(s). Feature requests on Tech Community are considered when we go through our planning process.


答:
Without looking into it too closely, my assumption is that this occurs because the first query only has to read to the 50th record to return results, whereas the second query has to read six million before returning results. Basically, the first query just shorts out quicker.

I would assume that this has an incredible amount to do with the makeup of the table - field types and keys, etc.

If a record is made up of fixed-length fields (e.g. CHAR vs. VARCHAR), then the DBMS can just calculate where the nth record starts and jumps there. If its variable length, then you would have to read the records to determine where the nth record starts. Similarly, I'd further assume that tables which have appropriate primary keys would be quicker to query than those without such keys.

Title: QUERY speed with limit and milion records

Body:
Hi i have a 7milion records db table for testing query speed.

I tested up my 2 queries which are the same query with different limit parametres:

query 1 -

SELECT    *
FROM      table
LIMIT     20, 50;

query 2 -

SELECT    *
FROM      table
LIMIT     6000000, 6000030;

query exec times are:

query 1 - 0.006 sec

query 2 - 5.500 sec

In both of these queries, I am fetching same number of records, but in the second case it's taking more time. Can someone please explain the reasons behind this?


问:
What is the rationale for "structure with flexible array member shall not be a member of a structure"?
C11, 6.7.2.1 Structure and union specifiers, Constraints, 3 (emphasis added):

A structure or union shall not contain a member with incomplete or function type (hence,
a structure shall not contain an instance of itself, but may contain a pointer to an instance
of itself), except that the last member of a structure with more than one named member
may have incomplete array type; such a structure (and any union containing, possibly
recursively, a member that is such a structure) shall not be a member of a structure or an
element of an array.

Rationale for C, Revision 5.10, April-2003 (emphasis added):

Similarly, structures containing flexible arrays can’t occur in other structures or in arrays.

So, Rationale for C doesn't provide a rationale. What is the rationale?

答:
A structure with a flexible array member can only really be used properly if allocated dynamically.  For example:

```<code>struct s1 {
    int a;
    int b;
    int c[];
};
...
struct s1 *x = malloc(sizeof(struct s1) + 5 * sizeof(int));
</code>```

Let's assume typical struct padding and sizeof(int)==4.  That would make sizeof(struct s1)==8.

Now imagine if such a struct was a member of another struct:

```<code>struct s2 {
    int a;
    struct s1 b;
    int c;
};
</code>```

The b member of struct s2 would start at offset 4.  But what about the c member?  Given that sizeof(struct s1)==8, that would make member c have offset 12.  But then there's no way for the b member to have any space set aside for its containing c member.

Because the offset of a given struct member is set at compile time, there is no way to allocate space for the flexible array member c inside of struct s1.

In theory, if the struct with a flexible array member was the last member:

```<code>struct s2 {
    int a;
    int b;
    struct s1 c;
};
</code>```

Then it could work, but then then means that struct s2 is also subject to the same rules as a struct with a flexible array member, causing a cascading effect.  This would make it more difficult to determine which structures are subject to this rule.

So a struct with a flexible array member is not allowed as a member of another struct or an array.

Body:
A structure with a flexible array member can only really be used properly if allocated dynamically.  For example:

struct s1 {
    int a;
    int b;
    int c[];
};
...
struct s1 *x = malloc(sizeof(struct s1) + 5 * sizeof(int));

Let's assume typical struct padding and sizeof(int)==4.  That would make sizeof(struct s1)==8.

Now imagine if such a struct was a member of another struct:

struct s2 {
    int a;
    struct s1 b;
    int c;
};

The b member of struct s2 would start at offset 4.  But what about the c member?  Given that sizeof(struct s1)==8, that would make member c have offset 12.  But then there's no way for the b member to have any space set aside for its containing c member.

Because the offset of a given struct member is set at compile time, there is no way to allocate space for the flexible array member c inside of struct s1.

In theory, if the struct with a flexible array member was the last member:

struct s2 {
    int a;
    int b;
    struct s1 c;
};

Then it could work, but then then means that struct s2 is also subject to the same rules as a struct with a flexible array member, causing a cascading effect.  This would make it more difficult to determine which structures are subject to this rule.

So a struct with a flexible array member is not allowed as a member of another struct or an array.


问:
Load file from same folder as Python 3.x script inside package
Opening and loading data from a file that is situated in the same folder as the currently executing Python 3.x script can be done like this:

```<code>import os

mydata_path = os.path.join(os.path.dirname(__file__), "mydata.txt")
with open(mydata_path, 'r') as file:
    data = file.read()
</code>```

However once the script and mydata.txt files become part of a Python package this is not as straight forward anymore. I have managed to do this using a concoction of functions from the pkg_resources module such as resource_exists(), resource_listdir(), resource_isdir() and resource_string(). I won't put my code here because it is horrible and broken (but it sort of works).

Anyhow my question is; is there no way to manage the loading of a file in the same folder as the currently executing Python script that works regardles of wether the files are in a package or not?

答:
You can use importlib.resources.read_text in order to read a file that's located relative to a package:

from importlib.resources import read_text

data = read_text('mypkg.foo', 'mydata.txt')
```

Body:
Opening and loading data from a file that is situated in the same folder as the currently executing Python 3.x script can be done like this:

import os

mydata_path = os.path.join(os.path.dirname(__file__), "mydata.txt")
with open(mydata_path, 'r') as file:
    data = file.read()

However once the script and mydata.txt files become part of a Python package this is not as straight forward anymore. I have managed to do this using a concoction of functions from the pkg_resources module such as resource_exists(), resource_listdir(), resource_isdir() and resource_string(). I won't put my code here because it is horrible and broken (but it sort of works).

Anyhow my question is; is there no way to manage the loading of a file in the same folder as the currently executing Python script that works regardles of wether the files are in a package or not?


问:
Azure Databricks Execution Fail - CLOUD_PROVIDER_LAUNCH_FAILURE
I'm using Azure DataFactory for my data ingestion and using an Azure Databricks notebook through ADF's Notebook activity.

The Notebook uses an existing instance pool of Standard DS3_V2 (2-5 nodes autoscaled) with 7.3LTS Spark Runtime version. The same Azure subscription is used by multiple teams for their respective data pipelines.

During the ADF pipeline execution, I'm facing a notebook activity failure frequently with the below error message

```<code>{
  "reason": {
    "code": "CLOUD_PROVIDER_LAUNCH_FAILURE",
    "type": "CLOUD_FAILURE",
    "parameters": {
      "azure_error_code": "SubnetIsFull",
      "azure_error_message": "Subnet /subscriptions/<Subscription>/resourceGroups/<RG>/providers/Microsoft.Network/virtualNetworks/<VN>/subnets/<subnet> with address prefix 10.237.35.128/26 does not have enough capacity for 2 IP addresses."
    }
  }
}
</code>```

Can anyone explain what this error is and how I can reduce the occurrence of this? (The documents I found are not explanatory)

答:
The problem arise from the fact that when your workspace was created, the network and subnet sizes wasn't planned correctly (see docs). As result, when you're trying to launch a cluster, then there is not enough IP addresses in a given subnet, and given this error.

Unfortunately right now it's not possible to expand network/subnets size, so if you need a bigger network, then you need to deploy a new workspace and migrate into it.

Body:
I'm using Azure DataFactory for my data ingestion and using an Azure Databricks notebook through ADF's Notebook activity.

The Notebook uses an existing instance pool of Standard DS3_V2 (2-5 nodes autoscaled) with 7.3LTS Spark Runtime version. The same Azure subscription is used by multiple teams for their respective data pipelines.

During the ADF pipeline execution, I'm facing a notebook activity failure frequently with the below error message

{
  "reason": {
    "code": "CLOUD_PROVIDER_LAUNCH_FAILURE",
    "type": "CLOUD_FAILURE",
    "parameters": {
      "azure_error_code": "SubnetIsFull",
      "azure_error_message": "Subnet /subscriptions/<Subscription>/resourceGroups/<RG>/providers/Microsoft.Network/virtualNetworks/<VN>/subnets/<subnet> with address prefix 10.237.35.128/26 does not have enough capacity for 2 IP addresses."
    }
  }
}

Can anyone explain what this error is and how I can reduce the occurrence of this? (The documents I found are not explanatory)


问:
Nodejs - How do I identify wheather the user from Android OS or IOS in nodejs backend
What I want is Identify the user then redirect from backend to some url.</p>
```<code>app.get('/someurl', function (req, res, next) {

if(android OS){
res.redirect("https://playstore")
}else{
res.redirect("https://appstore")
}

})
</code>```

答:
You could use the ua-parser-js package.

npm install ua-parser-js

From there you can follow the docs.
Or do the following:

```<code>const parser = require("ua-parser-js")
app.get('/someurl', function (req, res, next) {
  if(parser(req.headers["user-agent"]).getOS().name === "Android[-x86]") {
    res.redirect("https://playstore")
  } else{
    res.redirect("https://appstore")
  }
})
</code>```

Body:
What I want is Identify the user then redirect from backend to some url.

app.get('/someurl', function (req, res, next) {

if(android OS){
res.redirect("https://playstore")
}else{
res.redirect("https://appstore")
}

})

Body:
You could use the ua-parser-js package.

npm install ua-parser-js

From there you can follow the docs.
Or do the following:

const parser = require("ua-parser-js")
app.get('/someurl', function (req, res, next) {
  if(parser(req.headers["user-agent"]).getOS().name === "Android[-x86]") {
    res.redirect("https://playstore")
  } else{
    res.redirect("https://appstore")
  }
})


问:
R - Specify column name in function model using character strings
I am trying to perform an STL decomposition over multiple columns in a dataframe using the feasts package by Rob Hyndman (Forecasting Principles and Practice edition 3 author).

The code below works

```<code>dcmp1 <- a_tibble %>%
  model(stl = STL(Cost))
components(dcmp1)
</code>```

But now I want to generate multiple decompositions for different variables within a_tibble using a for loop.  The problem I face is that I iterate over the names of the columns as if they were strings, and that yields an error

Specfically, I am running this code:

```<code>for (col_name in c("Cost", "sqrt_cost")){

  dcmp <- model(a_tibble, stl = STL(.data[[col_name]]))

}
</code>```

This yields the following warning everytime the statement within the for loop is run:

```<code>Warning: 1 error encountered for stl
[1] values must be length 1,
 but FUN(X[[1]]) result is length 0
</code>```

I have tried multiple approaches to be able make decompositions for multiple variables using iteration but to no avail.

Couls someone please let me know how I should iterate to avoid this problem?

Thanks

答:
Ok, so I resorted to this post here:

dplyr - using column names as function arguments

It solved the issue. And it made me feel like I would need to study quite in depth this "quosure" thing.

Body:
I am trying to perform an STL decomposition over multiple columns in a dataframe using the feasts package by Rob Hyndman (Forecasting Principles and Practice edition 3 author).

The code below works

dcmp1 <- a_tibble %>%
  model(stl = STL(Cost))
components(dcmp1)

But now I want to generate multiple decompositions for different variables within a_tibble using a for loop.  The problem I face is that I iterate over the names of the columns as if they were strings, and that yields an error

Specfically, I am running this code:

for (col_name in c("Cost", "sqrt_cost")){

  dcmp <- model(a_tibble, stl = STL(.data[[col_name]]))

}

This yields the following warning everytime the statement within the for loop is run:

Warning: 1 error encountered for stl
[1] values must be length 1,
 but FUN(X[[1]]) result is length 0

I have tried multiple approaches to be able make decompositions for multiple variables using iteration but to no avail.

Couls someone please let me know how I should iterate to avoid this problem?

Thanks


问:
PROTÉGÉ SPARQL QUERY TAB: cannot query for ontology-specific classes
I am using SPARQL Query tab in Protege 5 to query an OWL ontology I have been constructing. I succeded in many kinds of queries, but when I use some specific class of my ontology inside the very same queries (that are apparently well formed) they return no results. Following, two of the problematic queries - assuming "Event" as one of the concepts of the ontology (http://www.semanticweb.org/ontologies/2014/5/MyOnto#Event):

```<code>PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX onto: <http://www.semanticweb.org/ontologies/2014/5/MyOnto#>

SELECT ?a  WHERE { ?a rdfs:subClassOf onto:Event }
</code>```

and, with the same prefixes

```<code>SELECT ?a  WHERE { ?a rdfs:range onto:Event }
</code>```

Both return no results. However, if I substitute "onto:Event" for, let's say, ?b, both return a long list of results - inclunding Event as a match for ?b.

Is it something I'm misusing or forgetting (although I've seen this pattern in several links on internet with people claiming to have got results) or is it a limitation of SPARQL or some issue of the Protege tab?

答:
I had the same problem, whenever using an ontology specific class there were no results although there should have been. My ontology (pizza.owl) was loaded from a local file.
I found that it is required to add the file name in the PREFIX.

```<code>PREFIX : <http://www.co-ode.org/ontologies/pizza/pizza.owl#>
</code>```

After that I got the information that I expected.

Body:
I am using SPARQL Query tab in Protege 5 to query an OWL ontology I have been constructing. I succeded in many kinds of queries, but when I use some specific class of my ontology inside the very same queries (that are apparently well formed) they return no results. Following, two of the problematic queries - assuming "Event" as one of the concepts of the ontology (http://www.semanticweb.org/ontologies/2014/5/MyOnto#Event):

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX onto: <http://www.semanticweb.org/ontologies/2014/5/MyOnto#>

SELECT ?a  WHERE { ?a rdfs:subClassOf onto:Event }

and, with the same prefixes

SELECT ?a  WHERE { ?a rdfs:range onto:Event }

Both return no results. However, if I substitute "onto:Event" for, let's say, ?b, both return a long list of results - inclunding Event as a match for ?b.

Is it something I'm misusing or forgetting (although I've seen this pattern in several links on internet with people claiming to have got results) or is it a limitation of SPARQL or some issue of the Protege tab?

Body:
I had the same problem, whenever using an ontology specific class there were no results although there should have been. My ontology (pizza.owl) was loaded from a local file.
I found that it is required to add the file name in the PREFIX.

PREFIX : <http://www.co-ode.org/ontologies/pizza/pizza.owl#>

After that I got the information that I expected.


问:
How to disable or uncheck the toggle switch when clicking on the icon in multiple icons
In my angular application I have some icons and on right side I have one toggle switch by default the switch is in ON stage
and when we click on any of the icon the color will change from white to red among multiple icons the switch should be turned to OFF stage and vice versa (means when we click on icon(the color of icon will change) the switch is in OFF state and when we click on Switch the colored icon will again changed to previous white color.

and My code is given below:

.component.html

```<code> <label class="rating-switch" id="toggleSwitch">
      <input class="rating-checkbox" type="checkbox" checked >
      <div class="slide round" >

      </div>
    </label>    <span class="no-rating-switch" >No Rating</span>

<div class="container">
        <span class="iconss"></span><i (click)="selectedIcon = icon.id" class="stl" [ngClass]="icon.class"
  [style.color]="selectedIcon === icon.id ? '#FF0000' : '#ffffff'" *ngFor="let icon of iconsArray"></i>
</div>
</code>```

.component.ts

```<code> iconsArray = [
    { id: 1, class: "icon-onlife-smiley-face-1" },
    { id: 2, class: "icon-onlife-smiley-face-2" },
    { id: 3, class: "icon-onlife-smiley-face-3" },
    { id: 4, class: "icon-onlife-smiley-face-4" },
    { id: 5, class: "icon-onlife-smiley-face-5" },
    { id: 6, class: "icon-onlife-smiley-face-6" }
]
selectedIcon = 0;

</code>```

.component.css

```<code>.rating-switch{
  position: relative;
  width: 48px;
  height: 17px;
  margin-top: 3em;

}
.switch, .rating-checkbox {
  opacity: 0;
  width: 0;
  height: 0;
}
.slide {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}
.slide:before {
  position: absolute;
  content: "";
  height: 17px;
  width: 17px;
  left: 1.2px;
  bottom: 2px;
  top:0.5px;
  background-color: #2b547e;
  -webkit-transition: .4s;
  transition: .4s;
}
.rating-checkbox:checked + .slide {
  background-color: #87d3f8;
}

.rating-checkbox:focus + .slide {
  box-shadow: 0 0 1px #87d3f8;
}

.rating-checkbox:checked + .slide:before {
  -webkit-transform: translateX(29px);
  -ms-transform: translateX(29px);
  transform: translateX(29px);
}
.slide.round {
  border-radius: 34px;
}.slide.round:before {
  border-radius: 50%;
}
</code>```

So my requirement is when we click on any of the icon the switch should be OFF(unchecked)when we click on switch the colored icon will changed white color .

Can anyone help me on this

答:
```<code><label class="rating-switch" id="toggleSwitch">
    <input class="rating-checkbox" type="checkbox" [(ngModel)]="rating">
    <div class="slide round">

    </div>
</label> <span class="no-rating-switch">No Rating</span>

<div class="container">
    <span class="iconss"></span>
    <i (click)="selectedIcon = icon.id" class="stl" [ngClass]="icon.class"
        [style.color]="(selectedIcon === icon.id && !rating) ? '#FF0000' : '#ffffff'"
        *ngFor="let icon of iconsArray"></i>
</div>
</code>```

in ts file

```<code>rating = true;
iconsArray = [
    { id: 1, class: "icon-onlife-smiley-face-1" },
    { id: 2, class: "icon-onlife-smiley-face-2" },
    { id: 3, class: "icon-onlife-smiley-face-3" },
    { id: 4, class: "icon-onlife-smiley-face-4" },
    { id: 5, class: "icon-onlife-smiley-face-5" },
    { id: 6, class: "icon-onlife-smiley-face-6" }
]
selectedIcon = 0;
</code>```

Body:
In my angular application I have some icons and on right side I have one toggle switch by default the switch is in ON stage
and when we click on any of the icon the color will change from white to red among multiple icons the switch should be turned to OFF stage and vice versa (means when we click on icon(the color of icon will change) the switch is in OFF state and when we click on Switch the colored icon will again changed to previous white color.

and My code is given below:

.component.html

      <input class="rating-checkbox" type="checkbox" checked >

        No Rating

.component.ts

 iconsArray = [
    { id: 1, class: "icon-onlife-smiley-face-1" },
    { id: 2, class: "icon-onlife-smiley-face-2" },
    { id: 3, class: "icon-onlife-smiley-face-3" },
    { id: 4, class: "icon-onlife-smiley-face-4" },
    { id: 5, class: "icon-onlife-smiley-face-5" },
    { id: 6, class: "icon-onlife-smiley-face-6" }
]
selectedIcon = 0;

.component.css

.rating-switch{
  position: relative;
  width: 48px;
  height: 17px;
  margin-top: 3em;

}
.switch, .rating-checkbox {
  opacity: 0;
  width: 0;
  height: 0;
}
.slide {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}
.slide:before {
  position: absolute;
  content: "";
  height: 17px;
  width: 17px;
  left: 1.2px;
  bottom: 2px;
  top:0.5px;
  background-color: #2b547e;
  -webkit-transition: .4s;
  transition: .4s;
}
.rating-checkbox:checked + .slide {
  background-color: #87d3f8;
}

.rating-checkbox:focus + .slide {
  box-shadow: 0 0 1px #87d3f8;
}

.rating-checkbox:checked + .slide:before {
  -webkit-transform: translateX(29px);
  -ms-transform: translateX(29px);
  transform: translateX(29px);
}
.slide.round {
  border-radius: 34px;
}.slide.round:before {
  border-radius: 50%;
}

So my requirement is when we click on any of the icon the switch should be OFF(unchecked)when we click on switch the colored icon will changed white color .

Can anyone help me on this

Body:
<label class="rating-switch" id="toggleSwitch">
    <input class="rating-checkbox" type="checkbox" [(ngModel)]="rating">
    <div class="slide round">

    </div>
</label> <span class="no-rating-switch">No Rating</span>

<div class="container">
    <span class="iconss"></span>
    <i (click)="selectedIcon = icon.id" class="stl" [ngClass]="icon.class"
        [style.color]="(selectedIcon === icon.id && !rating) ? '#FF0000' : '#ffffff'"
        *ngFor="let icon of iconsArray"></i>
</div>

in ts file

rating = true;
iconsArray = [
    { id: 1, class: "icon-onlife-smiley-face-1" },
    { id: 2, class: "icon-onlife-smiley-face-2" },
    { id: 3, class: "icon-onlife-smiley-face-3" },
    { id: 4, class: "icon-onlife-smiley-face-4" },
    { id: 5, class: "icon-onlife-smiley-face-5" },
    { id: 6, class: "icon-onlife-smiley-face-6" }
]
selectedIcon = 0;


问:
Why the url of youtube will be changed when I hover mouse on a video?
I was surfing  on youtube and I realized something.

When I hover mouse on a video, then the url will be changed.

Interestingly, this happens in some browsers.
What's the matter?
 Why does string start with &? https://www.youtube.com/?&ab_channel=NASA

What is the benefit to change the URL?

答:
Interestingly, this happens in some browsers.

Different browser different support, a what you see is what you get is a standard we all want and must write our scripts specific to each browser if a feature requires it. In this case the new feature may not be widely supported or their coding wasn't compliant enough to give you this exact result each browser.

What's the matter?

No problem here, the URL is a tiny-bit broken but won't impact site performance unless you happen to error out the server and crash the entire network.

Why does string start with ?& https://www.youtube.com/?&ab_channel=NASA
What is the benefit to change the URL?

A URL alone has no parameters passed to it, so youtube.com. When a parameter is passed through the site on its HTTPS request will check these and determine what it is you want. So the response will return NASA cause ab_channel included it.

Because ? has nothing after it like ?video=asd89sa982 it's treated as undefined and serves no value or importance.

YouTube can fix it if they desire with script adjustment.


问:
php replace array value
I have following mysql query function:

```<code>$query_number = 2;
$query        = "SELECT * FROM $table ORDER by date desc limit $query_number";
$results      = mysql_query($query);

$message['posts']    = $results;
echo json_encode($message);
exit;
</code>```

I get an array of objects with multiple keys:

```<code>Array
(
[0] => stdClass Object
    (
        [ID] => 4983
        [post_id] => 56357
        [date] => 2016-06-04 23:45:28
    )

[1] => stdClass Object
    (
        [ID] => 4982
        [post_id] => 56241
        [date] => 2016-06-04 22:58:27
    )
 )
</code>```

I am sending the whole array to the js via ajax.

However, I want to change the date format to "ago" and send it to js.

I have the "ago" function, but I am not sure how to target the date value and put it back to its original place (replacement).

Any help would be much appreciate!

Thanks!

答:
Because you are processing an array of objects -- and objects are modifiable by reference by default -- you can set up ago() to modify by reference as well and use array_walk().

Code: (Demo)

```<code>function ago(&$v) {
    $v = date('M Y', strtotime($v)); // do whatever
}

array_walk($array, fn($obj) => ago($obj->date));
var_export($array);
</code>```

Output:

```<code>array (
  0 =>
  (object) array(
     'ID' => 4983,
     'post_id' => 56357,
     'date' => 'Jun 2016',
  ),
  1 =>
  (object) array(
     'ID' => 4982,
     'post_id' => 56241,
     'date' => 'Jun 2016',
  ),
)
</code>```

Using PHP7.4's arrow function syntax means you dont need to use use() to bring ago() into array_walk()'s callback scope.  Also, array_walk() will ignore the return value generated by the arrow.

Title: php replace array value

Body:
I have following mysql query function:

$query_number = 2;
$query        = "SELECT * FROM $table ORDER by date desc limit $query_number";
$results      = mysql_query($query);

$message['posts']    = $results;
echo json_encode($message);
exit;

I get an array of objects with multiple keys:

Array
(
[0] => stdClass Object
    (
        [ID] => 4983
        [post_id] => 56357
        [date] => 2016-06-04 23:45:28
    )

[1] => stdClass Object
    (
        [ID] => 4982
        [post_id] => 56241
        [date] => 2016-06-04 22:58:27
    )
 )

I am sending the whole array to the js via ajax.

However, I want to change the date format to "ago" and send it to js.

I have the "ago" function, but I am not sure how to target the date value and put it back to its original place (replacement).

Any help would be much appreciate!

Thanks!

Body:
Because you are processing an array of objects -- and objects are modifiable by reference by default -- you can set up ago() to modify by reference as well and use array_walk().

Code: (Demo)

function ago(&$v) {
    $v = date('M Y', strtotime($v)); // do whatever
}

array_walk($array, fn($obj) => ago($obj->date));
var_export($array);

Output:

array (
  0 =>
  (object) array(
     'ID' => 4983,
     'post_id' => 56357,
     'date' => 'Jun 2016',
  ),
  1 =>
  (object) array(
     'ID' => 4982,
     'post_id' => 56241,
     'date' => 'Jun 2016',
  ),
)

Using PHP7.4's arrow function syntax means you dont need to use use() to bring ago() into array_walk()'s callback scope.  Also, array_walk() will ignore the return value generated by the arrow.


问:
I want to take the data and close the current layout on the click on the item of recyclerview
I'm stuck by a problem and I don't know how too resolve it.
I want to click on my item in my recycler view, and at this click the layout with the recylcer view will be closed, and my mainActivity will be refresh with the data of the item who i have click on.</p>

答:
After 2 hours in the sauce I have resolve that and I'm very happy.
The problem with the setResult() and the finish() but if you apply this code

```<code>((StructureEnFeuActivity)context).setResult(RESULT_OK, intent);
((StructureEnFeuActivity)context).finish();
</code>```

You will not have the probleme with "static".
So I'm happy.
And thank you for all.

Body:
After 2 hours in the sauce I have resolve that and I'm very happy.
The problem with the setResult() and the finish() but if you apply this code

((StructureEnFeuActivity)context).setResult(RESULT_OK, intent);
((StructureEnFeuActivity)context).finish();

You will not have the probleme with "static".
So I'm happy.
And thank you for all.


问:
Mapped type compiler error when strict is true: Mapped object type implicitly has an 'any' template type
I have a mapped type:

```<code>export type Errors<T> = {
  [P in keyof T]?
}
</code>```

strict is set to true in tsconfig.json and I get this error:

Mapped object type implicitly has an 'any' template type.
```

How can I get rid of this error without setting strict to false or disabling the error?

答:
You are missing the type, so the default is for the mapped type to implicitly be any for all props. But under noImplictAny which is part of strict, TypeScript will not implicitly assume any

The simplest solution is to specify a type. To keep existing behavior you can use any but maybe consider a stricter type if possible.

```<code>export type Errors<T> = {
  [P in keyof T]?: any
}

</code>```

Playground Link

Body:
I have a mapped type:

export type Errors<T> = {
  [P in keyof T]?
}

strict is set to true in tsconfig.json and I get this error:

Mapped object type implicitly has an 'any' template type.

How can I get rid of this error without setting strict to false or disabling the error?

Body:
You are missing the type, so the default is for the mapped type to implicitly be any for all props. But under noImplictAny which is part of strict, TypeScript will not implicitly assume any

The simplest solution is to specify a type. To keep existing behavior you can use any but maybe consider a stricter type if possible.

export type Errors<T> = {
  [P in keyof T]?: any
}

Playground Link


问:
Redux Toolkit - Can a state update invalidate RTK Query Data?
We currently have such values set in a settings slice;

```<code>settingsSlice: {
  projectId: 'a'
}
</code>```

The projectId in the example above is used to compose a dynamic URL that an RTK Query API uses for requests, e.g. https://projectId...

Is it possible to invalidate the API data upon a change to the settings slice?

From the documentation, it seems possible to invalidate other API's using tags, but that doesn't seem to be supported within state slices.

答: No you would have to manually call dispatch(api.invalidateTags(...)).

Body:
We currently have such values set in a settings slice;

settingsSlice: {
  projectId: 'a'
}

The projectId in the example above is used to compose a dynamic URL that an RTK Query API uses for requests, e.g. https://projectId...

Is it possible to invalidate the API data upon a change to the settings slice?

From the documentation, it seems possible to invalidate other API's using tags, but that doesn't seem to be supported within state slices.


问:
Python library for GraphDB
Is there a Python library out there for importing TTL files into GraphDB? I.e. Just point it at a file, rather than loop through millions of statements and inserting them individually?</p>

答:
There is a rather fresh probably unstable library you could use.

It (presumably) includes all the available interfaces for GraphDB.

A turtle import can be executed as:

```<code>from graphdb.rdf4j.api.repositories_api import RepositoriesApi
from graphdb.rdf4j.configuration import Configuration
from graphdb.rdf4j.api_client import ApiClient
from graphdb.mime_types import RDFTypes

conf = Configuration()
conf.host = "http://localhost:7200/"
api_client = ApiClient(configuration=conf)
api_client.set_default_header("Content-Type", RDFTypes.TURTLE)
repository = "tеst"
api = RepositoriesApi(api_client)
api.put_statements(repository, rdf_data="@prefix ex: <http://test/> . \
    ex:1 ex:p ex:2 . ")
</code>```

Title: Python library for GraphDB

Body:
There is a rather fresh probably unstable library you could use.

It (presumably) includes all the available interfaces for GraphDB.

A turtle import can be executed as:

from graphdb.rdf4j.api.repositories_api import RepositoriesApi
from graphdb.rdf4j.configuration import Configuration
from graphdb.rdf4j.api_client import ApiClient
from graphdb.mime_types import RDFTypes

conf = Configuration()
conf.host = "http://localhost:7200/"
api_client = ApiClient(configuration=conf)
api_client.set_default_header("Content-Type", RDFTypes.TURTLE)
repository = "tеst"
api = RepositoriesApi(api_client)
api.put_statements(repository, rdf_data="@prefix ex: <http://test/> . \
    ex:1 ex:p ex:2 . ")


问:
Full Screen DialogFragment in Android
I'm trying to show an almost fullscreen DialogFragment. But I'm somehow not able to do so.

The way I am showing the Fragment is straight from the android developer documentation

```<code>FragmentManager f = ((Activity)getContext()).getFragmentManager();
FragmentTransaction ft = f.beginTransaction();
Fragment prev = f.findFragmentByTag("dialog");
if (prev != null) {
    ft.remove(prev);
}
ft.addToBackStack(null);

// Create and show the dialog.
DialogFragment newFragment = new DetailsDialogFragment();
newFragment.show(ft, "dialog");
</code>```

I know naively tried to set the RelativeLayout in the fragment to fill_parent and some minWidth and minHeight.

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="1000px"
    android:minHeight="600px"
    android:background="#ff0000">
</code>```

I would know expect the DialogFragment to fill the majority of the screen. But I only seems to resize vertically but only until some fixed width horizontally.

I also tried to set the Window Attributes in code, as suggested here: http://groups.google.com/group/android-developers/browse_thread/thread/f0bb813f643604ec. But this didn't help either.

I am probably misunderstanding something about how Android handles Dialogs, as I am brand new to it. How can I do something like this? Are there any alternative ways to reach my goal?

Android Device:

Asus EeePad Transformer

Android 3.0.1

Update:
I now managed to get it into full screen, with the following code in the fragment

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light);
}
</code>```

Unfortunately, this is not quite want I want. I definitely need a small "padding" around the dialog to show the background.

Any ideas how to accomplish that?

答:
This was a productive find to run a full screen dialog box:

```<code>AlertDialog.Builder(activity, R.style.Theme_AppName_PopupOverlay)
</code>```

with the corresponding theme:

```<code><!--night\theme-->
<style name="Theme.AppName.PopupOverlay" parent="ThemeOverlay.AppCompat.Light">
    <!--text-->
    <item name="colorPrimary">@color/white</item>
    <!--title-->
    <item name="android:textColor">@color/white</item>
    <!--window color-->
    <item name="android:backgroundTint">@color/grey_dark</item>
</style>
</code>```

The Alert Dialog Builder also needs the reference to the PopupOverlay for the day theme. So I just have:

```<code><style name="Theme.AppName.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</code>```

Title: Full Screen DialogFragment in Android

Body:
I'm trying to show an almost fullscreen DialogFragment. But I'm somehow not able to do so.

The way I am showing the Fragment is straight from the android developer documentation

FragmentManager f = ((Activity)getContext()).getFragmentManager();
FragmentTransaction ft = f.beginTransaction();
Fragment prev = f.findFragmentByTag("dialog");
if (prev != null) {
    ft.remove(prev);
}
ft.addToBackStack(null);

// Create and show the dialog.
DialogFragment newFragment = new DetailsDialogFragment();
newFragment.show(ft, "dialog");

I know naively tried to set the RelativeLayout in the fragment to fill_parent and some minWidth and minHeight.

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="1000px"
    android:minHeight="600px"
    android:background="#ff0000">

I would know expect the DialogFragment to fill the majority of the screen. But I only seems to resize vertically but only until some fixed width horizontally.

I also tried to set the Window Attributes in code, as suggested here: http://groups.google.com/group/android-developers/browse_thread/thread/f0bb813f643604ec. But this didn't help either.

I am probably misunderstanding something about how Android handles Dialogs, as I am brand new to it. How can I do something like this? Are there any alternative ways to reach my goal?

Android Device:

Asus EeePad Transformer

Android 3.0.1

Update:
I now managed to get it into full screen, with the following code in the fragment

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light);
}

Unfortunately, this is not quite want I want. I definitely need a small "padding" around the dialog to show the background.

Any ideas how to accomplish that?

Body:
This was a productive find to run a full screen dialog box:

AlertDialog.Builder(activity, R.style.Theme_AppName_PopupOverlay)

with the corresponding theme:

<!--night\theme-->
<style name="Theme.AppName.PopupOverlay" parent="ThemeOverlay.AppCompat.Light">
    <!--text-->
    <item name="colorPrimary">@color/white</item>
    <!--title-->
    <item name="android:textColor">@color/white</item>
    <!--window color-->
    <item name="android:backgroundTint">@color/grey_dark</item>
</style>

The Alert Dialog Builder also needs the reference to the PopupOverlay for the day theme. So I just have:

<style name="Theme.AppName.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />


问:
Warnings on update state of <select> based on state of previous <select> state
I have two dropdowns, the values of the second dropdown should be updated based on the state of the first dropdown.
Although the code seems to work, I get warnings for out-of-range value. How can I improve this code so that the warnings disappear?

MWE on Codesandbox

The full component in case that's preferred.

const MyForm = () => {
  const [state1, setState1] = useState(list1[0]);
  const [state2, setState2] = useState(list2[0]);

  return (
    <>
      <FormControl fullWidth sx={{ marginY: "16px" }}>
        <InputLabel>List 1</InputLabel>
        <Select
          label="List 1"
          value={state1.code}
          onChange={(e) => {
            const tmpState1 = list1.find(
              (item) => item.code === e.target.value
            );
            setState1(tmpState1);
          }}
        >
          {list1.map((item) => {
            return (
              <MenuItem value={item.code} key={item.name}>
                {item.name}
              </MenuItem>
            );
          })}
          <MenuItem value={""}>All</MenuItem>
        </Select>
      </FormControl>
      <FormControl fullWidth sx={{ marginY: "16px" }}>
        <InputLabel>List 2</InputLabel>
        <Select
          label="List 2"
          value={state2.name}
          onChange={(e) => {
            const tmpState2 = list2.find(
              (item) => item.name === e.target.value
            );
            console.log(tmpState2);
            setState2(tmpState2);
          }}
        >
          {list2
            .filter((item) => item.code === state1.code)
            .map((item) => {
              return (
                <MenuItem value={item.name} key={item.name}>
                  {item.name}
                </MenuItem>
              );
            })}
        </Select>
      </FormControl>
    </>
  );
};

export default MyForm;
```

答:
The problem was that when the variable state1 get's updated, the value of the second dropdown isn't among the list of updated <MenuItem>s. Thus it throws a warning.

A simple fix is to update the value in the second dropdown when the state1 changes:

//...
<FormControl fullWidth sx={{ marginY: "16px" }}>
  <InputLabel>List 1</InputLabel>
    <Select
      label="List 1"
      value={state1.code}
      onChange={(e) => {
        const tmpState1 = list1.find(
          (item) => item.code === e.target.value);
        {/* this is the fix */}
        setState2(list2.find((item) => item.code === tmpState1.code));
        setState1(tmpState1);
      }}
    >
      {list1.map((item) => {
        return (
          <MenuItem value={item.code} key={item.name}>
            {item.name}
          </MenuItem>
        );
      })}
    <MenuItem value={""}>All</MenuItem>
  </Select>
</FormControl>
//...
```


问:
How do I make case-insensitive queries on Mongodb?
```<code>var thename = 'Andrew';
db.collection.find({'name':thename});
</code>```

How do I query case insensitive? I want to find result even if "andrew";

答:
Chris Fulstow's solution will work (+1), however, it may not be efficient, especially if your collection is very large. Non-rooted regular expressions (those not beginning with ^, which anchors the regular expression to the start of the string), and those using the i flag for case insensitivity will not use indexes, even if they exist.

An alternative option you might consider is to denormalize your data to store a lower-case version of the name field, for instance as name_lower. You can then query that efficiently (especially if it is indexed) for case-insensitive exact matches like:

```<code>db.collection.find({"name_lower": thename.toLowerCase()})
</code>```

Or with a prefix match (a rooted regular expression) as:

```<code>db.collection.find( {"name_lower":
    { $regex: new RegExp("^" + thename.toLowerCase(), "i") } }
);
</code>```

Both of these queries will use an index on name_lower.

Body:
var thename = 'Andrew';
db.collection.find({'name':thename});

How do I query case insensitive? I want to find result even if "andrew";

Body:
Chris Fulstow's solution will work (+1), however, it may not be efficient, especially if your collection is very large. Non-rooted regular expressions (those not beginning with ^, which anchors the regular expression to the start of the string), and those using the i flag for case insensitivity will not use indexes, even if they exist.

An alternative option you might consider is to denormalize your data to store a lower-case version of the name field, for instance as name_lower. You can then query that efficiently (especially if it is indexed) for case-insensitive exact matches like:

db.collection.find({"name_lower": thename.toLowerCase()})

Or with a prefix match (a rooted regular expression) as:

db.collection.find( {"name_lower":
    { $regex: new RegExp("^" + thename.toLowerCase(), "i") } }
);

Both of these queries will use an index on name_lower.


问:
Add line break for string assignment (For html rendering)
I am trying to create a new line like so:

```<code>let myString= "";
for (const [key, value] of Object.entries(response)) {
   myString += response + "\n";
}
</code>```

But the HTML outputs space instead of line break

答:
you can use
 tag in HTML for line break.

Body:
I am trying to create a new line like so:

let myString= "";
for (const [key, value] of Object.entries(response)) {
   myString += response + "\n";
}

But the HTML outputs space instead of line break

Body: you can use <br> tag in HTML for line break.