问:
What does =< mean in a batch file after SET /P and variable name?
So my friend gave me a batch file he wanted me to check if everything is correct, but I've got no clue what =< does in this.

```<code>:artthou_54
mode 50,20
cls
set videopath=0
title Art thou sure?
set /p videopath=<\DataTron\Ainstro\YePathToVido.dat
if %videopath%=="" echo Video Path = %videopath%
if %videopath%=="C:\Vodie" echo It seems you have the same path as the creator
set /p videopath="Would you like to open %VideoPath%? (Y/N): "
mode 50,20
if %videopath%==Y goto videohole-b
if %videopath%==N goto videohole
if %videopath%==y goto videohole-b
if %videopath%==n goto videohole
if %videopath%==back goto videohole-c
if %videopath%==exit exit
goto Art-thou-unsure
</code>```

答:
That line sets the first line of YePathToVido.dat to the variable videopath.

Normally, set /p gets input from the user and reads in until it receives a CRLF.

However, < redirects input from the specified file and sends it to the set /p command. Since set /p reads until it receives a CRLF, this effectively tells the command to read from the start of the file until the end of the first line.

On a side note, those first two if statements are incorrect because batch compares everything on both sides of the ==, including the quotes. Those lines need to change to if "%videopath%"=="" and if "%videopath%"=="C:\Vodie", respectively.

Body:
So my friend gave me a batch file he wanted me to check if everything is correct, but I've got no clue what =< does in this.

:artthou_54
mode 50,20
cls
set videopath=0
title Art thou sure?
set /p videopath=<\DataTron\Ainstro\YePathToVido.dat
if %videopath%=="" echo Video Path = %videopath%
if %videopath%=="C:\Vodie" echo It seems you have the same path as the creator
set /p videopath="Would you like to open %VideoPath%? (Y/N): "
mode 50,20
if %videopath%==Y goto videohole-b
if %videopath%==N goto videohole
if %videopath%==y goto videohole-b
if %videopath%==n goto videohole
if %videopath%==back goto videohole-c
if %videopath%==exit exit
goto Art-thou-unsure


来源: stackexchange

问:
Python method lookup, static vs. instance
Until like one hour ago, I was convinced that in python Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) which passes the instance as first parameter. In this example the last two lines do (apparently) the same thing:

```<code>class Foo (object):
    def bar (self): print "baz"

qux = Foo ()
qux.bar ()
Foo.bar (qux)
</code>```

But now I have a class Animal that has a static method populate() that returns a list of all animals known to man. Also each instance of Animal has a method populate() that fills the properties of the instance with random values.

```<code>#! /usr/bin/env python
# -*- coding: utf-8 -*-

import random

animals = [ ("Bella", "cow"), ("Spike", "dog"), ("José", "iguana"), ("Tux", "penguin") ]

class Animal (object):
    @staticmethod
    def populate (*args): return map (lambda x: Animal (*x), animals)

    def __init__ (self, name = None, species = None):
        def bar (): self.name, self.species = random.choice (animals)
        self.name = name
        self.species = species
        self.populate = bar

    def __repr__ (self): return "%s of species %s" % (self.name, self.species)

print Animal.populate ()
print Animal ("Pinky", "mouse")
qux = Animal ()
qux.populate ()
print qux
</code>```

The code works fine, but what made me suspicious was the fact that print Animal.populate (qux) called the static populate method (and hence returned a list and did not populate poor qux). So apparently my conviction that Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) is wrong.

This raises various questions for me:

What happens when I call Foo ().bar ()?

What happens when I call Foo.bar (Foo () )?

Is there an internal difference between the both?

Am I missing some fundamental concept of python?

If you had to write a class whose static populate method does something else than the populate method invoked over an instance of this class, which would be the way to go?

(Yes it must be the same name.)

答:
qnx.populate() first looks on the instance qnx for populate. If that is not there the __mro__ is followed until something called populate is found.

Animals.populate(qnx) is skipping the first step in the above lookup

ContentLicense: CC BY-SA 3.0

Body:
Until like one hour ago, I was convinced that in python Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) which passes the instance as first parameter. In this example the last two lines do (apparently) the same thing:

class Foo (object):
    def bar (self): print "baz"

qux = Foo ()
qux.bar ()
Foo.bar (qux)

But now I have a class Animal that has a static method populate() that returns a list of all animals known to man. Also each instance of Animal has a method populate() that fills the properties of the instance with random values.

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import random

animals = [ ("Bella", "cow"), ("Spike", "dog"), ("José", "iguana"), ("Tux", "penguin") ]

class Animal (object):
    @staticmethod
    def populate (*args): return map (lambda x: Animal (*x), animals)

    def __init__ (self, name = None, species = None):
        def bar (): self.name, self.species = random.choice (animals)
        self.name = name
        self.species = species
        self.populate = bar

    def __repr__ (self): return "%s of species %s" % (self.name, self.species)

print Animal.populate ()
print Animal ("Pinky", "mouse")
qux = Animal ()
qux.populate ()
print qux

The code works fine, but what made me suspicious was the fact that print Animal.populate (qux) called the static populate method (and hence returned a list and did not populate poor qux). So apparently my conviction that Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) is wrong.

This raises various questions for me:

What happens when I call Foo ().bar ()?

What happens when I call Foo.bar (Foo () )?

Is there an internal difference between the both?

Am I missing some fundamental concept of python?

If you had to write a class whose static populate method does something else than the populate method invoked over an instance of this class, which would be the way to go?

(Yes it must be the same name.)


问:
Closure and variable scope in python 3.x issue causing me confusion
I am using Python 3.7.0 and I am doing some experiments in order to comprehend the subtleties of variable scopes but I still don't understand this behaviour.

When I execute this code:

```<code>def f():
    x=0
    def g():y=x+1;x=y
    return g
f()()
</code>```

I get UnboundLocalError: local variable 'x' referenced before assignment

However when I execute this one:

```<code>def f():
   x=0
   def g():y=x+1
   return g
f()()
</code>```

It works fine. And even this one:

```<code>def f():
   x=0
   def g():x=1
   return g
f()()
</code>```

It also works fine. So I am confused. It seems to me that if assigning the value 1 to the nonlocal variable x in the g function works fine alone and on the other hand if assigning an expression containing x to a local variable y in the function g works also fine then the instructions y=x+1 and x=y should both work. I don't understand what is causing the error. I feel I am missing something fundamental in my understanding of Python's behaviour.

答:
I'll take an ill-advised crack at this.  In the following code:

```<code>def f():
    x = 0  # assignment makes this x local to f()

    def g():
        y = x + 1
        x = y  # assignment makes this x local to g()

    return g

f()()
</code>```

The assignment of x inside g() forces it to be a variable local to g().  So the first line causes the error as you accessing the value of an unassigned local.  I believe this "assignment makes it local" logic doesn't follow the flow of your program -- the function is viewed as whole to make this determination and then the code is looked at line by line.

You can access any variable in scope from a function, but you can only set locals.  Unless you've declared the variable you're assigning as global or nonlocal:

```<code>def f():
    x = 0  # assignment makes this x local to f()

    def g():
        nonlocal x

        y = x + 1
        x = y  # x is declared to come from a nonlocal scope

    return g

f()()
</code>```

In your second example, it's not an issue as you're only looking at the value of x, not setting it, so it can come from any appropriate scope:

```<code>def f():
    x = 0  # assignment makes this x local to f()

    def g():
        y = x + 1  # x comes from an outer scope

    return g

f()()
</code>```

Finally, your third example is the same as the first without the unssigned local variable usage error:

```<code>def f():
    x = 0  # assignment makes this x local to f()

    def g():
        x = 1  # assignment makes this x local to g()

    return g

f()()
</code>```

It seems to me that if assigning the value 1 to the nonlocal variable
  x in the g function works fine alone

How did you determine that the reassignment of x in f() worked fine?

ContentLicense: CC BY-SA 4.0

Body:
I am using Python 3.7.0 and I am doing some experiments in order to comprehend the subtleties of variable scopes but I still don't understand this behaviour.

When I execute this code:

def f():
    x=0
    def g():y=x+1;x=y
    return g
f()()

I get UnboundLocalError: local variable 'x' referenced before assignment

However when I execute this one:

def f():
   x=0
   def g():y=x+1
   return g
f()()

It works fine. And even this one:

def f():
   x=0
   def g():x=1
   return g
f()()

It also works fine. So I am confused. It seems to me that if assigning the value 1 to the nonlocal variable x in the g function works fine alone and on the other hand if assigning an expression containing x to a local variable y in the function g works also fine then the instructions y=x+1 and x=y should both work. I don't understand what is causing the error. I feel I am missing something fundamental in my understanding of Python's behaviour.

Body:
I'll take an ill-advised crack at this.  In the following code:

def f():
    x = 0  # assignment makes this x local to f()

    def g():
        y = x + 1
        x = y  # assignment makes this x local to g()

    return g

f()()

The assignment of x inside g() forces it to be a variable local to g().  So the first line causes the error as you accessing the value of an unassigned local.  I believe this "assignment makes it local" logic doesn't follow the flow of your program -- the function is viewed as whole to make this determination and then the code is looked at line by line.

You can access any variable in scope from a function, but you can only set locals.  Unless you've declared the variable you're assigning as global or nonlocal:

def f():
    x = 0  # assignment makes this x local to f()

    def g():
        nonlocal x

        y = x + 1
        x = y  # x is declared to come from a nonlocal scope

    return g

f()()

In your second example, it's not an issue as you're only looking at the value of x, not setting it, so it can come from any appropriate scope:

def f():
    x = 0  # assignment makes this x local to f()

    def g():
        y = x + 1  # x comes from an outer scope

    return g

f()()

Finally, your third example is the same as the first without the unssigned local variable usage error:

def f():
    x = 0  # assignment makes this x local to f()

    def g():
        x = 1  # assignment makes this x local to g()

    return g

f()()

It seems to me that if assigning the value 1 to the nonlocal variable
  x in the g function works fine alone

How did you determine that the reassignment of x in f() worked fine?


问:
Select rows with excat two same entries in a column
i have a pandas dataframe. And I want to select all the rows, where in one column I have two times the same value. So the dataframe looks like this:

```<code>group  value
A       1
A       2
B       3
B       1
B       4
C       1
C       1
D       4
D       5
D       3
D       2
</code>```

And I want to filter it that this is the outcome:

```<code>group  value
A       1
A       2
C       1
C       1
</code>```

How can I achieve that?

答:
Use Series.value_counts with Series.map for counts values, compare by Series.eq and filter by boolean indexing:

```<code>df1 = df[df['group'].map(df['group'].value_counts()).eq(2)]
</code>```

Or use GroupBy.transform:

```<code>df1 = df[df.groupby('group')['group'].transform('size').eq(2)]
</code>```

```<code>print (df1)
  group  value
0     A      1
1     A      2
5     C      1
6     C      1
</code>```

Most clean, but unfortunately most slow is use DataFrameGroupBy.filter:

```<code>df = df.groupby('group').filter(lambda x: len(x) == 2)
</code>```

Body:
i have a pandas dataframe. And I want to select all the rows, where in one column I have two times the same value. So the dataframe looks like this:

group  value
A       1
A       2
B       3
B       1
B       4
C       1
C       1
D       4
D       5
D       3
D       2

And I want to filter it that this is the outcome:

group  value
A       1
A       2
C       1
C       1

How can I achieve that?

Body:
Use Series.value_counts with Series.map for counts values, compare by Series.eq and filter by boolean indexing:

df1 = df[df['group'].map(df['group'].value_counts()).eq(2)]

Or use GroupBy.transform:

df1 = df[df.groupby('group')['group'].transform('size').eq(2)]

print (df1)
  group  value
0     A      1
1     A      2
5     C      1
6     C      1

Most clean, but unfortunately most slow is use DataFrameGroupBy.filter:

df = df.groupby('group').filter(lambda x: len(x) == 2)


问:
How can I suppress warnings (codebase-wide) during javadoc compilation?
I'm stuck with a legacy Java codebase that has THOUSANDS of warnings when you compile it. I would love to actually fix the source of all these warnings, but unfortunately that's not an option at this time at my company (other things like "making new products that generate revenue" are considered higher priority by the people in charge; fancy that).

Now, I could just live with all of these warnings, if it wasn't for the fact that they make it difficult to find actual errors in the output from our continuous build server.  The build server just uses an ant  call, nothing fancy, but so far I haven't been able to find anything anywhere for how I can modify this call to prevent warning output.

Going through the code and adding a @SuppressWarnings annotation everywhere would work, but it would also be almost as much of a pain as going through and fixing all the warnings' sources.  So what I'd really love is if there was just some way I could do:

```<code><javadoc suppressWarrnings="true"
</code>```

or something similar, to make the javadoc compiler not output all the warning messages.  Is anything like this (global javadoc warning disabling) possible?

答: Try the -quiet flag.</p>

OwnerDisplayName: machineghost

ContentLicense: CC BY-SA 2.5

Body:
I'm stuck with a legacy Java codebase that has THOUSANDS of warnings when you compile it. I would love to actually fix the source of all these warnings, but unfortunately that's not an option at this time at my company (other things like "making new products that generate revenue" are considered higher priority by the people in charge; fancy that).

Now, I could just live with all of these warnings, if it wasn't for the fact that they make it difficult to find actual errors in the output from our continuous build server.  The build server just uses an ant  call, nothing fancy, but so far I haven't been able to find anything anywhere for how I can modify this call to prevent warning output.

Going through the code and adding a @SuppressWarnings annotation everywhere would work, but it would also be almost as much of a pain as going through and fixing all the warnings' sources.  So what I'd really love is if there was just some way I could do:

<javadoc suppressWarrnings="true"

or something similar, to make the javadoc compiler not output all the warning messages.  Is anything like this (global javadoc warning disabling) possible?

Body: Try the -quiet flag.


问:
express-validator not initializing properly in express 4
When starting express-validator 6.3 with Express 4 and Node.js 11 like this:

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

const { check, validationResult } = require('express-validator');

var app = express()

app.use(express.json())

app.post('/whatever', [
      check('somevariable').escape() // <---keeps saying that check is not defined!? same error if I change "check" to "sanitize"
    ], (req, res) => {
      console.log(req.body.somevariable);
})
</code>```

I keep getting a ReferenceError: check is not defined. What am I doing wrong!?

答:
For "express-validator": "^6.5.0", It should be:

const express = require('express');
const { check } = require('express-validator');
const app = express();
const port = 3000;
app.use(express.json());
app.post('/whatever', [check('somevariable').escape()], (req, res) => {
  console.log(req.body.somevariable);
});

app.listen(3000, () => console.log(`server listen port ${port}`));
```

<p>NOT:</p>

```const check = require('express-validator');
```

See Getting Started for express-validator module

Body:
When starting express-validator 6.3 with Express 4 and Node.js 11 like this:

var express = require('express');

const { check, validationResult } = require('express-validator');

var app = express()

app.use(express.json())

app.post('/whatever', [
      check('somevariable').escape() // <---keeps saying that check is not defined!? same error if I change "check" to "sanitize"
    ], (req, res) => {
      console.log(req.body.somevariable);
})

I keep getting a ReferenceError: check is not defined. What am I doing wrong!?

Body:
For "express-validator": "^6.5.0", It should be:

const express = require('express');
const { check } = require('express-validator');
const app = express();
const port = 3000;
app.use(express.json());
app.post('/whatever', [check('somevariable').escape()], (req, res) => {
  console.log(req.body.somevariable);
});

app.listen(3000, () => console.log(`server listen port ${port}`));

NOT:

const check = require('express-validator');

See Getting Started for express-validator module


问:
How do we can make a image to take the whole space available in the floating action button in flutter
I am trying to add a image in floating action button which I have done easily but the problem I am facing is that I don't know how to make this image to take the whole space available in the floating action button ... I tried my best researched in the internet but did not not fount anything ...any help is appreciated thanks in advance </p>

```<code>floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: Container(
height: MediaQuery.of(context).size.width * 0.24,
width: MediaQuery.of(context).size.width * 0.24,
child: FloatingActionButton(
//backgroundColor:Colors.lightGreen,
child: Image.asset("assets/home_unselected.png"),
onPressed: () {}),
),
</code>```

答:
You can make use of CircleAvatar widget and pass the desired image as backgroundImage alongwith giving a custom radius to it, as below:

```<code>child: FloatingActionButton(
            child: CircleAvatar(
              radius: 50,
              backgroundImage: AssetImage("assets/placeholder.png",
              ),
            ),
            onPressed: () {}),
</code>```

Hope this answers your question.

Body:
I am trying to add a image in floating action button which I have done easily but the problem I am facing is that I don't know how to make this image to take the whole space available in the floating action button ... I tried my best researched in the internet but did not not fount anything ...any help is appreciated thanks in advance

floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: Container(
height: MediaQuery.of(context).size.width * 0.24,
width: MediaQuery.of(context).size.width * 0.24,
child: FloatingActionButton(
//backgroundColor:Colors.lightGreen,
child: Image.asset("assets/home_unselected.png"),
onPressed: () {}),
),

Body:
You can make use of CircleAvatar widget and pass the desired image as backgroundImage alongwith giving a custom radius to it, as below:

child: FloatingActionButton(
            child: CircleAvatar(
              radius: 50,
              backgroundImage: AssetImage("assets/placeholder.png",
              ),
            ),
            onPressed: () {}),

Hope this answers your question.


问:
primary key value EF Core
I need to get a primary key value before it will be assigned to the model by EF Core.

My Model:

```<code>**namespace Tree.Models
{
  public class MeterLocationTree
  {
    [Key]
    public int Id { get; set; }
    [Required]
    public string LocationElement { get; set; }
    [Required]
    public int[] Path { get; set; }
  }
}**
</code>```

My migration snapshot for the model:

```<code>modelBuilder.Entity("Tree.Models.MeterLocationTree", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("integer")
                        .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);

                    b.Property<string>("LocationElement")
                        .IsRequired()
                        .HasColumnType("text");

                    b.Property<int[]>("Path")
                        .IsRequired()
                        .HasColumnType("integer[]");

                    b.HasKey("Id");

                    b.ToTable("MeterLocationTree");
                });
</code>```

Is it possible to get the current primary key value before it will be assigned to the model during Add operation?
So maybe we can have access to the ef mechanism of primary key values generating?

答: Model contains data and we cannot access the value before it is assigned to model in EF core.</p>

Title: primary key value EF Core

Body:
I need to get a primary key value before it will be assigned to the model by EF Core.

My Model:

**namespace Tree.Models
{
  public class MeterLocationTree
  {
    [Key]
    public int Id { get; set; }
    [Required]
    public string LocationElement { get; set; }
    [Required]
    public int[] Path { get; set; }
  }
}**

My migration snapshot for the model:

modelBuilder.Entity("Tree.Models.MeterLocationTree", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("integer")
                        .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);

                    b.Property<string>("LocationElement")
                        .IsRequired()
                        .HasColumnType("text");

                    b.Property<int[]>("Path")
                        .IsRequired()
                        .HasColumnType("integer[]");

                    b.HasKey("Id");

                    b.ToTable("MeterLocationTree");
                });

Is it possible to get the current primary key value before it will be assigned to the model during Add operation?
So maybe we can have access to the ef mechanism of primary key values generating?


问:
Javascript getCurrentPosition() function giving me incorrect latitude and longitude values on localhost
```<code>Here is my code...

<!DOCTYPE html>
<html>
    <head>
        <title>Geeting User Location</title>
    </head>
    <body>
        <button onclick="getLocation()">Click here to get your address</button><br><br>
        <label>Address: </label>
        <textarea cols="100" rows="5" id="demo"></textarea>
    </body>
</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
    var x = document.getElementById("demo");

    function getLocation()
    {
        if (navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(function(position){showPosition(position)}, null, {
                maximumAge: 75000,
                timeout: 30000,
                enableHighAccuracy: true,
            });
        }
        else
        {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

    function showPosition(position)
    {
        var locApi = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude+","+position.coords.longitude+"&key=MY_API_KEY_HERE";

        $.ajax({
          url: locApi,
          dataType: 'json',
          type: 'GET',
          success: function(data) {
            console.log(data);
            var address = data.city;
            address += data.region;
            address += data.country;
            $("#demo").append(JSON.stringify(address));
          },
          error: function() {
             $('#demo').html('<p>An error has occurred</p>');
          },
       });
    }
</script>
</code>```

<p>I want to get the city, region, country name through latitude & longitude values and append it to the textarea when user click on the button. I want to know where I am wrong. Does Geolocation not gives correct latitude & longitude values on localhost. </p>

答:
See https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition and https://www.sitepoint.com/html5-geolocation/

If you are using a device that does not have high-accuracy GPS, it is likely basing location of broad assumptions such as your IP address or where your ISP (Internet Service Provider) is located.

You should also get an Accuracy measurement with the location so you can have an estimation of how accurate the information you've gotten is.

Body:
Here is my code...

<!DOCTYPE html>

        <title>Geeting User Location</title>

        <button onclick="getLocation()">Click here to get your address</button>

        Address:
        <textarea cols="100" rows="5" id="demo"></textarea>

I want to get the city, region, country name through latitude & longitude values and append it to the textarea when user click on the button. I want to know where I am wrong. Does Geolocation not gives correct latitude & longitude values on localhost.


问:
How do I edit multiple elements in a list on a conditional basis?
An assignment I'm working on for school has tasked me with writing a script in Python that will edit a list of file names. All the files that end with the "hpp" extension must be renamed to "h".

```<code>filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
</code>```

Can this be solved using a list comparision? This is what I have so far...

```<code>def newfilenames(filenames):
  elements = [ "h".format(filenames) for filenames]
</code>```

答:
You could try this.

```<code>aa = [ff.replace('hpp', 'h') for ff in filenames]
</code>```

Hope it helps.

Body:
An assignment I'm working on for school has tasked me with writing a script in Python that will edit a list of file names. All the files that end with the "hpp" extension must be renamed to "h".

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]

Can this be solved using a list comparision? This is what I have so far...

def newfilenames(filenames):
  elements = [ "h".format(filenames) for filenames]

Body:
You could try this.

aa = [ff.replace('hpp', 'h') for ff in filenames]

Hope it helps.


问:
Thread synchronization and define atomic block using Pthread
I had some problems while programming C using Pthread.

There are two threads(Reader, Main) and shared resource, fd.
fd can be accessed in blocking manner by using read_blocking() and write_blocking()

What I intended is to write data in the Main thread whenever needed; with free-running Reader thread. I used Pthread components(Semaphore, Mutex lock, etc.) for implementing this; but encountered synchronization problem, deadlock.

The following is simplified code for this situation.

Reader Thread (free-running):

```<code>// Read data from `fd`
// (Separated thread other than main thread)
void ReaderThread() {
    while ( 1 ) {

        // [A]

        wait_write_complete(g_lock);

        // [!] "main thread" should NOT cut into here

        read_blocking(fd);  // [B]

    }
}
</code>```

Writer Function (called from main thread):

```<code>// Write data to `fd`
// Called from "main thread"
void WriteData() {
    lock(g_lock);

    // At this point, the ReaderThread() shoule be @ [A] or [B]

    cancel_read();  // force terminate read_blocking()
    write_blocking(fd);

    unlock(g_lock);
}
</code>```

[Key Point]

read_blocking() and write_blocking() should NOT be called while the other is blocking

read_blocking() can be force terminated by calling cancel_read()

[Requirements]

No busy wait

No sleep()

WriteData() has higher priority than ReaderThread()
(read_blocking() should be cancelled whenever WriteData() is called)

How to prevent WriteData() from interrupt between wait_write_complete(g_lock) and read_blocking(fd)(position marked [!]) ?

wait_write_complete(g_lock) and read_blocking(fd) should be atomic block

What type of locking mechanism is appropriate for g_lock?
(Semaphore, Mutex lock, Barrier, Conditional wait, or any other?)

Example code will be very very helpful!! :)

答:
I'm inclined to agree with @EOF that the communication pattern you describe seems excessively complex.  Taking the question as it stands, however, a MUTual EXclusion lock is the natural synchronization mechanism for excluding one thread from taking action between two or more actions performed by a different thread.  That probably means that to achieve your aim, wait_write_complete() must lock g_lock before it returns, and read_blocking() must unlock it soon after function entry.

Note that you'll need to take great care to avoid simply moving the race condition into read_blocking().  How you might avoid that depends on the mechanism you intend to use interrupt that function's execution.

Moreover, I suspect you'll want a shared flag indicating whether a write is pending / whether the reader may read (all access to which is protected by the same mutex), and a condition variable for suspending execution of the reader until the writer is done.  Using those, wait_write_complete() might then look something like this:

```<code>int wait_write_complete(pthread_mutex_t *g_lock) {
    int result = pthread_mutex_lock(g_lock);

    while (!result && !may_read) {
        result = pthread_cond_wait(&read_write_cv, &g_lock);
    }

    // Note: if this function returns a failure code then the state of the mutex is unknown
    return result;
}
</code>```

The writer thread is responsible for manipulating may_read appropriately, under protection of the mutex, and for signaling the condition variable when (re-)enabling reading.

Body:
I had some problems while programming C using Pthread.

There are two threads(Reader, Main) and shared resource, fd.
fd can be accessed in blocking manner by using read_blocking() and write_blocking()

What I intended is to write data in the Main thread whenever needed; with free-running Reader thread. I used Pthread components(Semaphore, Mutex lock, etc.) for implementing this; but encountered synchronization problem, deadlock.

The following is simplified code for this situation.

Reader Thread (free-running):

// Read data from `fd`
// (Separated thread other than main thread)
void ReaderThread() {
    while ( 1 ) {

        // [A]

        wait_write_complete(g_lock);

        // [!] "main thread" should NOT cut into here

        read_blocking(fd);  // [B]

    }
}

Writer Function (called from main thread):

// Write data to `fd`
// Called from "main thread"
void WriteData() {
    lock(g_lock);

    // At this point, the ReaderThread() shoule be @ [A] or [B]

    cancel_read();  // force terminate read_blocking()
    write_blocking(fd);

    unlock(g_lock);
}

[Key Point]

read_blocking() and write_blocking() should NOT be called while the other is blocking

read_blocking() can be force terminated by calling cancel_read()

[Requirements]

No busy wait

No sleep()

WriteData() has higher priority than ReaderThread()
(read_blocking() should be cancelled whenever WriteData() is called)

How to prevent WriteData() from interrupt between wait_write_complete(g_lock) and read_blocking(fd)(position marked [!]) ?

wait_write_complete(g_lock) and read_blocking(fd) should be atomic block

What type of locking mechanism is appropriate for g_lock?
(Semaphore, Mutex lock, Barrier, Conditional wait, or any other?)

Example code will be very very helpful!! :)

Body:
I'm inclined to agree with @EOF that the communication pattern you describe seems excessively complex.  Taking the question as it stands, however, a MUTual EXclusion lock is the natural synchronization mechanism for excluding one thread from taking action between two or more actions performed by a different thread.  That probably means that to achieve your aim, wait_write_complete() must lock g_lock before it returns, and read_blocking() must unlock it soon after function entry.

Note that you'll need to take great care to avoid simply moving the race condition into read_blocking().  How you might avoid that depends on the mechanism you intend to use interrupt that function's execution.

Moreover, I suspect you'll want a shared flag indicating whether a write is pending / whether the reader may read (all access to which is protected by the same mutex), and a condition variable for suspending execution of the reader until the writer is done.  Using those, wait_write_complete() might then look something like this:

int wait_write_complete(pthread_mutex_t *g_lock) {
    int result = pthread_mutex_lock(g_lock);

    while (!result && !may_read) {
        result = pthread_cond_wait(&read_write_cv, &g_lock);
    }

    // Note: if this function returns a failure code then the state of the mutex is unknown
    return result;
}

The writer thread is responsible for manipulating may_read appropriately, under protection of the mutex, and for signaling the condition variable when (re-)enabling reading.


问:
re-rendering a component every milliseconds
I made a Countdown component.

It works well as Normal Countdown but I wanna see it works with milliseconds.

But I have no idea how it re-render every millisecond and display milliseconds.

this code is what I made and it re-render every second.

edited

I am considering re-rendering every 100ms or 10ms.
and I want to display this.

furthermore, I want to know If it re-rendered every 100ms, whether it is okay or not

const {useState, useEffect} = React;
function Countdown(props){
  const [timer, setTimer] = useState(0);
  const {d,h,m,s} = secToDay(timer);
  useEffect(()=>{
    setTimer(props.value)
  },[]);
  useInterval(()=>{
    setTimer(timer - 1);
    if( (timer-1) === 0){
      // Timeover
    }
  }, timer > 0 ? 1000 : null);
  return (

      {d}:
      {h}:
      {m}:
      {s}

  )
}

const App = () => (<Countdown value={300} />);
ReactDOM.render(<App />, document.getElementById('root'));

function secToDay(seconds:number){
  let d = (~~(seconds/(3600*24))).toString().padStart(2,'0');
  let h = (~~(seconds % (3600*24) /3600)).toString().padStart(2,'0');
  let m = (~~((seconds % (3600*24) % 3600) / 60)).toString().padStart(2,'0');
  let s = (~~(seconds % 60)).toString().padStart(2,'0');
  return {d,h,m,s};
}
function useInterval(callback: any, delay: any) {
  const savedCallback: any = React.useRef();

  React.useEffect(() => {
    savedCallback.current = callback;
  });

  React.useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" /></code>```

答:
Add ms by s*1000 in secToDay function and change delay to 1 instead of 1000. Run the snippet to see the result.

const {useState, useEffect} = React;
function Countdown(props){
  const [timer, setTimer] = useState(0);
  // add ms
  const {d,h,m,s, ms} = secToDay(timer);
  useEffect(()=>{
    setTimer(props.value)
  },[]);
  useInterval(()=>{
    setTimer(timer - 1);
    if( (timer-1) === 0){
      // Timeover
    }
  }, timer > 0 ? 1 : null); // set delay 1
  return (

      {d}:
      {h}:
      {m}:
      {s}:
      {ms}

  )
}

const App = () => (<Countdown value={300} />);
ReactDOM.render(<App />, document.getElementById('root'));

function secToDay(seconds:number){
  let d = (~~(seconds/(3600*24))).toString().padStart(2,'0');
  let h = (~~(seconds % (3600*24) /3600)).toString().padStart(2,'0');
  let m = (~~((seconds % (3600*24) % 3600) / 60)).toString().padStart(2,'0');
  let s = (~~(seconds % 60)).toString().padStart(2,'0');
 // add ms
  let ms = s*1000
  return {d,h,m,s,ms};
}
function useInterval(callback: any, delay: any) {
  const savedCallback: any = React.useRef();

  React.useEffect(() => {
    savedCallback.current = callback;
  });

  React.useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" /></code>```

Body:
Add ms by s*1000 in secToDay function and change delay to 1 instead of 1000. Run the snippet to see the result.

const {useState, useEffect} = React;
function Countdown(props){
  const [timer, setTimer] = useState(0);
  // add ms
  const {d,h,m,s, ms} = secToDay(timer);
  useEffect(()=>{
    setTimer(props.value)
  },[]);
  useInterval(()=>{
    setTimer(timer - 1);
    if( (timer-1) === 0){
      // Timeover
    }
  }, timer > 0 ? 1 : null); // set delay 1
  return (
    <div>
      <span>{d}</span>:
      <span>{h}</span>:
      <span>{m}</span>:
      <span>{s}</span>:
      <span>{ms}</span>
    </div>
  )
}

const App = () => (<Countdown value={300} />);
ReactDOM.render(<App />, document.getElementById('root'));

function secToDay(seconds:number){
  let d = (~~(seconds/(3600*24))).toString().padStart(2,'0');
  let h = (~~(seconds % (3600*24) /3600)).toString().padStart(2,'0');
  let m = (~~((seconds % (3600*24) % 3600) / 60)).toString().padStart(2,'0');
  let s = (~~(seconds % 60)).toString().padStart(2,'0');
 // add ms
  let ms = s*1000
  return {d,h,m,s,ms};
}
function useInterval(callback: any, delay: any) {
  const savedCallback: any = React.useRef();

  React.useEffect(() => {
    savedCallback.current = callback;
  });

  React.useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" />


问:
FOREIGN KEY (`shiftid`, `groupid`, `sectionid`) REFERENCES `tbl_academic`(`id`, `id`, `id`) is not working in mysql database
```<code>ALTER TABLE `tbl_acc_payable` ADD CONSTRAINT `FK_APAY_SGS` FOREIGN KEY (`shiftid`, `groupid`, `sectionid`) REFERENCES `tbl_academic`(`id`, `id`, `id`) ON DELETE SET NULL ON UPDATE CASCADE
</code>```

why I cannot apply multiple columns references another table multiple column in MySQL database?

return Error Message:

#1005 - Can't create table fastpay.tbl_acc_payable (errno: 150 "Foreign key constraint is incorrectly formed") (Details…)

答:
FK references used the whole expression value or its prefix. The value - not the column name.

You need to reference to the values in 3 different rows which cannot be provided by composite index. So create 3 separate foreign keys referred to the same index tbl_academic(id):

```<code>ALTER TABLE tbl_acc_payable
ADD CONSTRAINT FK_APAY_SGS_1
  FOREIGN KEY (shiftid)
  REFERENCES tbl_academic(id)
  ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT FK_APAY_SGS_2
  FOREIGN KEY (groupid)
  REFERENCES tbl_academic(id)
  ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT FK_APAY_SGS_3
  FOREIGN KEY (sectionid)
  REFERENCES tbl_academic(id)
  ON DELETE SET NULL ON UPDATE CASCADE;
</code>```

Body:
ALTER TABLE `tbl_acc_payable` ADD CONSTRAINT `FK_APAY_SGS` FOREIGN KEY (`shiftid`, `groupid`, `sectionid`) REFERENCES `tbl_academic`(`id`, `id`, `id`) ON DELETE SET NULL ON UPDATE CASCADE

why I cannot apply multiple columns references another table multiple column in MySQL database?

return Error Message:

#1005 - Can't create table fastpay.tbl_acc_payable (errno: 150 "Foreign key constraint is incorrectly formed") (Details…)

Body:
FK references used the whole expression value or its prefix. The value - not the column name.

You need to reference to the values in 3 different rows which cannot be provided by composite index. So create 3 separate foreign keys referred to the same index tbl_academic(id):

ALTER TABLE tbl_acc_payable
ADD CONSTRAINT FK_APAY_SGS_1
  FOREIGN KEY (shiftid)
  REFERENCES tbl_academic(id)
  ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT FK_APAY_SGS_2
  FOREIGN KEY (groupid)
  REFERENCES tbl_academic(id)
  ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT FK_APAY_SGS_3
  FOREIGN KEY (sectionid)
  REFERENCES tbl_academic(id)
  ON DELETE SET NULL ON UPDATE CASCADE;


问:
Syntax error in SQL statement - H2 error 42001
Upon running this SQL statement:

select TimeInterval,
       ((((Timer*60)/1.0)*100)/((10.0*60)/60.0)) as 'Throughput-run_1_8_11'
from StatExternalData, StatisticDefinition
where StatisticDefinition.ID=StatExternalData.StatDefId
      and StatisticName='PSI_CompTran_Successful_Cnt'
order by TimeInterval asc
```

<p>I get this error:</p>

<pre class="lang-none prettyprint-override"><code>"select TimeInterval, ((((Timer*60)/1.0)*100)/((10.0*60)/60.0)) as 'Throughput-run_1_8_11'[*] from StatExternalData, StatisticDefinition where StatisticDefinition.ID=StatExternalData.StatDefId and StatisticName='PSI_CompTran_Successful_Cnt'  order by TimeInterval asc";
expected "identifier"; [42001-185]
</code>```

I've figured out that the [*] is indicating what part of the statement is incorrect and that H2 error code 42001 signifies an invalid SQL statement, but I've been banging my head on the wall for weeks trying to figure out what the problem is, anyone have an idea?

答: In case of 42001-197 you can also check for Oracle analytical functions and H2 version, which needs to be from 1.4.198 onward, especially for ROW_NUMBER OVER PARTITION.</p>

Body:
Upon running this SQL statement:

select TimeInterval,
       ((((Timer*60)/1.0)*100)/((10.0*60)/60.0)) as 'Throughput-run_1_8_11'
from StatExternalData, StatisticDefinition
where StatisticDefinition.ID=StatExternalData.StatDefId
      and StatisticName='PSI_CompTran_Successful_Cnt'
order by TimeInterval asc

I get this error:

"select TimeInterval, ((((Timer*60)/1.0)*100)/((10.0*60)/60.0)) as 'Throughput-run_1_8_11'[*] from StatExternalData, StatisticDefinition where StatisticDefinition.ID=StatExternalData.StatDefId and StatisticName='PSI_CompTran_Successful_Cnt'  order by TimeInterval asc";
expected "identifier"; [42001-185]

I've figured out that the [*] is indicating what part of the statement is incorrect and that H2 error code 42001 signifies an invalid SQL statement, but I've been banging my head on the wall for weeks trying to figure out what the problem is, anyone have an idea?


答:
This helps

>>[i.replace('hpp','h') if 'hpp' in i else i for i in filenames ]
['program.c', 'stdio.h', 'sample.h', 'a.out', 'math.h', 'h.out']

Title: How do I edit multiple elements in a list on a conditional basis?


问:
Is there a synchronous alternative of setState() in Reactjs functional components
I know how to do this in class components but when i use same code in functional component i get an error. This is what i want -

```<code>this.setState({cnt:this.state.cnt+1})
alert(this.state.cnt);
</code>```

now i want the alert to show count as 1 .
How we do it in class component -

this.setState({cnt:this.state.cnt+1}, () => alert(this.state.cnt));

But when i do same in functional component like this

```<code>const[count, setCount] = useState(0);
setCount(count+1, () => alert(count));
</code>```

I get an error - "expected no of arguments - 1".

答:
State updater with react-hooks doesn't provide a callback. You need to use useEffect to achieve the same behavior. Also since you would want the useEffect to run only on update you can disable its initial execution with the help of a useRef

```<code>setCount(prev => prev+1);
...
const initialRender = useRef(true);
useEffect(() => {
   if(!initialRender.current) {
     alert(count);
   } else {
     initialRender.current = false;
   }
}, [count]);
</code>```

In some cases you may not want the useEffect to trigger whenever count is updated but only when count is updated from a special function. In such cases you can make use of useRef

```<code>const runEffect = useRef(false);
const initialRender = useRef(true);
useEffect(() => {
   if(!initialRender.current) {
     // This will only be executed when you toggle ref

     alert(count);
   } else {
     initialRender.current = false;
   }
}, [runEffect.current]);
// adding ref as a dependency is fine here since we know that a re-render will be triggered by setCount

someFunction = () => {
   setCount(prev => prev + 1);
   runEffect.current = !runEffect.current;
}
</code>```

Body:
I know how to do this in class components but when i use same code in functional component i get an error. This is what i want -

this.setState({cnt:this.state.cnt+1})
alert(this.state.cnt);

now i want the alert to show count as 1 .
How we do it in class component -

this.setState({cnt:this.state.cnt+1}, () => alert(this.state.cnt));

But when i do same in functional component like this

const[count, setCount] = useState(0);
setCount(count+1, () => alert(count));

I get an error - "expected no of arguments - 1".

Body:
State updater with react-hooks doesn't provide a callback. You need to use useEffect to achieve the same behavior. Also since you would want the useEffect to run only on update you can disable its initial execution with the help of a useRef

setCount(prev => prev+1);
...
const initialRender = useRef(true);
useEffect(() => {
   if(!initialRender.current) {
     alert(count);
   } else {
     initialRender.current = false;
   }
}, [count]);

In some cases you may not want the useEffect to trigger whenever count is updated but only when count is updated from a special function. In such cases you can make use of useRef

const runEffect = useRef(false);
const initialRender = useRef(true);
useEffect(() => {
   if(!initialRender.current) {
     // This will only be executed when you toggle ref

     alert(count);
   } else {
     initialRender.current = false;
   }
}, [runEffect.current]);
// adding ref as a dependency is fine here since we know that a re-render will be triggered by setCount

someFunction = () => {
   setCount(prev => prev + 1);
   runEffect.current = !runEffect.current;
}


问:
why isnt my code printing out the highest and 1st runner up properly?
Main:

```<code>public class Main {

  private static String [] Countries={"UK", "Italy",
            "Germany", "Thailand","Denmark","Japan","Spain","Argentina"};
  static double average[] = new double[8];
  double[] results = new double[8];

  public static String getWinner(ArrayList<MissUniverse>alist){
    int winner = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() ) {
            winner= s;
        }
    }
    return alist.get(winner).getCountry();
  }

public static String firstRunnerUp(ArrayList<MissUniverse>alist){
    int firstrunnerUp =0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() && alist.get(s).getCountry() != getWinner(alist) ) {
            firstrunnerUp = s;
        }
    }
    return alist.get(firstrunnerUp).getCountry();

  }

 public static void main (String[] args){
   ArrayList<MissUniverse> alist = new ArrayList<MissUniverse>();
 MissUniverse missUniverse[] = new MissUniverse[Countries.length];

        for(int i=0;i<Countries.length;i++)
        {
            missUniverse[i] = new MissUniverse(Countries[i]);
            missUniverse[i].getScore();
            alist.add(missUniverse[i]);
        }

   System.out.printf("%-15s%-5s%-5s%-5s%-5s%-5s%-5s%-5s%-5s%-10s",
                "Countries","1","2","3","4","5","6","7","8","Average");
    System.out.println();
    for (int i = 0; i < Countries.length; i++){
    System.out.printf("%-13s",Countries[i]);
    missUniverse[i].printInfo();
    System.out.printf("%5.1f", alist.get(i).average() );
    System.out.println();
    }
    System.out.println("The result is");
    System.out.println("Winner: Miss " + getWinner(alist) );
    System.out.println("1st Runner Up: Miss " + firstRunnerUp(alist) );

  }
}
</code>```

MissUniverse:

```<code>class MissUniverse {
  public static int SIZE=8;
  private String country;
  private double[] score;

  public MissUniverse(String country){
    this.country = country;
    score = new double [SIZE];
  }

  public String getCountry(){
    return country;
  }

  public void getScore(){
      for (int i=0;i<score.length;i++)
        {
            score[i] = Math.random()*10;
        }
  }

  public void setCountry(String newCountry) {
    this.country = newCountry;
  }

 private int highest(){
  int i;
        double highest;
        highest = score[0];

        for (i = 0; i <score.length; i++)
        {
            if (highest < score [i])
            {
                highest = score[i] ;
            }
        }
        return i;
  }

  private int lowest(){
  int i;
        double lowest;
        lowest = score[0];
        for (i = 0; i <score.length; i++)
        {
            if (lowest > score [i])
            {
                lowest = score[i];
            }
        }
        return i;
  }

  public double average(){

    double sum = 0.0;
     for (int i = 0; i < score.length; i++){
        sum +=  score[i];
     }
    double average;
    average = (sum - score[lowest()-1] - score[highest()-1] )/ (score.length - 2);
    return average;
  }

  public void printInfo(){

      for(int i=0;i< score.length;i++){
      System.out.printf("%-5.1f",score[i]);
      }

  }
}
</code>```

Why is the output wrong?

output 1:

```<code>Countries      1    2    3    4    5    6    7    8    Average
UK           2.0  0.5  3.7  2.0  5.2  7.0  9.2  5.8    4.0
Italy        3.9  3.8  2.4  5.1  5.7  1.0  6.7  6.9    3.6
Germany      7.0  0.5  8.4  2.4  6.3  4.4  8.8  7.1    5.1
Thailand     6.9  8.7  3.9  4.7  4.9  3.5  4.7  9.4    4.7
Denmark      0.5  0.9  3.4  3.3  6.3  10.0 7.0  6.6    4.1
Japan        4.2  2.1  5.9  9.4  9.8  2.3  4.2  9.7    4.7
Spain        6.5  4.0  6.5  3.6  8.5  8.5  9.2  9.4    6.2
Argentina    0.4  6.6  6.5  2.3  2.6  4.5  5.6  3.7    4.1
The result is
Winner: Miss Argentina
1st Runner Up: Miss Spain
</code>```

its supposed to be winner: miss spain, runner up: miss germany.
but isnt the logic in getWinner(alist) and firstrunnerup(alist) correct?

output 2:

```<code>Countries      1    2    3    4    5    6    7    8    Average
UK           0.5  9.2  2.8  1.3  7.0  9.6  6.9  6.9    5.1
Italy        4.3  7.6  2.3  3.3  8.6  9.3  7.0  3.1    6.5
Germany      2.2  0.4  6.1  4.4  5.8  3.1  5.5  9.1    3.1
Thailand     1.7  7.1  6.2  9.5  7.9  4.9  0.8  8.3    5.0
Denmark      1.6  1.6  2.5  6.5  8.8  5.8  3.7  1.2    4.9
Japan        7.4  1.5  5.6  1.6  3.1  5.8  3.2  3.4    4.1
Spain        0.2  0.9  0.3  7.2  1.5  7.8  7.3  8.6    2.7
Argentina    9.1  8.9  0.3  5.1  2.6  8.8  4.3  5.1    5.7
The result is
Winner: Miss Argentina
1st Runner Up: Miss Italy
</code>```

its supposed to be:
winner:italy
runner up:argentina

can someone point me in the right direction?i think the mistake is supposed to be in the getwinner and firstrunnerup methods but i can't spot the mistake.

答:
In getWinner() change

```<code>if (alist.get(s).average() > alist.get(0).average() ) {
</code>```

to

```<code>if (alist.get(s).average() > alist.get(winner).average() ) {
</code>```

Similarly in getFirstRunnerUp() change

```<code>if (alist.get(s).average() > alist.get(0).average() && alist.get(s).getCountry() != getWinner(alist) ) {
</code>```

to

```<code>if (alist.get(s).average() > alist.get(firstRunnerUp).average() && alist.get(s).getCountry() != getWinner(alist) ) {
</code>```

Body:
Main:

public class Main {

  private static String [] Countries={"UK", "Italy",
            "Germany", "Thailand","Denmark","Japan","Spain","Argentina"};
  static double average[] = new double[8];
  double[] results = new double[8];

  public static String getWinner(ArrayList<MissUniverse>alist){
    int winner = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() ) {
            winner= s;
        }
    }
    return alist.get(winner).getCountry();
  }

public static String firstRunnerUp(ArrayList<MissUniverse>alist){
    int firstrunnerUp =0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() && alist.get(s).getCountry() != getWinner(alist) ) {
            firstrunnerUp = s;
        }
    }
    return alist.get(firstrunnerUp).getCountry();

  }

 public static void main (String[] args){
   ArrayList<MissUniverse> alist = new ArrayList<MissUniverse>();
 MissUniverse missUniverse[] = new MissUniverse[Countries.length];

        for(int i=0;i<Countries.length;i++)
        {
            missUniverse[i] = new MissUniverse(Countries[i]);
            missUniverse[i].getScore();
            alist.add(missUniverse[i]);
        }

   System.out.printf("%-15s%-5s%-5s%-5s%-5s%-5s%-5s%-5s%-5s%-10s",
                "Countries","1","2","3","4","5","6","7","8","Average");
    System.out.println();
    for (int i = 0; i < Countries.length; i++){
    System.out.printf("%-13s",Countries[i]);
    missUniverse[i].printInfo();
    System.out.printf("%5.1f", alist.get(i).average() );
    System.out.println();
    }
    System.out.println("The result is");
    System.out.println("Winner: Miss " + getWinner(alist) );
    System.out.println("1st Runner Up: Miss " + firstRunnerUp(alist) );

  }
}

MissUniverse:

class MissUniverse {
  public static int SIZE=8;
  private String country;
  private double[] score;

  public MissUniverse(String country){
    this.country = country;
    score = new double [SIZE];
  }

  public String getCountry(){
    return country;
  }

  public void getScore(){
      for (int i=0;i<score.length;i++)
        {
            score[i] = Math.random()*10;
        }
  }

  public void setCountry(String newCountry) {
    this.country = newCountry;
  }

 private int highest(){
  int i;
        double highest;
        highest = score[0];

        for (i = 0; i <score.length; i++)
        {
            if (highest < score [i])
            {
                highest = score[i] ;
            }
        }
        return i;
  }

  private int lowest(){
  int i;
        double lowest;
        lowest = score[0];
        for (i = 0; i <score.length; i++)
        {
            if (lowest > score [i])
            {
                lowest = score[i];
            }
        }
        return i;
  }

  public double average(){

    double sum = 0.0;
     for (int i = 0; i < score.length; i++){
        sum +=  score[i];
     }
    double average;
    average = (sum - score[lowest()-1] - score[highest()-1] )/ (score.length - 2);
    return average;
  }

  public void printInfo(){

      for(int i=0;i< score.length;i++){
      System.out.printf("%-5.1f",score[i]);
      }

  }
}

Why is the output wrong?

output 1:

Countries      1    2    3    4    5    6    7    8    Average
UK           2.0  0.5  3.7  2.0  5.2  7.0  9.2  5.8    4.0
Italy        3.9  3.8  2.4  5.1  5.7  1.0  6.7  6.9    3.6
Germany      7.0  0.5  8.4  2.4  6.3  4.4  8.8  7.1    5.1
Thailand     6.9  8.7  3.9  4.7  4.9  3.5  4.7  9.4    4.7
Denmark      0.5  0.9  3.4  3.3  6.3  10.0 7.0  6.6    4.1
Japan        4.2  2.1  5.9  9.4  9.8  2.3  4.2  9.7    4.7
Spain        6.5  4.0  6.5  3.6  8.5  8.5  9.2  9.4    6.2
Argentina    0.4  6.6  6.5  2.3  2.6  4.5  5.6  3.7    4.1
The result is
Winner: Miss Argentina
1st Runner Up: Miss Spain

its supposed to be winner: miss spain, runner up: miss germany.
but isnt the logic in getWinner(alist) and firstrunnerup(alist) correct?

output 2:

Countries      1    2    3    4    5    6    7    8    Average
UK           0.5  9.2  2.8  1.3  7.0  9.6  6.9  6.9    5.1
Italy        4.3  7.6  2.3  3.3  8.6  9.3  7.0  3.1    6.5
Germany      2.2  0.4  6.1  4.4  5.8  3.1  5.5  9.1    3.1
Thailand     1.7  7.1  6.2  9.5  7.9  4.9  0.8  8.3    5.0
Denmark      1.6  1.6  2.5  6.5  8.8  5.8  3.7  1.2    4.9
Japan        7.4  1.5  5.6  1.6  3.1  5.8  3.2  3.4    4.1
Spain        0.2  0.9  0.3  7.2  1.5  7.8  7.3  8.6    2.7
Argentina    9.1  8.9  0.3  5.1  2.6  8.8  4.3  5.1    5.7
The result is
Winner: Miss Argentina
1st Runner Up: Miss Italy

its supposed to be:
winner:italy
runner up:argentina

can someone point me in the right direction?i think the mistake is supposed to be in the getwinner and firstrunnerup methods but i can't spot the mistake.

Body:
In getWinner() change

if (alist.get(s).average() > alist.get(0).average() ) {

to

if (alist.get(s).average() > alist.get(winner).average() ) {

Similarly in getFirstRunnerUp() change

if (alist.get(s).average() > alist.get(0).average() && alist.get(s).getCountry() != getWinner(alist) ) {

to

if (alist.get(s).average() > alist.get(firstRunnerUp).average() && alist.get(s).getCountry() != getWinner(alist) ) {


问:
Checklistbox adding items

Any know what will be the problem? I want to add Items to checklistbox but nothing happens... Items are CollectionItems in a Table Collection. Tables has a Name property

```<code>  procedure TForm1.FormShow(Sender: TObject);
  var

  DisplayName: string;
  c :integer;
  begin

 for C := 0 to Compname.Tables.Count - 1 do
  with cxCheckListBox1.Items.Add do
  begin
  DisplayName := Compname.Tables.Items[C].TableName;
  Tag := C;
end;
</code>```

end;

Thanks!

答:
If needed to store in list not only strings but also additional data (for examole some identifier) Items.Add() method isn't appropriate. In this case useful is Items.AddObject() method.

For example, adding new item:

```<code>lbFeatures.AddItem(
      qrFeatures.FieldByName('DESCR').AsString,
      TObject(qrFeatures.FieldByName('ID').AsInteger));
</code>```

And read stored ID:

```<code>if lbFeatures.Checked[I] then
  id := Integer(lbFeatures.Items.Objects[I]);
</code>```

Title: Checklistbox adding items

Body:
Any know what will be the problem? I want to add Items to checklistbox but nothing happens... Items are CollectionItems in a Table Collection. Tables has a Name property

  procedure TForm1.FormShow(Sender: TObject);
  var

  DisplayName: string;
  c :integer;
  begin

 for C := 0 to Compname.Tables.Count - 1 do
  with cxCheckListBox1.Items.Add do
  begin
  DisplayName := Compname.Tables.Items[C].TableName;
  Tag := C;
end;

end;

Thanks!

Body:
If needed to store in list not only strings but also additional data (for examole some identifier) Items.Add() method isn't appropriate. In this case useful is Items.AddObject() method.

For example, adding new item:

lbFeatures.AddItem(
      qrFeatures.FieldByName('DESCR').AsString,
      TObject(qrFeatures.FieldByName('ID').AsInteger));

And read stored ID:

if lbFeatures.Checked[I] then
  id := Integer(lbFeatures.Items.Objects[I]);


问:
Skip lines while reading csv - Azure Data Factory
I am trying to copy data from Blob to Azure SQL using data flows within a pipeline.
Data Files is in csv format and the Header is at 4th row in the csv file.
i want to use the header as is what is available in the csv data file.

I want to loop through all the files and upload data.

Thanks

答: Add a Surrogate Key transformation and then a Filter transformation to filter out row number 4.</p>


问:
How to update UICollectionView inside UITableViewCell after transition to landscape
I have the following collectionView:

https://youtu.be/dY2MDeFINEY

I want the images to stay centered during transitions in landscape and even the "paging-behaviour" of the collectionView should remain.

To achieve this, I have tried a couple of things. My current code (just for the transition) looks like this:

Code of the TableViewController, which holds the TableViewCell with the collectionView:

```<code>...
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        let indexPath = IndexPath(row: 1, section: 0)//The position of the row doesn't change
        let cell = tableView.cellForRow(at: indexPath) as? PlantDetailImageTableViewCell
        tableView.reloadData()
        cell?.respondToTransition()
    }
...
</code>```

The method respondToTransition (inside the TableViewCell which holds the collectionView) looks like this:

```<code>func respondToTransition() {
        collectionView.collectionViewLayout.invalidateLayout()
        let indexPath = IndexPath(item: pageControl.currentPage, section: 0)

        DispatchQueue.main.async {
            self.pageControl.currentPage = indexPath.row
            self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        }
    }
</code>```

My flow layout is the following:

```<code>extension PlantDetailImageTableViewCell: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.frame.size
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        pageControl.currentPage = Int(self.collectionView.contentOffset.x / self.collectionView.frame.size.width)
    }
}
</code>```

The result on transition to landsape is the following:

https://youtu.be/RlTX0LgfKEY

How could I force the images to keep centered. In addition it seems like the collectionView "losts" a "bit" of their "paging behaviour".

The view debugger of Xcode shows the following for landscape (the marked blue is the imageview inside the collectionView cell):

Any help is appreciated!

EDIT:

The problem only occurs, when I'm trying to go from portrait to landscape. So if I start the app in landscape, then everything works as expected.

答:
I came up with a solution for the problem.

As LeoDabus mentioned in the comment section, the call for tableView.reloadData() in the TableViewController was unnecessary. So I deleted this one and in addition, I have changed respondToTransition() to the following:

```<code>func respondToTransition() {
    collectionView.collectionViewLayout.invalidateLayout()
    let indexPath = IndexPath(item: pageControl.currentPage, section: 0)

    DispatchQueue.main.async {
        self.collectionView.reloadData()//!!!
        self.pageControl.currentPage = indexPath.row
        self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }
}
</code>```

My flow layout is still the same...

Body:
I have the following collectionView:

https://youtu.be/dY2MDeFINEY

I want the images to stay centered during transitions in landscape and even the "paging-behaviour" of the collectionView should remain.

To achieve this, I have tried a couple of things. My current code (just for the transition) looks like this:

Code of the TableViewController, which holds the TableViewCell with the collectionView:

...
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        let indexPath = IndexPath(row: 1, section: 0)//The position of the row doesn't change
        let cell = tableView.cellForRow(at: indexPath) as? PlantDetailImageTableViewCell
        tableView.reloadData()
        cell?.respondToTransition()
    }
...

The method respondToTransition (inside the TableViewCell which holds the collectionView) looks like this:

func respondToTransition() {
        collectionView.collectionViewLayout.invalidateLayout()
        let indexPath = IndexPath(item: pageControl.currentPage, section: 0)

        DispatchQueue.main.async {
            self.pageControl.currentPage = indexPath.row
            self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        }
    }

My flow layout is the following:

extension PlantDetailImageTableViewCell: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.frame.size
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        pageControl.currentPage = Int(self.collectionView.contentOffset.x / self.collectionView.frame.size.width)
    }
}

The result on transition to landsape is the following:

https://youtu.be/RlTX0LgfKEY

How could I force the images to keep centered. In addition it seems like the collectionView "losts" a "bit" of their "paging behaviour".

The view debugger of Xcode shows the following for landscape (the marked blue is the imageview inside the collectionView cell):

Any help is appreciated!

EDIT:

The problem only occurs, when I'm trying to go from portrait to landscape. So if I start the app in landscape, then everything works as expected.

Body:
I came up with a solution for the problem.

As LeoDabus mentioned in the comment section, the call for tableView.reloadData() in the TableViewController was unnecessary. So I deleted this one and in addition, I have changed respondToTransition() to the following:

func respondToTransition() {
    collectionView.collectionViewLayout.invalidateLayout()
    let indexPath = IndexPath(item: pageControl.currentPage, section: 0)

    DispatchQueue.main.async {
        self.collectionView.reloadData()//!!!
        self.pageControl.currentPage = indexPath.row
        self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }
}

My flow layout is still the same...


问:
JSON to C# Classes - Unknown property names
let's say I have the following JSON payload;

```<code>  {
   "pagemap": {
    "metatags": [
     {
      "msapplication-task": "name\u003dAbout Tugberk Ugurlu;action-uri\u003d/about;icon-uri\u003d/content/App_Icons/icos/about.ico",
      "msapplication-task": "name\u003dContact;action-uri\u003d/contact;icon-uri\u003d/content/App_Icons/icos/contact.ico",
      "msapplication-task": "name\u003dBlog RSS Feed;action-uri\u003dhttp://feeds.feedburner.com/TugberkUgurlu;icon-uri\u003d/content/App_Icons/icos/rss.ico",
      "msapplication-task": "name\u003dTugberk on Twitter;action-uri\u003dhttp://twitter.com/tourismgeek;icon-uri\u003d/content/App_Icons/icos/twitter.ico",
      "msapplication-starturl": "./",
      "application-name": "Tugberk's Blog",
      "msapplication-tooltip": "bla bla bla..."
     }
    ]
   }
  }
</code>```

The property names under mettags are dynamic. I mean one of them is msapplication-starturl for this request but it might be msapplication-foo for another.

So what would be the best c# classes for this kind of JSON payload?

EDIT

this is the part of JSON format which google search API gives. Also I am using Json.NET. is There any other way than dynamic?

答:
I'd probably just want the MetaTags array to just get pushed into a Dictionary<string,string> or even just List<string> and then write a helper class that parses msapplication-task values into something you want.

Edit: I believe the OP is looking for some help in how his model class would actually be

```<code>public class PageMap
{
    public Dictionary<string,string> MetaTags {get;set; }
}
</code>```

From looking at that json object, it appears that RestSharp should be able to deserialize it into this class.

Calling code would be similar to

```<code>var client = new RestClient("somegoogle.com");
var request = new RestRequest("Some/Foo/Bar", Method.GET)
                                 { RequestFormat = DataFormat.Json };
request.AddParameter("p1", "quigybo");
client.Execute<PageMan>(request)
</code>```

Body:
let's say I have the following JSON payload;

  {
   "pagemap": {
    "metatags": [
     {
      "msapplication-task": "name\u003dAbout Tugberk Ugurlu;action-uri\u003d/about;icon-uri\u003d/content/App_Icons/icos/about.ico",
      "msapplication-task": "name\u003dContact;action-uri\u003d/contact;icon-uri\u003d/content/App_Icons/icos/contact.ico",
      "msapplication-task": "name\u003dBlog RSS Feed;action-uri\u003dhttp://feeds.feedburner.com/TugberkUgurlu;icon-uri\u003d/content/App_Icons/icos/rss.ico",
      "msapplication-task": "name\u003dTugberk on Twitter;action-uri\u003dhttp://twitter.com/tourismgeek;icon-uri\u003d/content/App_Icons/icos/twitter.ico",
      "msapplication-starturl": "./",
      "application-name": "Tugberk's Blog",
      "msapplication-tooltip": "bla bla bla..."
     }
    ]
   }
  }

The property names under mettags are dynamic. I mean one of them is msapplication-starturl for this request but it might be msapplication-foo for another.

So what would be the best c# classes for this kind of JSON payload?

EDIT

this is the part of JSON format which google search API gives. Also I am using Json.NET. is There any other way than dynamic?

Body:
I'd probably just want the MetaTags array to just get pushed into a Dictionary<string,string> or even just List<string> and then write a helper class that parses msapplication-task values into something you want.

Edit: I believe the OP is looking for some help in how his model class would actually be

public class PageMap
{
    public Dictionary<string,string> MetaTags {get;set; }
}

From looking at that json object, it appears that RestSharp should be able to deserialize it into this class.

Calling code would be similar to

var client = new RestClient("somegoogle.com");
var request = new RestRequest("Some/Foo/Bar", Method.GET)
                                 { RequestFormat = DataFormat.Json };
request.AddParameter("p1", "quigybo");
client.Execute<PageMan>(request)


答:
The pattern here is to also use a useEffect hook with a dependency array of the state value you want to alert on. The effect hook runs once per render when state updates, and the dependency array helps filter when the effect actually triggers, in this case when count updates.

```<code>const [count, setCount] = useState(0);

useEffect(() => {
  alert('count updated!);
}, [count]);
</code>```

Title: Is there a synchronous alternative of setState() in Reactjs functional components

Body:
The pattern here is to also use a useEffect hook with a dependency array of the state value you want to alert on. The effect hook runs once per render when state updates, and the dependency array helps filter when the effect actually triggers, in this case when count updates.

const [count, setCount] = useState(0);

useEffect(() => {
  alert('count updated!);
}, [count]);


问:
Angular: Reuse reducer and selectors in different roots (not using redux)
I do have different routes

/department

/candidates

/candidates-department

I have to use the same reducer structure (state and action) in /candidates and /candidates-department. The candidate part is common with minor difference in fetching data from api and having that data in store.

so /candidates will list all candidates, but for /candidates-department we do have department list that shows candidates corresponding to that department.

Is there any way I can use the same store/action/reducer from /candidates in /candidates-department with only difference in feature key in both /candidates and /candidates-department.

I need to reuse selectors as well.

答:
ngrx provides a single storage for a single StoreModule.forRoot. All its children will use the same store.

If you want to achieve desired behavior you need to change the structure of your app so that StoreModule.forRoot is called in a child module that belongs to the rote.

If you need to call StoreModule.forRoot in AppModule due to other dependencies, then bad news, there's no way to split contexts for child modules of a parent with StoreModule.forRoot.

If you need it - try to add to your actions a property that points to a key. And then respect this key in reducers and selectors. It requires more coding, but that's the only way to split it currently.


答:
You can get your result by doing:

elements = [str(name.split('.')[0] + '.h') for name in filenames if name.endswith('.hpp')]
```

Body:
An assignment I'm working on for school has tasked me with writing a script in Python that will edit a list of file names. All the files that end with the "hpp" extension must be renamed to "h".

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]

Can this be solved using a list comparision? This is what I have so far...

def newfilenames(filenames):
  elements = [ "h".format(filenames) for filenames]


问:
How to map an object using a string name to refer to that object?
I'm trying to reduce the hardcoded values in my code. Currently the set up is as follows

```<code>//FROM THE DATA FILE
AppleTable = [
{name: 'test', type: 'fruit' },
{name: 'test2', type: 'fruit' },
{name: 'test3', type: 'fruit' },]

BananaTable = [
{name: 'test', type: 'fruit' },
{name: 'test2', type: 'fruit' },
{name: 'test3', type: 'fruit' },]

//IN A DIFFERENT FILE
import {AppleTable, BananaTable} from './Data'

var result = [];
var all = [];
if (category === 'Apples'){
  result = AppleTable.map(value)
  all = Objects.values('AppleTable')
}
</code>```

But how do I get rid of the hardcoded aspect of it so the information from the AppleTable and BananaTable can be accessed using the 'TableID' in the new Tables object shown below- I have a new Object called Tables and I have tried the following e.g.:

```<code>//FROM THE DATA FILE
export const Tables = [
 {name: 'Apple'  , TableID: 'AppleTable'},
 {name: 'Banana' , TableID: 'BananaTable'}
]

export const AppleTable = [
 {name: 'test', type: 'fruit' },
 {name: 'test2', type: 'fruit' },
 {name: 'test3', type: 'fruit' }
]

export const BananaTable = [
 {name: 'test', type: 'fruit' },
 {name: 'test2', type: 'fruit' },
 {name: 'test3', type: 'fruit' }
]

//IN A DIFFERENT FILE
import {Tables} from './Data'

var result = [];
var all = [];

var TableName = '';

for (var i = 0 ; i < Tables.length ; i++){
    if (category === Tables[i].name){
       TableName = Tables[i].TablesID //THIS IS THE NAME OF THE TABLE I WANT
       result = [TableName].map(value) //CARRIED OUT MAPPING USING THAT TABLE
       all = Objects.values([TableName]) //GET ALL THE VALUES BASED ON THAT TABLE NAME
   }
}
</code>```

I am aware this is not correct - How do I get it so that it maps the data from those tables as opposed to  mapping the string name.

答:
So, instead of setting string, you can simply set the table as reference to the TableID property in main data file like:

```<code>//FROM THE DATA FILE
const AppleTable = [
 {name: 'test', type: 'fruit' },
 {name: 'test2', type: 'fruit' },
 {name: 'test3', type: 'fruit' }
]

const BananaTable = [
 {name: 'test', type: 'fruit' },
 {name: 'test2', type: 'fruit' },
 {name: 'test3', type: 'fruit' }
]

export const Tables = [
 {name: 'Apple'  , TableID: AppleTable},
 {name: 'Banana' , TableID: BananaTable}
]
</code>```

And then in a different file, you can access them like:

```<code>if (category === Tables[i].name) {
  TableName = Tables[i].TablesID
  result = TableName.map(/* your mapping logic here */)
  all = Object.values(TableName)
}
</code>```

Body:
I'm trying to reduce the hardcoded values in my code. Currently the set up is as follows

//FROM THE DATA FILE
AppleTable = [
{name: 'test', type: 'fruit' },
{name: 'test2', type: 'fruit' },
{name: 'test3', type: 'fruit' },]

BananaTable = [
{name: 'test', type: 'fruit' },
{name: 'test2', type: 'fruit' },
{name: 'test3', type: 'fruit' },]

//IN A DIFFERENT FILE
import {AppleTable, BananaTable} from './Data'

var result = [];
var all = [];
if (category === 'Apples'){
  result = AppleTable.map(value)
  all = Objects.values('AppleTable')
}

But how do I get rid of the hardcoded aspect of it so the information from the AppleTable and BananaTable can be accessed using the 'TableID' in the new Tables object shown below- I have a new Object called Tables and I have tried the following e.g.:

//FROM THE DATA FILE
export const Tables = [
 {name: 'Apple'  , TableID: 'AppleTable'},
 {name: 'Banana' , TableID: 'BananaTable'}
]

export const AppleTable = [
 {name: 'test', type: 'fruit' },
 {name: 'test2', type: 'fruit' },
 {name: 'test3', type: 'fruit' }
]

export const BananaTable = [
 {name: 'test', type: 'fruit' },
 {name: 'test2', type: 'fruit' },
 {name: 'test3', type: 'fruit' }
]

//IN A DIFFERENT FILE
import {Tables} from './Data'

var result = [];
var all = [];

var TableName = '';

for (var i = 0 ; i < Tables.length ; i++){
    if (category === Tables[i].name){
       TableName = Tables[i].TablesID //THIS IS THE NAME OF THE TABLE I WANT
       result = [TableName].map(value) //CARRIED OUT MAPPING USING THAT TABLE
       all = Objects.values([TableName]) //GET ALL THE VALUES BASED ON THAT TABLE NAME
   }
}

I am aware this is not correct - How do I get it so that it maps the data from those tables as opposed to  mapping the string name.

Body:
So, instead of setting string, you can simply set the table as reference to the TableID property in main data file like:

//FROM THE DATA FILE
const AppleTable = [
 {name: 'test', type: 'fruit' },
 {name: 'test2', type: 'fruit' },
 {name: 'test3', type: 'fruit' }
]

const BananaTable = [
 {name: 'test', type: 'fruit' },
 {name: 'test2', type: 'fruit' },
 {name: 'test3', type: 'fruit' }
]

export const Tables = [
 {name: 'Apple'  , TableID: AppleTable},
 {name: 'Banana' , TableID: BananaTable}
]

And then in a different file, you can access them like:

if (category === Tables[i].name) {
  TableName = Tables[i].TablesID
  result = TableName.map(/* your mapping logic here */)
  all = Object.values(TableName)
}


问:
MPAndroidChart hide background grid
I'm using MPAndroidChart - LineChart in my android application. I want to remove gridlines from the background . How can I remove gridlines from the background?

Library: MPAndroidChart on GitHub

EDIT: I created my own custom LineChart using this library. I want to remove bottom line. how can I do that too?

答:
to remove borders from chart you can use setDrawBorder(boolean) property.

chart.setDrawBorders(false);

Title: MPAndroidChart hide background grid


答:
The problem is in the compare condition.

Your compare condition for the winner is this alist.get(s).average() > alist.get(0).average() but it should be this alist.get(s).average() > alist.get(winner).average(). You should compare with the current winner.

Same goes for runnerup function, it should be this alist.get(s).average() > alist.get(firstrunnerUp).average() && alist.get(s).getCountry() != getWinner(alist)

Title: why isnt my code printing out the highest and 1st runner up properly?


问:
How to deal with variable number of columns in dataframe
In the dataframe I have there are so many columns of which I only need a few. For instance

```<code>Col_A      Col_B      Col_C      Col_D      Col_E      Col_F
...        ...        ...      ...      ...      ...      ...
</code>```

I only need columns Col_A, Col_C and Col_E so currently what I do is df = df[['Col_A', 'Col_C', 'Col_E']] but the issue here is that not always there will columns A, C and E maybe all these wont be present. So I need if Col_A is in df.columns add to the df and so on. Is there any simple method to do this ? rather than so many if? Now if a Column is missing I get a KeyError: "['Col_C'] not in index

答:
You can use loc and isin

```<code>df.loc[:, df.columns.isin(['a','b','c'])]
</code>```

Body:
In the dataframe I have there are so many columns of which I only need a few. For instance

Col_A      Col_B      Col_C      Col_D      Col_E      Col_F
...        ...        ...      ...      ...      ...      ...

I only need columns Col_A, Col_C and Col_E so currently what I do is df = df[['Col_A', 'Col_C', 'Col_E']] but the issue here is that not always there will columns A, C and E maybe all these wont be present. So I need if Col_A is in df.columns add to the df and so on. Is there any simple method to do this ? rather than so many if? Now if a Column is missing I get a KeyError: "['Col_C'] not in index

Body:
You can use loc and isin

df.loc[:, df.columns.isin(['a','b','c'])]


问:
How to DRY Sass code using variables?
I have a design that uses colors to identify sections of the site. I have put a file with the color variables defined, since they can change and it is difficult to track them down through the CSS files.

```<code>$people: #D50000;
$galleries: #D500AA;
$projects: #D5BA00;
//etc...
</code>```

The name of my classes matches those of the variables. For example, the navigation menu is something like:

```<code><ul>
  <li class="people">People</div>
  <li class="galleries">Galleries</div>
  <li class="projects">Projects</div>
  <!-- etc... ->
</ul>
</code>```

and I find myself writing SASS like

```<code>#nav {
  ul {
    li.people    { border-left: 5px solid $people;    }
    li.galleries { border-left: 5px solid $galleries; }
    li.projects  { border-left: 5px solid $projects;  }
  }
}
</code>```

which I'd like to DRY up. I have tried to use mixins, but I don't know how to tell SASS to lookup a variable named after the argument I pass (variable indirection). I have something like:

```<code>@mixin menu-states($resource) {
  li.#{$resource} a {                     // This works
    border-left: 7px solid $#{$resource}; // But this doesn't...
  }
}
</code>```

Does anybody have a suggestion on how to DRY this? Thanks.

答:
this code works for me</p>

```<code>@mixin test($resource: "red"){
    $updated: unquote($resource);
    li.#{$updated} a{
        border-left: 7px solid $updated;
    }
}
</code>```

Title: How to DRY Sass code using variables?

Body:
I have a design that uses colors to identify sections of the site. I have put a file with the color variables defined, since they can change and it is difficult to track them down through the CSS files.

$people: #D50000;
$galleries: #D500AA;
$projects: #D5BA00;
//etc...

The name of my classes matches those of the variables. For example, the navigation menu is something like:

People

Galleries

Projects

Body:
this code works for me

@mixin test($resource: "red"){
    $updated: unquote($resource);
    li.#{$updated} a{
        border-left: 7px solid $updated;
    }
}


问:
React hook that runs AFTER the DOM updates
I have a React app where I am hiding/showing an element based on state, and want to do some  calculations on that DOM element after the state variable changes.

I've tried using useLayoutEffect, but this still runs before the DOM has updated, so my calculations aren't useful. Is my understanding of useLayoutEffect wrong? Am I using it incorrectly?

Here's what I have

const myComponent = () => {

  const elem = useRef()
  const [isElemVisible, setIElemVisible] = useState(false)

  useLayoutEffect(() => {
    // I want this to run AFTER the element is added/removed from the DOM
    // Instead this is run before the element is actually modified in the DOM (but the ref itself has changed)

    elem.current.getBoundingClientRect() // do something with this object if it exists
  }, [elem.current])

  return (

    { isElemVisible && (

    )}

  )
}
```

答:
An easy solution to this, is to manually check for state update in a useEffect hook:

const myComponent = () => {

  const elem = useRef()
  const [isElemVisible, setIElemVisible] = useState(false)

  useEffect(() => {
   if (isElemVisible) {
     // Assuming UI has updated:
     elem.current.getBoundingClientRect() // do something with this object
   }

  }, [isElemVisible])

  return (

    { isElemVisible && (

    )}

  )
}
```

Body:
An easy solution to this, is to manually check for state update in a useEffect hook:

const myComponent = () => {

  const elem = useRef()
  const [isElemVisible, setIElemVisible] = useState(false)

  useEffect(() => {
   if (isElemVisible) {
     // Assuming UI has updated:
     elem.current.getBoundingClientRect() // do something with this object
   }

  }, [isElemVisible])

  return (
   <div id="base-element">
    { isElemVisible && (
      <div id="element" ref={elem}></div>
    )}
   </div>
  )
}


问:
A subquery returning multple rows
I am getting an error in the below query.. can anyone help fixing this query

```<code>select c.CHANGE_NUMBER,
(select le.ENTRYVALUE from listentry  le
where le.ENTRYID = c.CATEGORY)as CATEGORY ,
(
            SELECT  last_name || ',' || first_name || '(' || loginid || ')'
            FROM agileuser
            WHERE id = c.ORIGINATOR
        ) initiator,(
            SELECT  last_name || ',' || first_name || '(' || loginid || ')'
            FROM agileuser
            WHERE id = c.owner
        ) coordinator, w.state,

(SELECT description
            FROM nodetable
            WHERE id = w.state
        ) workflow_status , TO_CHAR(w.LOCAL_DATE,'DD-MON-YY HH24:MI:SS')local_date,
      (select
        (trunc(to_date(B.local_date, 'DD-MON-YY HH24:MI:SS') - to_date(w.local_date, 'DD-MON-YY HH24:MI:SS')))as timediff
        FROM WORKFLOW_PROCESS w INNER JOIN WORKFLOW_PROCESS B ON B.order_by = (w.order_by + 1)
        where w.change_id=B.Change_id and w.change_id=9946301 )--ORDER BY w.order_by ASC

       from change c, WORKFLOW_PROCESS w
        where w.change_id = c.id-- order by w.ORDER_BY)
       and c.CHANGE_NUMBER='NPI001084'
      order by w.ORDER_BY,local_date ASC
</code>```

The trunc() query gives multiple records

```<code> select
     (trunc(to_date(B.local_date, 'DD-MON-YY HH24:MI:SS') - to_date(w.local_date, 'DD-MON-YY HH24:MI:SS')))as timediff
      FROM WORKFLOW_PROCESS w INNER JOIN WORKFLOW_PROCESS B ON B.order_by = (w.order_by + 1)
      where w.change_id=B.Change_id and w.change_id=9946301 ORDER BY w.order_by ASC
</code>```

hence not able to run along with this main query.

答:
What a mess! You should really consider using SQL formatter or - if you can't for some reason - try to format code you write manually. This is unreadable.

Anyway: although subqueries look like a nice way out of your problems, generally - avoid them. Most of those can be rewritten so that you properly join tables involved.

If you choose to use them within the SELECT statement, you have to make sure that each of them returns a single value.

This returns two or more rows:

```<code>SELECT (TRUNC (
             TO_DATE (b.local_date, 'DD-MON-YY HH24:MI:SS')
           - TO_DATE (w.local_date, 'DD-MON-YY HH24:MI:SS')))
          AS timediff
  FROM workflow_process w
       INNER JOIN workflow_process b ON b.order_by = (w.order_by + 1)
 WHERE     w.change_id = b.change_id
       AND w.change_id = 9946301
</code>```

How to fix it? I don't know, I don't have your tables and have no idea what you want. Simple options might be to:

```<code>select distinct timediff ...
</code>```

or

```<code>select max(timediff) ...
</code>```

or

```<code>select ...
where rownum = 1
</code>```

or some other option, but - again, it depends on something we don't know.

Title: A subquery returning multple rows

Body:
I am getting an error in the below query.. can anyone help fixing this query

select c.CHANGE_NUMBER,
(select le.ENTRYVALUE from listentry  le
where le.ENTRYID = c.CATEGORY)as CATEGORY ,
(
            SELECT  last_name || ',' || first_name || '(' || loginid || ')'
            FROM agileuser
            WHERE id = c.ORIGINATOR
        ) initiator,(
            SELECT  last_name || ',' || first_name || '(' || loginid || ')'
            FROM agileuser
            WHERE id = c.owner
        ) coordinator, w.state,

(SELECT description
            FROM nodetable
            WHERE id = w.state
        ) workflow_status , TO_CHAR(w.LOCAL_DATE,'DD-MON-YY HH24:MI:SS')local_date,
      (select
        (trunc(to_date(B.local_date, 'DD-MON-YY HH24:MI:SS') - to_date(w.local_date, 'DD-MON-YY HH24:MI:SS')))as timediff
        FROM WORKFLOW_PROCESS w INNER JOIN WORKFLOW_PROCESS B ON B.order_by = (w.order_by + 1)
        where w.change_id=B.Change_id and w.change_id=9946301 )--ORDER BY w.order_by ASC

       from change c, WORKFLOW_PROCESS w
        where w.change_id = c.id-- order by w.ORDER_BY)
       and c.CHANGE_NUMBER='NPI001084'
      order by w.ORDER_BY,local_date ASC

The trunc() query gives multiple records

 select
     (trunc(to_date(B.local_date, 'DD-MON-YY HH24:MI:SS') - to_date(w.local_date, 'DD-MON-YY HH24:MI:SS')))as timediff
      FROM WORKFLOW_PROCESS w INNER JOIN WORKFLOW_PROCESS B ON B.order_by = (w.order_by + 1)
      where w.change_id=B.Change_id and w.change_id=9946301 ORDER BY w.order_by ASC

hence not able to run along with this main query.

Body:
What a mess! You should really consider using SQL formatter or - if you can't for some reason - try to format code you write manually. This is unreadable.

Anyway: although subqueries look like a nice way out of your problems, generally - avoid them. Most of those can be rewritten so that you properly join tables involved.

If you choose to use them within the SELECT statement, you have to make sure that each of them returns a single value.

This returns two or more rows:

SELECT (TRUNC (
             TO_DATE (b.local_date, 'DD-MON-YY HH24:MI:SS')
           - TO_DATE (w.local_date, 'DD-MON-YY HH24:MI:SS')))
          AS timediff
  FROM workflow_process w
       INNER JOIN workflow_process b ON b.order_by = (w.order_by + 1)
 WHERE     w.change_id = b.change_id
       AND w.change_id = 9946301

How to fix it? I don't know, I don't have your tables and have no idea what you want. Simple options might be to:

select distinct timediff ...

or

select max(timediff) ...

or

select ...
where rownum = 1

or some other option, but - again, it depends on something we don't know.


问:
TypeScript compiler complains about nulls when using isNull
When I have strictNullChecks: true in tsconfig.json and use isNull for null checks, the compiler throws the error TS2531: Object is possibly 'null'. isNull gets rid of the error in VsCode, but the compiler still complains when I'm trying to build and run my Angular app. If I use === null for null checks, no error.

Is there a way to tell the compiler to respect isNull as a valid null check?

```<code>import { isNull } from "util"; // from @types/node
    ...

    public run() {
        this.printS("hello");
        this.printS(null);
    }

    public printS(s: string | null) {
        if (isNull(s)) {
            console.log("s is null");
            return;
        }
        console.log("s is not null: ", s.toString()); // error on this line
    }
</code>```

```<code>"typescript": "~3.2.2"
"@types/node": "~8.9.4",
</code>```

答:
isNull is deprecated since node v4.

    /** @deprecated since v4.0.0 - use `value === null` instead. */
    function isNull(object: any): object is null;
```

simply use s === null. That's enough.

Body:
When I have strictNullChecks: true in tsconfig.json and use isNull for null checks, the compiler throws the error TS2531: Object is possibly 'null'. isNull gets rid of the error in VsCode, but the compiler still complains when I'm trying to build and run my Angular app. If I use === null for null checks, no error.

Is there a way to tell the compiler to respect isNull as a valid null check?

import { isNull } from "util"; // from @types/node
    ...

    public run() {
        this.printS("hello");
        this.printS(null);
    }

    public printS(s: string | null) {
        if (isNull(s)) {
            console.log("s is null");
            return;
        }
        console.log("s is not null: ", s.toString()); // error on this line
    }

"typescript": "~3.2.2"
"@types/node": "~8.9.4",

Body:
isNull is deprecated since node v4.

    /** @deprecated since v4.0.0 - use `value === null` instead. */
    function isNull(object: any): object is null;

simply use s === null. That's enough.


问:
Download asset from private repo in java with kohsuke github api
I am trying to download assets from a private repository.
I use the kohsuke api, it allows me to see all releases and i can download assets from public repos, but in private repos i still can see all the releases but not download them.

Getting the following error:

```<code>java.io.FileNotFoundException: https://github.com/*username*/*repo*/releases/download/*tag*/asset.jar
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1909)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:245)
    at java.base/java.net.URL.openStream(URL.java:1117)
    at org.apache.commons.io.FileUtils.copyURLToFile(FileUtils.java:1460)
</code>```

The token has all the permissions.

答:
The API route for assets is in GHAsset.java and might not be complete for private repository download:

```<code> return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/releases/assets/" + getId();
</code>```

It is a code from 7 years ago (commit 178c9f)

And it might be missing the Accept: application/octet-stream header mentioned here (in a separate project)

Body:
I am trying to download assets from a private repository.
I use the kohsuke api, it allows me to see all releases and i can download assets from public repos, but in private repos i still can see all the releases but not download them.

Getting the following error:

java.io.FileNotFoundException: https://github.com/*username*/*repo*/releases/download/*tag*/asset.jar
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1909)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:245)
    at java.base/java.net.URL.openStream(URL.java:1117)
    at org.apache.commons.io.FileUtils.copyURLToFile(FileUtils.java:1460)

The token has all the permissions.

Body:
The API route for assets is in GHAsset.java and might not be complete for private repository download:

 return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/releases/assets/" + getId();

It is a code from 7 years ago (commit 178c9f)

And it might be missing the Accept: application/octet-stream header mentioned here (in a separate project)


问:
Write tables from Word (.docx) to Excel (.xlsx) using xlsxwriter
I am trying to parse a word (.docx) for tables, then copy these tables over to excel using xlsxwriter.
This is my code:

```<code>from docx.api import Document
import xlsxwriter

document = Document('/Users/xxx/Documents/xxx/Clauses Sample - Copy v1 - for merge.docx')
tables = document.tables

wb = xlsxwriter.Workbook('C:/Users/xxx/Documents/xxx/test clause retrieval.xlsx')
Sheet1 = wb.add_worksheet("Compliance")
index_row = 0

print(len(tables))

for table in document.tables:
data = []
keys = None
for i, row in enumerate(table.rows):
    text = (cell.text for cell in row.cells)

    if i == 0:
        keys = tuple(text)
        continue
    row_data = dict(zip(keys, text))
    data.append(row_data)
    #print (data)
    #big_data.append(data)
    Sheet1.write(index_row,0, str(row_data))
    index_row = index_row + 1

print(row_data)

wb.close()
</code>```

This is my desired output:

However, here is my actual output:

I am aware that my current output produces a list of string instead.

Is there anyway that I can get my desired output using xlsxwriter? Any help is greatly appreciated

答:
This is the portion of my code update that allowed me to get the output I want:

```<code>for row in block.rows:
        for x, cell in enumerate(row.cells):
            print(cell.text)
            Sheet1.write(index_row, x, cell.text)
        index_row += 1
</code>```

Output:

Body:
I am trying to parse a word (.docx) for tables, then copy these tables over to excel using xlsxwriter.
This is my code:

from docx.api import Document
import xlsxwriter

document = Document('/Users/xxx/Documents/xxx/Clauses Sample - Copy v1 - for merge.docx')
tables = document.tables

wb = xlsxwriter.Workbook('C:/Users/xxx/Documents/xxx/test clause retrieval.xlsx')
Sheet1 = wb.add_worksheet("Compliance")
index_row = 0

print(len(tables))

for table in document.tables:
data = []
keys = None
for i, row in enumerate(table.rows):
    text = (cell.text for cell in row.cells)

    if i == 0:
        keys = tuple(text)
        continue
    row_data = dict(zip(keys, text))
    data.append(row_data)
    #print (data)
    #big_data.append(data)
    Sheet1.write(index_row,0, str(row_data))
    index_row = index_row + 1

print(row_data)

wb.close()

This is my desired output:

However, here is my actual output:

I am aware that my current output produces a list of string instead.

Is there anyway that I can get my desired output using xlsxwriter? Any help is greatly appreciated

Body:
This is the portion of my code update that allowed me to get the output I want:

for row in block.rows:
        for x, cell in enumerate(row.cells):
            print(cell.text)
            Sheet1.write(index_row, x, cell.text)
        index_row += 1

Output: