问:
How to add a known type to a List<T>?
The overall goal here is like this:  We have a lot of CSV files of various names and format stored in Azure blob storage.  We need to convert them to lists.

I have an interface:

```<code>public interface IGpasData
{
    List<T> ConvertToList<T>(StreamReader reader);
}
</code>```

And then here's an example of a class that Implements it:

```<code>public class GpasTableOfContent : IGpasData
{
    public string TocProp0 { get; set; }
    public string TocProp1 { get; set; }
    public string TocProp2 { get; set; }

    public List<T> ConvertToList<T>(StreamReader reader)
    {
        List<T> dataList = new List<T>();
        while (!reader.EndOfStream)
        {
            var lineItem = reader.ReadLine();
            GpasTableOfContent dataItem = new GpasTableOfContent
            {
                TocProp0 = lineItem.Split(',')[0],
                TocProp1 = lineItem.Split(',')[1],
                Type = lineItem.Split(',')[2]
            };
            dataList.Add(dataItem);
        }
        return dataList;
    }
}
</code>```

To keep going with the example of the class above, there is a file called ToC.csv.  In a class that is designed to convert THAT file into a list, I make this call:

```<code>List<GpasTableOfContent> gpasToCList = ConvertCloudFileToList<GpasTableOfContent>("ToC.csv", "MyModel");
</code>```

Some other possible examples:

```<code>List<GpasFoo> gpasFooList = ConvertCloudFileToList<GpasFoo>("foo.csv", "MyModel");

List<GpasBar> gpasBarList = ConvertCloudFileToList<GpasBar>("bar.csv", "MyModel");
</code>```

Here's ConvertCloudFileToList:

```<code>private List<T> ConvertCloudFileToList<T>(string fileName, string modelName)
    {
        // Get the .csv file from the InProgress Directory
        string filePath = $"{modelName}/{fileName}";
        CloudFile cloudFile = _inProgressDir.GetFileReference(filePath);

        List<T> dataList = new List<T>();

        // Does the file exist?
        if (!cloudFile.Exists())
            return dataList;

        using (StreamReader reader = new StreamReader(cloudFile.OpenRead()))
        {
            IGpasData gpasData = (IGpasData)Activator.CreateInstance<T>();
            dataList = gpasData.ConvertToList<T>(reader);
        }

        return dataList;
    }
</code>```

And that brings us back to ConvertToList.  The problem is here:

```<code>dataList.Add(dataItem);
</code>```

Can not convert 'GpasFoo' to 'T'

Not sure how to work around this.

答:
As other have pointed out, this design is flawed:

```<code>public interface IGpasData
{
   List<T> ConvertToList<T>(StreamReader reader);
}
</code>```

This contract says that an IGpasData should only know how deserialize anything. It doesn't make sense.

An IGpasData should know how to deserialize itself, and for this we would need a self-referencing interface:

```<code>public interface IGpasData<T> where T : IGpasData<T>
{
    List<T> ConvertToList(StreamReader reader);
}

public class GpasBar: IGpasData<GpasBar>
{
    public string MyPropertyA { get; set; }
    public int MyPropertyB { get; set; }

    public List<GpasBar> ConvertToList(StreamReader reader)
    {
        var results = new List<GpasBar>();
        while (!reader.EndOfStream)
        {
            var values = reader.ReadLine().Split(',');
            results.Add(new GpasBar()
            {
                PropertyA = values[0],
                PropertyB = int.Parse(values[1]),
            });
        }
        return results;
    }
}
</code>```

Or, an IGpasData should know how to populate itself from an array of values:

```<code>public interface IGpasData
{
    void Populate(string[] values);
}
public class GpasBar
{
    public string MyPropertyA { get; set; }
    public int MyPropertyB { get; set; }

    public void Populate(string[] values)
    {
        MyPropertyA = values[0];
        MyPropertyB = int.Parse(values[1]);
    }
}

public static List<T> ConvertCloudFileToList<T>(string fileName, string modelName)
    where T : IGpasData, new()
{
    // ...
    using (StreamReader reader = new StreamReader(cloudFile.OpenRead()))
    {
        var results = new List<T>();
        while (!reader.EndOfStream)
        {
            var item = new T();
            item.Populate(reader.ReadLine().Split(','));

            results.Add(item);
        }
        return results;
    }
}
</code>```

Using this 2nd approach, you can avoid duplicating the part about StreamReader and read lines.

Title: How to add a known type to a List<T>?

Body:
The overall goal here is like this:  We have a lot of CSV files of various names and format stored in Azure blob storage.  We need to convert them to lists.

I have an interface:

public interface IGpasData
{
    List<T> ConvertToList<T>(StreamReader reader);
}

And then here's an example of a class that Implements it:

public class GpasTableOfContent : IGpasData
{
    public string TocProp0 { get; set; }
    public string TocProp1 { get; set; }
    public string TocProp2 { get; set; }

    public List<T> ConvertToList<T>(StreamReader reader)
    {
        List<T> dataList = new List<T>();
        while (!reader.EndOfStream)
        {
            var lineItem = reader.ReadLine();
            GpasTableOfContent dataItem = new GpasTableOfContent
            {
                TocProp0 = lineItem.Split(',')[0],
                TocProp1 = lineItem.Split(',')[1],
                Type = lineItem.Split(',')[2]
            };
            dataList.Add(dataItem);
        }
        return dataList;
    }
}

To keep going with the example of the class above, there is a file called ToC.csv.  In a class that is designed to convert THAT file into a list, I make this call:

List<GpasTableOfContent> gpasToCList = ConvertCloudFileToList<GpasTableOfContent>("ToC.csv", "MyModel");

Some other possible examples:

List<GpasFoo> gpasFooList = ConvertCloudFileToList<GpasFoo>("foo.csv", "MyModel");

List<GpasBar> gpasBarList = ConvertCloudFileToList<GpasBar>("bar.csv", "MyModel");

Here's ConvertCloudFileToList:

private List<T> ConvertCloudFileToList<T>(string fileName, string modelName)
    {
        // Get the .csv file from the InProgress Directory
        string filePath = $"{modelName}/{fileName}";
        CloudFile cloudFile = _inProgressDir.GetFileReference(filePath);

        List<T> dataList = new List<T>();

        // Does the file exist?
        if (!cloudFile.Exists())
            return dataList;

        using (StreamReader reader = new StreamReader(cloudFile.OpenRead()))
        {
            IGpasData gpasData = (IGpasData)Activator.CreateInstance<T>();
            dataList = gpasData.ConvertToList<T>(reader);
        }

        return dataList;
    }

And that brings us back to ConvertToList.  The problem is here:

dataList.Add(dataItem);

Can not convert 'GpasFoo' to 'T'

Not sure how to work around this.

Body:
As other have pointed out, this design is flawed:

public interface IGpasData
{
   List<T> ConvertToList<T>(StreamReader reader);
}

This contract says that an IGpasData should only know how deserialize anything. It doesn't make sense.

An IGpasData should know how to deserialize itself, and for this we would need a self-referencing interface:

public interface IGpasData<T> where T : IGpasData<T>
{
    List<T> ConvertToList(StreamReader reader);
}

public class GpasBar: IGpasData<GpasBar>
{
    public string MyPropertyA { get; set; }
    public int MyPropertyB { get; set; }

    public List<GpasBar> ConvertToList(StreamReader reader)
    {
        var results = new List<GpasBar>();
        while (!reader.EndOfStream)
        {
            var values = reader.ReadLine().Split(',');
            results.Add(new GpasBar()
            {
                PropertyA = values[0],
                PropertyB = int.Parse(values[1]),
            });
        }
        return results;
    }
}

Or, an IGpasData should know how to populate itself from an array of values:

public interface IGpasData
{
    void Populate(string[] values);
}
public class GpasBar
{
    public string MyPropertyA { get; set; }
    public int MyPropertyB { get; set; }

    public void Populate(string[] values)
    {
        MyPropertyA = values[0];
        MyPropertyB = int.Parse(values[1]);
    }
}

public static List<T> ConvertCloudFileToList<T>(string fileName, string modelName)
    where T : IGpasData, new()
{
    // ...
    using (StreamReader reader = new StreamReader(cloudFile.OpenRead()))
    {
        var results = new List<T>();
        while (!reader.EndOfStream)
        {
            var item = new T();
            item.Populate(reader.ReadLine().Split(','));

            results.Add(item);
        }
        return results;
    }
}

Using this 2nd approach, you can avoid duplicating the part about StreamReader and read lines.


来源: stackexchange

问:
How is it decided that how much physical memory is to be allocated to java heap?
I have machine with 16G RAM. I run a java application with arguments -Xms9G -Xmx9G.
When I run top command I see that my java process is taking 13.8g VIRT, but only 4.6g of RES.

```<code>  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 5019 root      20   0 13.8g 4.7g  18m S  0.7 30.7   3:28.39 java
</code>```

On running pmap command, I see that only ~3.9g of heap is present as RES, rest 5.7g is in virtual.

```<code>Address           Kbytes     RSS   Dirty Mode   Mapping
0000000580000000 9452384 4074228 4074228 rw---    [ anon ]
</code>```

Upon monitoring HPCUR with jvmtop, I observe that the GC is triggered when the HPCUR reaches about 3g.

```<code>PID MAIN-CLASS        HPCUR HPMAX NHCUR NHMAX    CPU     GC    VM USERNAME   #T DL
 5019 .1-SNAPSHOT.jar  408m 9216m  192m   n/a  0.25%  0.00% O8U20   webapp  823
</code>```

I observe that the RES for the process increases gradually, heap memory in RES (by pmap) also increases gradually too. As a result GC threshold increases.

I have several questions about this behavior.

Is only the heap that is present in RES used, and not the VIRT?

If I have allotted 9G min heap (-Xms), then initially why only 3.9g RES is allotted. Isn't this same as keeping -Xms low? What is the point of keeping -Xms=-Xmx then?

On what basis is it decided that how much heap should be in RES? Read somewhere that its managed by OS, but any rough logic?

Any way to make sure, that the allotted heap is actually used?

答:
VIRT denotes Virtual memory - this is the entire reserved address space of the process. RSS is the resident set size - the portion of the virtual address space allocated in physical RAM. For any address range (not only the heap) RSS is the subset of VIRT, possibly complete or empty. Seems like you already explored pmap - for each virtual address range it shows the exact amount of physically allocated memory (RSS).

OS allocates physical pages lazily on the first access. That's why even committed memory is not the part of RSS until the corresponding pages are read or written to. The fact that the large portion of heap is not in RSS means that this part of the heap has never been touched. See also this question.

There is a JVM option -XX:+AlwaysPreTouch that forcibly touches every page of the heap thus making it the part of RSS. Try java -Xms9G -Xmx9G -XX:+AlwaysPreTouch.

ContentLicense: CC BY-SA 4.0

Body:
I have machine with 16G RAM. I run a java application with arguments -Xms9G -Xmx9G.
When I run top command I see that my java process is taking 13.8g VIRT, but only 4.6g of RES.

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 5019 root      20   0 13.8g 4.7g  18m S  0.7 30.7   3:28.39 java

On running pmap command, I see that only ~3.9g of heap is present as RES, rest 5.7g is in virtual.

Address           Kbytes     RSS   Dirty Mode   Mapping
0000000580000000 9452384 4074228 4074228 rw---    [ anon ]

Upon monitoring HPCUR with jvmtop, I observe that the GC is triggered when the HPCUR reaches about 3g.

PID MAIN-CLASS        HPCUR HPMAX NHCUR NHMAX    CPU     GC    VM USERNAME   #T DL
 5019 .1-SNAPSHOT.jar  408m 9216m  192m   n/a  0.25%  0.00% O8U20   webapp  823

I observe that the RES for the process increases gradually, heap memory in RES (by pmap) also increases gradually too. As a result GC threshold increases.

I have several questions about this behavior.

Is only the heap that is present in RES used, and not the VIRT?

If I have allotted 9G min heap (-Xms), then initially why only 3.9g RES is allotted. Isn't this same as keeping -Xms low? What is the point of keeping -Xms=-Xmx then?

On what basis is it decided that how much heap should be in RES? Read somewhere that its managed by OS, but any rough logic?

Any way to make sure, that the allotted heap is actually used?


问:
What html elements are tabbable
I'm trying to find a list of elements that are tabbable.

Adding tab-index to elements make them tabbable.
Some elements are tabbable by default like <input>.
Is there a list of these elements that are tabbable by default?

And optionally, why are they tabbable by deault?

答: https://allyjs.io/data-tables/focusable.html is probably the most comprehensive list I've ever found. Not only does it go over what is "expected" by the spec but also how all major browsers actually behave.</p>

Title: What html elements are tabbable


问:
What type of JavaScript term/definition fits this?
I was reading the MDN documentation on JavaScript classes and came across an example of assigning values that I did not understand. The lines in question were not explained because the page was simply explaining something else (static methods). I am fascinated though with how it worked and what this would be officially called so that I can research it further.

```<code> class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;
    return Math.hypot(dx, dy);
  }
}
</code>```

What I don't understand specifically is the a.x, b.x, a.y and b.y. I wouldn't consider this dot notation because dot notation is defined as "In JavaScript, one can access properties using the dot notation...". So if this is not dot notation, then what term would apply to the value of x and y being assigned to a and b?

Wouldn't the letters a and b in line -

```<code>static distance(a, b)
</code>```

technically be called "parameters" which is clearly defined as something other than a property. And since they are "parameters", then the word "property" would not apply, therefore the official definition of dot notation does not apply.

Definition of parameter: Parameters are variables listed as a part of the function definition

Definition of property:  has a value, which may or may not be writable

Definition of dot notation: In JavaScript, one can access properties using the dot notation...

答:
This question was due to a lack of understanding of how object instantiation works and how this object can be referenced in a static method. The a and b on line

```<code>static distance(a,b)
</code>```

are not typical parameters that simply take a single value as I thought. They are actually receiving a complete instantiated object reference upon said objects creation. Therefore the dot notation of a.x is indeed a 'dot notation' reference to a value that is assigned to a name or property inside of an object. Also what I found confusing was how

b.x and b.y

would have not been created yet upon the first objects instantiation. Apparently a "helper method" such as a static method programatically knows to wait until all the parameters are filled before the method can produce a return result. And it knows this by having all its parameters filled with objects.

Body:
I was reading the MDN documentation on JavaScript classes and came across an example of assigning values that I did not understand. The lines in question were not explained because the page was simply explaining something else (static methods). I am fascinated though with how it worked and what this would be officially called so that I can research it further.

 class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;
    return Math.hypot(dx, dy);
  }
}

What I don't understand specifically is the a.x, b.x, a.y and b.y. I wouldn't consider this dot notation because dot notation is defined as "In JavaScript, one can access properties using the dot notation...". So if this is not dot notation, then what term would apply to the value of x and y being assigned to a and b?

Wouldn't the letters a and b in line -

static distance(a, b)

technically be called "parameters" which is clearly defined as something other than a property. And since they are "parameters", then the word "property" would not apply, therefore the official definition of dot notation does not apply.

Definition of parameter: Parameters are variables listed as a part of the function definition

Definition of property:  has a value, which may or may not be writable

Definition of dot notation: In JavaScript, one can access properties using the dot notation...

Body:
This question was due to a lack of understanding of how object instantiation works and how this object can be referenced in a static method. The a and b on line

static distance(a,b)

are not typical parameters that simply take a single value as I thought. They are actually receiving a complete instantiated object reference upon said objects creation. Therefore the dot notation of a.x is indeed a 'dot notation' reference to a value that is assigned to a name or property inside of an object. Also what I found confusing was how

b.x and b.y

would have not been created yet upon the first objects instantiation. Apparently a "helper method" such as a static method programatically knows to wait until all the parameters are filled before the method can produce a return result. And it knows this by having all its parameters filled with objects.


问:
Message "the term 'ng' is not recognized as the name of a cmdlet"
Today, while working through some basic AngularJS introduction, I ran into a problem.

I opened PowerShell to get going on the project. NPM worked.

I was able to install Angular using:

```<code>npm install -g @angular/cli
</code>```

Anytime I tried to run ng, I would get:

the term 'ng' is not recognized as the name of a cmdlet

答:
This PowerShell script worked to add the correct setting to my environment variable "Path" (as a per-user setting). It adds: %AppData%\npm—and then restart the command line that uses "ng".

$existingPath = [System.Environment]::GetEnvironmentVariable("Path", "User")
Write-Host "existing PATH variable is $existingPath"
$newPath = "%AppData%\npm;$existingPath"
Write-Host "new      PATH will be     $newPath"

# Update here
[System.Environment]::SetEnvironmentVariable("Path", $newPath, "User")

$finalPath = [System.Environment]::GetEnvironmentVariable("Path", "User")
Write-Host "final    PATH variable is $finalPath"
```

Body:
Today, while working through some basic AngularJS introduction, I ran into a problem.

I opened PowerShell to get going on the project. NPM worked.

I was able to install Angular using:

npm install -g @angular/cli

Anytime I tried to run ng, I would get:

the term 'ng' is not recognized as the name of a cmdlet


问:
Trying to instantiate a class androidx.navigation.fragment.NavHostFragment that is not a Fragment
as in the title:

Trying to instantiate a class androidx.navigation.fragment.NavHostFragment that is not a Fragment

I've got a two activities. Both have following code with different ids and reference to different navigation graphs

```<code><fragment
        android:id="@+id/splash_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation_splash"/>
</code>```

When i comment above code application runs ok. In First activity i can navigate to second activity and app works just fine. When i uncomment above code - app crashes

Any help?

答:
I was extending Activity but i should AppCompatActivity.

Now everything works fine.

Body:
as in the title:

Trying to instantiate a class androidx.navigation.fragment.NavHostFragment that is not a Fragment

I've got a two activities. Both have following code with different ids and reference to different navigation graphs

<fragment
        android:id="@+id/splash_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation_splash"/>

When i comment above code application runs ok. In First activity i can navigate to second activity and app works just fine. When i uncomment above code - app crashes

Any help?


问:
What is the downside of TableAdapterManager?
I using tableAdapterManager for updating my data. But when i want save with this function the window is freezing. What do you about this problem?</p>

答: You can use a BackgroundWorker to avoid your "window is freezing". Useful if you have lots of data to load.</p>

ContentLicense: CC BY-SA 3.0


问:
Kotlin: data class private setter public getter
Is there any way I can make a private setter and a public getter in a Kotlin Data Class?</p>

```<code>data class Test(var attribute: String) {

    // attribute can be mutated inside this class

    // but outside only readable ?
}
</code>```

答:
A simple approach would be to have a private var, but then to provide a public property that delegates to it:</p>

```<code>data class Test (private var attribute_ : String) {
  val attribute: String get() = attribute_
}
</code>```

Body:
Is there any way I can make a private setter and a public getter in a Kotlin Data Class?

data class Test(var attribute: String) {

    // attribute can be mutated inside this class

    // but outside only readable ?
}

Body:
A simple approach would be to have a private var, but then to provide a public property that delegates to it:

data class Test (private var attribute_ : String) {
  val attribute: String get() = attribute_
}


问:
How to make coq simplify expressions inside an implication hypothesis
Im trying to prove the following lemma:

```<code>Inductive even : nat → Prop :=
| ev_0 : even 0
| ev_SS (n : nat) (H : even n) : even (S (S n)).

Lemma even_Sn_not_even_n : forall n,
    even (S n) <-> not (even n).
Proof.
  intros n. split.
  + intros H. unfold not. intros H1. induction H1 as [|n' E' IHn].
    - inversion H.
    - inversion_clear H. apply IHn in H0. apply H0.
  + unfold not. intros H. induction n as [|n' E' IHn].
    -
Qed.
</code>```

Here is what I got at the end:

```<code>1 subgoal (ID 173)

H : even 0 -> False
============================
even 1
</code>```

I want coq to evaluate "even 0" to true and "even 1" to false. I tried simpl, apply ev_0 in H. but they give an error. What to do?

答:
Answer to the title

```<code>simpl in H.
</code>```

Real answer

The above code will not work.

The definition of even from the Logical Foundations book is:

```<code>Inductive even : nat → Prop :=
| ev_0 : even 0
| ev_SS (n : nat) (H : even n) : even (S (S n)).
</code>```

even 0 is a Prop, not a bool. Looks like you're mixing up the types True and False and the booleans true and false. They're totally different things, and not interchangeable under Coq's logic. In short, even 0 does not simplify to true or True or anything. It is just even 0. If you want to show even 0 is logically true, you should construct a value of that type.

I don't remember which tactics are available at that point in LF, but here are some possibilities:

```<code>(* Since you know `ev_0` is a value of type `even 0`,
   construct `False` from H and destruct it.
   This is an example of forward proof. *)
set (contra := H ev_0). destruct contra.

(* ... or, in one step: *)
destruct (H ev_0).

(* We all know `even 1` is logically false,
   so change the goal to `False` and work from there.
   This is an example of backward proof. *)
exfalso. apply H. apply ev_0.
</code>```

Body:
Im trying to prove the following lemma:

Inductive even : nat → Prop :=
| ev_0 : even 0
| ev_SS (n : nat) (H : even n) : even (S (S n)).

Lemma even_Sn_not_even_n : forall n,
    even (S n) <-> not (even n).
Proof.
  intros n. split.
  + intros H. unfold not. intros H1. induction H1 as [|n' E' IHn].
    - inversion H.
    - inversion_clear H. apply IHn in H0. apply H0.
  + unfold not. intros H. induction n as [|n' E' IHn].
    -
Qed.

Here is what I got at the end:

1 subgoal (ID 173)

H : even 0 -> False
============================
even 1

I want coq to evaluate "even 0" to true and "even 1" to false. I tried simpl, apply ev_0 in H. but they give an error. What to do?

Body:
Answer to the title

simpl in H.

Real answer

The above code will not work.

The definition of even from the Logical Foundations book is:

Inductive even : nat → Prop :=
| ev_0 : even 0
| ev_SS (n : nat) (H : even n) : even (S (S n)).

even 0 is a Prop, not a bool. Looks like you're mixing up the types True and False and the booleans true and false. They're totally different things, and not interchangeable under Coq's logic. In short, even 0 does not simplify to true or True or anything. It is just even 0. If you want to show even 0 is logically true, you should construct a value of that type.

I don't remember which tactics are available at that point in LF, but here are some possibilities:

(* Since you know `ev_0` is a value of type `even 0`,
   construct `False` from H and destruct it.
   This is an example of forward proof. *)
set (contra := H ev_0). destruct contra.

(* ... or, in one step: *)
destruct (H ev_0).

(* We all know `even 1` is logically false,
   so change the goal to `False` and work from there.
   This is an example of backward proof. *)
exfalso. apply H. apply ev_0.


问:
How to get the last index of a comboBox when size isn't constant?
In an input form, I have two drop down boxes. The option selected in the first one determines what options will populate the second one. There will always be a 'Default' option in the last index of the drop down, but the number of items will change, so 'Default' is not always at a constant index. For the other options, I can just use it's index for other stuff without knowing what it was, but if default is selected I need to do a special action.

My current solution is a bit bulky because I have to check for the index I know will be the default for each case.

```<code>switch( comboBoxOne.SelectedIndex )
{
    case 0:
        if( comboBoxTwo.SelectedIndex == 6 )
            //special action
        break;
    case 1:
    case 2:
        if( comboBoxTwo.SelectedIndex== 4 )
            //special action
        break;
    case 3:
    case 4:
        if( comboBoxTwo.SelectedIndex== 5 )
            //special action
        break;
}
</code>```

I can't use comboBoxTwo.MaxDropDownHeight because that's just a limit for how many items you can potentially have.

NOTE**
I can't set 'Default' to index 0 because it causes the other indices to be wrong, so I'd have to do more work mapping them to the correct index. Also, the way the second options are populated is complicated (there's actually 50 different cases) so default is always appended to the last index. How can I get the last valid item index from a comboBox?

答:
A ComboBox control has an Items collection, which has a Count property. So the last item would be at the index one less than the count (since indexes are zero-based):

```<code>// Select the last item in the combobox
comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
</code>```

Body:
In an input form, I have two drop down boxes. The option selected in the first one determines what options will populate the second one. There will always be a 'Default' option in the last index of the drop down, but the number of items will change, so 'Default' is not always at a constant index. For the other options, I can just use it's index for other stuff without knowing what it was, but if default is selected I need to do a special action.

My current solution is a bit bulky because I have to check for the index I know will be the default for each case.

switch( comboBoxOne.SelectedIndex )
{
    case 0:
        if( comboBoxTwo.SelectedIndex == 6 )
            //special action
        break;
    case 1:
    case 2:
        if( comboBoxTwo.SelectedIndex== 4 )
            //special action
        break;
    case 3:
    case 4:
        if( comboBoxTwo.SelectedIndex== 5 )
            //special action
        break;
}

I can't use comboBoxTwo.MaxDropDownHeight because that's just a limit for how many items you can potentially have.

NOTE**
I can't set 'Default' to index 0 because it causes the other indices to be wrong, so I'd have to do more work mapping them to the correct index. Also, the way the second options are populated is complicated (there's actually 50 different cases) so default is always appended to the last index. How can I get the last valid item index from a comboBox?

Body:
A ComboBox control has an Items collection, which has a Count property. So the last item would be at the index one less than the count (since indexes are zero-based):

// Select the last item in the combobox
comboBox1.SelectedIndex = comboBox1.Items.Count - 1;


问:
Check three radio buttons automatically on load
I have three radio button lists, and I would like the first option of each to be selected when the page loads. The options are populated based on MySQL retrieval queries.

Currently, only the first element of the first radio button list is checked. I am struggling to get the first element of the other two lists to be checked on load.

```<code><ul id="radio" class="input-list">
    <?php
        $stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
        $stmt->execute();
        $stmt->bind_result($case_id, $case_name, $case_price);
        while($stmt->fetch())
        {
            echo
            '<li>
                <input id="'.$case_id.'" name="config-prod" value="'.$case_id.'" type="radio">
                <label class="sub-label" for="'.$case_id.'">'.$case_name.'    [£'.$case_price.']</label>
            </li>';
        }
        $stmt->close();
        ?>
        </ul>

        <ul id="radio" class="input-warranty">
            <?php
                $stmt18 = mysqli_prepare($link, "SELECT id, name, price FROM warranty ORDER BY price");
                $stmt18->execute();
                $stmt18->bind_result($warranty_id, $warranty_name, $warranty_price);
                while($stmt18->fetch())
                {
                    echo
                    '<li>
                        <input id="'.$warranty_id.'" name="config-warranty" value="'.$warranty_id.'" type="radio">
                        <label class="sub-label" for="'.$warranty_id.'">'.$warranty_name.'    [£'.$warranty_price.']</label>
                    </li>';
                }
                $stmt18->close();
            ?>
        </ul>

        <ul id="radio" class="input-build">
        <?php
            $stmt19 = mysqli_prepare($link, "SELECT id, name, price FROM buildtime ORDER BY price");
            $stmt19->execute();
            $stmt19->bind_result($buildtime_id, $buildtime_name, $buildtime_price);
            while($stmt19->fetch())
            {
                echo
                '<li>
                    <input id="'.$buildtime_id.'" name="config-build" value="'.$buildtime_id.'" type="radio">
                    <label class="sub-label" for="'.$buildtime_id.'">'.$buildtime_name.'    [£'.$buildtime_price.']</label>
                </li>';
            }
        $stmt19->close();
    ?>
</ul>
</code>```

I have used javascript to get the first option of the first radio button list to be checked on load:

```<code><script>
        document.querySelector("#radio li input").checked = true;
</script>
</code>```

How can I make the first element of the second and third lists to be selected on load? Thank you.

答:
In continuation with RobG's comment:

```<code>...
$isFirst = true;
while($stmt->fetch()) {
  echo '<li>
    <input id="'.$case_id.'" name="config-prod" value="'.$case_id.'" type="radio"'.$isFirst?' checked':''.'>
    <label class="sub-label" for="'.$case_id.'">'.$case_name.'         [£'.$case_price.']</label>
  </li>';
  $isFirst = false;
}
...

$isFirst = true;
while($stmt18->fetch()) {
  echo '<li>
    <input id="'.$warranty_id.'" name="config-warranty" value="'.$warranty_id.'" type="radio"'.$isFirst?' checked':''.'>
    <label class="sub-label" for="'.$warranty_id.'">'.$warranty_name.'         [£'.$warranty_price.']</label>
  </li>';
  $isFirst = false;
}
...
</code>```

BTW, on side note, it would be better to write a function to generate a checkbox and reuse that function for different loops ;). For example, the below code is more readable.

```<code>function echoCheckbox($property, $id, $name, $price, $checked){
  echo '<li>
    <input id="'.$id.'" name="'.$property.'" value="'.$id.'" type="radio"'.$checked?' checked':''.'>
    <label class="sub-label" for="'.$id.'">'.$name.'[£'.$price.']</label>
  </li>';
}
...
$isFirst = true;
while($stmt->fetch()) {
  echoCheckbox("config-prod", $case_id, $case_name, $case_price, $isFirst);
  $isFirst = false;
}
...

$isFirst = true;
while($stmt18->fetch()) {
  echoCheckbox("config-warranty", $warranty_id, $warranty_name, $warranty_price, $isFirst);
  $isFirst = false;
}
...
</code>```

Body:
I have three radio button lists, and I would like the first option of each to be selected when the page loads. The options are populated based on MySQL retrieval queries.

Currently, only the first element of the first radio button list is checked. I am struggling to get the first element of the other two lists to be checked on load.

    <?php
        $stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
        $stmt->execute();
        $stmt->bind_result($case_id, $case_name, $case_price);
        while($stmt->fetch())
        {
            echo
            '

                <input id="'.$case_id.'" name="config-prod" value="'.$case_id.'" type="radio">
                '.$case_name.'    [£'.$case_price.']

';
        }
        $stmt->close();
        ?>

            <?php
                $stmt18 = mysqli_prepare($link, "SELECT id, name, price FROM warranty ORDER BY price");
                $stmt18->execute();
                $stmt18->bind_result($warranty_id, $warranty_name, $warranty_price);
                while($stmt18->fetch())
                {
                    echo
                    '

                        <input id="'.$warranty_id.'" name="config-warranty" value="'.$warranty_id.'" type="radio">
                        '.$warranty_name.'    [£'.$warranty_price.']

';
                }
                $stmt18->close();
            ?>

        <?php
            $stmt19 = mysqli_prepare($link, "SELECT id, name, price FROM buildtime ORDER BY price");
            $stmt19->execute();
            $stmt19->bind_result($buildtime_id, $buildtime_name, $buildtime_price);
            while($stmt19->fetch())
            {
                echo
                '

                    <input id="'.$buildtime_id.'" name="config-build" value="'.$buildtime_id.'" type="radio">
                    '.$buildtime_name.'    [£'.$buildtime_price.']

';
            }
        $stmt19->close();
    ?>

I have used javascript to get the first option of the first radio button list to be checked on load:

How can I make the first element of the second and third lists to be selected on load? Thank you.

Body:
In continuation with RobG's comment:

...
$isFirst = true;
while($stmt->fetch()) {
  echo '<li>
    <input id="'.$case_id.'" name="config-prod" value="'.$case_id.'" type="radio"'.$isFirst?' checked':''.'>
    <label class="sub-label" for="'.$case_id.'">'.$case_name.'         [£'.$case_price.']</label>
  </li>';
  $isFirst = false;
}
...

$isFirst = true;
while($stmt18->fetch()) {
  echo '<li>
    <input id="'.$warranty_id.'" name="config-warranty" value="'.$warranty_id.'" type="radio"'.$isFirst?' checked':''.'>
    <label class="sub-label" for="'.$warranty_id.'">'.$warranty_name.'         [£'.$warranty_price.']</label>
  </li>';
  $isFirst = false;
}
...

BTW, on side note, it would be better to write a function to generate a checkbox and reuse that function for different loops ;). For example, the below code is more readable.

function echoCheckbox($property, $id, $name, $price, $checked){
  echo '<li>
    <input id="'.$id.'" name="'.$property.'" value="'.$id.'" type="radio"'.$checked?' checked':''.'>
    <label class="sub-label" for="'.$id.'">'.$name.'[£'.$price.']</label>
  </li>';
}
...
$isFirst = true;
while($stmt->fetch()) {
  echoCheckbox("config-prod", $case_id, $case_name, $case_price, $isFirst);
  $isFirst = false;
}
...

$isFirst = true;
while($stmt18->fetch()) {
  echoCheckbox("config-warranty", $warranty_id, $warranty_name, $warranty_price, $isFirst);
  $isFirst = false;
}
...


问:
cx_Oracle fail to connect to one database using different machine
I am trying to connect to ORACLE database using cx_Oracle with python.
Code shown below. Same code able to connect to target database while running on a pc, however not able to connect using a server.
Error message: ORA-12545: Connect failed because target host or object does not exist

Since it can be connected use other pc, I think should not be the password or service name wrong.
The server having issue connecting to the database is a linux, with cx_Oracle installed, and ORACLE_HOME, LD_LIBRARY_PATH defined.

Any one can give a hint on what might goes wrong?

code used

```<code>dsn_tns = cx_Oracle.makedsn('Host Name', 'Port Number', service_name='ServiceName')
conn = cx_Oracle.connect(user=r'UserName', password='Password', dsn=dsn_tns)
c = conn.cursor()
</code>```

答: Found out it was due to network access issue. </p>

Body:
I am trying to connect to ORACLE database using cx_Oracle with python.
Code shown below. Same code able to connect to target database while running on a pc, however not able to connect using a server.
Error message: ORA-12545: Connect failed because target host or object does not exist

Since it can be connected use other pc, I think should not be the password or service name wrong.
The server having issue connecting to the database is a linux, with cx_Oracle installed, and ORACLE_HOME, LD_LIBRARY_PATH defined.

Any one can give a hint on what might goes wrong?

code used

dsn_tns = cx_Oracle.makedsn('Host Name', 'Port Number', service_name='ServiceName')
conn = cx_Oracle.connect(user=r'UserName', password='Password', dsn=dsn_tns)
c = conn.cursor()


问:
Unable to insert products into ms access db
Im receiving a number of different errors when trying to insert products into my access DB. Such as Malformed String: ). User lacks privilege or object cant be found. Different errors when i try and insert different products.

tried re creating the db, debugging to the hilt.

public boolean addNewProduct(Product product)
    {

```<code>    String Make = "";
    String Model = "";
    String Type = "";
    String Genre = "";
    String AttConsole = "";
    String Desc = "";

    if(product.getClass().getName().equals("Models.Game"))
    {
         Game game = (Game)product;
         Genre = String.valueOf(game.getGenre());
         AttConsole = String.valueOf(game.getAttributedConsole());
         Desc = String.valueOf(game.getDescription());
    }
    else if(product.getClass().getName().equals("Models.Console"))
    {
         Console console = (Console)product;
         Make = String.valueOf(console.getMake());
         Model = String.valueOf(console.getModel());
         Desc = String.valueOf(console.getDescription());
    }
    else
    {
        Peripheral peripheral = (Peripheral)product;
        Type = String.valueOf(peripheral.getType());
        Desc = String.valueOf(peripheral.getDescription());
    }

     try
    {
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(connectionString);
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT INTO Products (ProductName, Price, StockLevel, Description, Genre, AttributedConsole, Make, Model, Type) VALUES "
                + "('" + product.getProductName() + "','" + product.getPrice() + "','" + product.getStocklevel()
                + "','" +  Desc + "','" + Genre + "','" + AttConsole +
                "','"  + Make + "','" + Model + "'," + Type + ")");
        //sql statement to add new products to database
        conn.close();
        return true;
    }

     catch(Exception ex)
     {
          String message = ex.getMessage();
          return false;
     }

}
</code>```

ex = (net.ucanaccess.jdbc.UcanaccessSQLException) net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 unexpected token: )
ex = (net.ucanaccess.jdbc.UcanaccessSQLException) net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 user lacks privilege or object not found: RAZOR

答:
Don't use string concatenation to insert column values into SQL command text. Search for "SQL Injection" or "Little Bobby Tables" for more information on why that is a "Bad Thing"™.

Instead, use a PreparedStatement to run a parameterized query, e.g.,

String sql = "INSERT INTO tableName (intColumn, textColumn) VALUES (?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setInt(1, 12345);
    ps.setString(2, "my text value");
    ps.executeUpdate();
}
```

Body:
Im receiving a number of different errors when trying to insert products into my access DB. Such as Malformed String: ). User lacks privilege or object cant be found. Different errors when i try and insert different products.

tried re creating the db, debugging to the hilt.

public boolean addNewProduct(Product product)
    {

    String Make = "";
    String Model = "";
    String Type = "";
    String Genre = "";
    String AttConsole = "";
    String Desc = "";

    if(product.getClass().getName().equals("Models.Game"))
    {
         Game game = (Game)product;
         Genre = String.valueOf(game.getGenre());
         AttConsole = String.valueOf(game.getAttributedConsole());
         Desc = String.valueOf(game.getDescription());
    }
    else if(product.getClass().getName().equals("Models.Console"))
    {
         Console console = (Console)product;
         Make = String.valueOf(console.getMake());
         Model = String.valueOf(console.getModel());
         Desc = String.valueOf(console.getDescription());
    }
    else
    {
        Peripheral peripheral = (Peripheral)product;
        Type = String.valueOf(peripheral.getType());
        Desc = String.valueOf(peripheral.getDescription());
    }

     try
    {
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(connectionString);
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT INTO Products (ProductName, Price, StockLevel, Description, Genre, AttributedConsole, Make, Model, Type) VALUES "
                + "('" + product.getProductName() + "','" + product.getPrice() + "','" + product.getStocklevel()
                + "','" +  Desc + "','" + Genre + "','" + AttConsole +
                "','"  + Make + "','" + Model + "'," + Type + ")");
        //sql statement to add new products to database
        conn.close();
        return true;
    }

     catch(Exception ex)
     {
          String message = ex.getMessage();
          return false;
     }

}

ex = (net.ucanaccess.jdbc.UcanaccessSQLException) net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 unexpected token: )
ex = (net.ucanaccess.jdbc.UcanaccessSQLException) net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 user lacks privilege or object not found: RAZOR


问:
How to get the type of each union case for a given union type in F#
I am wondering in the F# code below how to fetch the type associated with each union case via reflection

type AccountCreatedArgs = {
    Owner: string
    AccountId: Guid
    CreatedAt: DateTimeOffset
    StartingBalance: decimal
}

type Transaction = {
    To: Guid
    From: Guid
    Description: string
    Time: DateTimeOffset
    Amount: decimal
}

type AccountEvents =
    | AccountCreated of AccountCreatedArgs
    | AccountCredited of Transaction
    | AccountDebited of Transaction

```

<p>I tried using <code>FSharpType.GetUnionCases(typeof<AccountEvents>)</code> but <code>UnionCaseInfo</code> does not provide any information about the case type (only the declaring type aka <code>AccountEvents</code> so not really useful in my case) =/</p>

<hr>

<p>The answer of glennsl really helped me https://stackoverflow.com/a/56351231/4636721</p>

<p>What I really found handy in my case was:</p>

<pre class="lang-ml prettyprint-override"><code>let getUnionCasesTypes<'T> =
    Reflection.FSharpType.GetUnionCases(typeof<'T>)
    |> Seq.map (fun x -> x.GetFields().[0].DeclaringType)
</code>```

答:
UnionCaseInfo has a GetFields method which returns an array of PropertyInfos which describe each field/argument of the union case. For example:

```<code>FSharpType.GetUnionCases(typeof<AccountEvents>)
    |> Array.map(fun c -> (c.Name, c.GetFields()))
    |> printfn "%A"
</code>```

will print

```<code>[|("AccountCreated", [|AccountCreatedArgs Item|]);
  ("AccountCredited", [|Transaction Item|]);
  ("AccountDebited", [|Transaction Item|])|]
</code>```

The name assigned to a single field union case is "Item", and if multiple is "Item1", "Item2" etc. The field type itself can be retrieved from the PropertyType property of PropertyInfo, so:

```<code>FSharpType.GetUnionCases(typeof<AccountEvents>)
    |> Array.map(fun c -> (c.Name, c.GetFields() |> Array.map(fun p -> p.PropertyType.Name)))
    |> printfn "%A"
</code>```

will thus print

```<code>[|("AccountCreated", [|"AccountCreatedArgs"|]);
  ("AccountCredited", [|"Transaction"|]);
  ("AccountDebited", [|"Transaction"|])|]
</code>```

Body:
I am wondering in the F# code below how to fetch the type associated with each union case via reflection

type AccountCreatedArgs = {
    Owner: string
    AccountId: Guid
    CreatedAt: DateTimeOffset
    StartingBalance: decimal
}

type Transaction = {
    To: Guid
    From: Guid
    Description: string
    Time: DateTimeOffset
    Amount: decimal
}

type AccountEvents =
    | AccountCreated of AccountCreatedArgs
    | AccountCredited of Transaction
    | AccountDebited of Transaction

I tried using FSharpType.GetUnionCases(typeof<AccountEvents>) but UnionCaseInfo does not provide any information about the case type (only the declaring type aka AccountEvents so not really useful in my case) =/

The answer of glennsl really helped me https://stackoverflow.com/a/56351231/4636721

What I really found handy in my case was:

let getUnionCasesTypes<'T> =
    Reflection.FSharpType.GetUnionCases(typeof<'T>)
    |> Seq.map (fun x -> x.GetFields().[0].DeclaringType)

Body:
UnionCaseInfo has a GetFields method which returns an array of PropertyInfos which describe each field/argument of the union case. For example:

FSharpType.GetUnionCases(typeof<AccountEvents>)
    |> Array.map(fun c -> (c.Name, c.GetFields()))
    |> printfn "%A"

will print

[|("AccountCreated", [|AccountCreatedArgs Item|]);
  ("AccountCredited", [|Transaction Item|]);
  ("AccountDebited", [|Transaction Item|])|]

The name assigned to a single field union case is "Item", and if multiple is "Item1", "Item2" etc. The field type itself can be retrieved from the PropertyType property of PropertyInfo, so:

FSharpType.GetUnionCases(typeof<AccountEvents>)
    |> Array.map(fun c -> (c.Name, c.GetFields() |> Array.map(fun p -> p.PropertyType.Name)))
    |> printfn "%A"

will thus print

[|("AccountCreated", [|"AccountCreatedArgs"|]);
  ("AccountCredited", [|"Transaction"|]);
  ("AccountDebited", [|"Transaction"|])|]


问:
Open Google sheet with script
I would like to open each file in a folder via script.  Below is what I have tried.  This is my first shot at any script in sheets.

This code runs but does not open file, I could be a mile off on this but I can't figure out how to make it open the files.  Thanks for your help

```<code>function myFunction() {
  var dApp = DriveApp;
  var folder = dApp.getFoldersByName("test").next();
  var filesIter = folder.getFiles();

  while(filesIter.hasNext()) {
    var files = filesIter.next();
    var ss = SpreadsheetApp.open(files);
  }
}
</code>```

I simply want it to open all the files in a folder in this case "test".  there are currently two google sheets in the folder.

答:
You can read open files from Scripts but not in the way that users can open files.  You can open them on the server and read and/or write data but the file doesn't open  up in edit mode like it does when you open it as a user.

Here's a script that opens up spreadsheets and reads their name and id and returns it to a webapp.

HTML:

```<code><html>
<head><title></title>
</head>
<body>

<div id="data"></div>

<script>
  window.onload=function(){
    google.script.run
    .withSuccessHandler(function(ssA){
      var html='';
      for(var i=0;i<ssA.length;i++) {
        html+='<br />' + 'Name: ' + ssA[i].name + ' Id: ' + ssA[i].id;
      }
      document.getElementById('data').innerHTML=html;

    })
    .readSpreadsheetsInAFolder();
  }
  </script>
  </body>
  </html>
</code>```

CODE.gs:

```<code>function readSpreadsheetsInAFolder() {
  var ssA=[];
  var folders=DriveApp.getFoldersByName("LinkedSpreadsheets");
  while(folders.hasNext()){
    var folder=folders.next();
    var files=folder.getFilesByType(MimeType.GOOGLE_SHEETS);
    while(files.hasNext()) {
      var file=files.next();
      var ss=SpreadsheetApp.openById(file.getId());
      ssA.push({name:file.getName(),id:file.getId()});
    }
  }
  return ssA;
}
</code>```

This function was written for my account so you may have to modify the Folder Name to get  it to work on your account.

Title: Open Google sheet with script

Body:
I would like to open each file in a folder via script.  Below is what I have tried.  This is my first shot at any script in sheets.

This code runs but does not open file, I could be a mile off on this but I can't figure out how to make it open the files.  Thanks for your help

function myFunction() {
  var dApp = DriveApp;
  var folder = dApp.getFoldersByName("test").next();
  var filesIter = folder.getFiles();

  while(filesIter.hasNext()) {
    var files = filesIter.next();
    var ss = SpreadsheetApp.open(files);
  }
}

I simply want it to open all the files in a folder in this case "test".  there are currently two google sheets in the folder.

Body:
You can read open files from Scripts but not in the way that users can open files.  You can open them on the server and read and/or write data but the file doesn't open  up in edit mode like it does when you open it as a user.

Here's a script that opens up spreadsheets and reads their name and id and returns it to a webapp.

HTML:

<html>
<head><title></title>
</head>
<body>

<div id="data"></div>

<script>
  window.onload=function(){
    google.script.run
    .withSuccessHandler(function(ssA){
      var html='';
      for(var i=0;i<ssA.length;i++) {
        html+='<br />' + 'Name: ' + ssA[i].name + ' Id: ' + ssA[i].id;
      }
      document.getElementById('data').innerHTML=html;

    })
    .readSpreadsheetsInAFolder();
  }
  </script>
  </body>
  </html>

CODE.gs:

function readSpreadsheetsInAFolder() {
  var ssA=[];
  var folders=DriveApp.getFoldersByName("LinkedSpreadsheets");
  while(folders.hasNext()){
    var folder=folders.next();
    var files=folder.getFilesByType(MimeType.GOOGLE_SHEETS);
    while(files.hasNext()) {
      var file=files.next();
      var ss=SpreadsheetApp.openById(file.getId());
      ssA.push({name:file.getName(),id:file.getId()});
    }
  }
  return ssA;
}

This function was written for my account so you may have to modify the Folder Name to get  it to work on your account.


问:
Quartile sorter with externally specified quartile breakpoints in R data.table
I want to sort observations into quartiles on the variable "varbl". Since my data is pretty big (2Gb), I am trying to implement it via data.table. The problem is that I need to use external quartile breaks, which are group-specific. The group variable is "prd" or "prd1".

My data and breakpoints are as follows:

```<code>data <- data.table(id = c(1,2,3,4,5,1,2,3,4,5), prd1 = c(1,1,1,1,1,2,2,2,2,2), varbl = c(-1.6, -0.7, 0.1, 1.2, -0.5, -0.8, 0.4, 1.2, 1.9, 4))
bks <- data.table(prd=c(1,2), br0 = c(-5,-5), br1=c(-1,0), br2=c(0, 0.5), br3=c(1, 3), br4=c(5,5))
</code>```

```<code> > data
    id prd1 varbl
 1:  1    1  -1.6
 2:  2    1  -0.7
 3:  3    1   0.1
 4:  4    1   1.2
 5:  5    1  -0.5
 6:  1    2  -0.8
 7:  2    2   0.4
 8:  3    2   1.2
 9:  4    2   1.9
10:  5    2   4.0
> bks
   prd br0 br1 br2 br3 br4
1:   1  -5  -1 0.0   1   5
2:   2  -5   0 0.5   3   5
</code>```

The desired output is:

```<code>> output
    id prd1 varbl ntile
 1:  1    1  -1.6     1
 2:  2    1  -0.7     2
 3:  3    1   0.1     3
 4:  4    1   1.2     4
 5:  5    1  -0.5     2
 6:  1    2  -0.8     1
 7:  2    2   0.4     2
 8:  3    2   1.2     3
 9:  4    2   1.9     3
10:  5    2   4.0     4
</code>```

I tried the following code, but it fails, since I can not subset bks on the same prd as the current prd1 from data:

```<code>data[, ntile := cut(varbl, breaks = bks[prd==prd1], include.lowest=TRUE, labels = 1:4)]
</code>```

As another attempt, I tried to join data and bks first (I would prefer not to as it will increase the size of data from 2Gb to 4Gb)
and then sort observations into quantiles. It fails, since I can not understand how to use column names to construct a vector of breakpoints for every row. None of the attempts worked.

```<code>setnames(data, "prd1", "prd")
data <- data[bks, on="prd", nomatch=0]
data[, ntile := cut(varbl, breaks = .(br0, br1, br2, br3, br4), include.lowest=TRUE, labels=1:4)]
data[, ntile := cut(varbl, breaks = colnames(bks)[-1], include.lowest=TRUE, labels=1:4)]
data[, ntile := cut(varbl, breaks = c("br0", "br1", "br2", "br3", "br4"), include.lowest=TRUE, labels=1:4)]
</code>```

Body:
I want to sort observations into quartiles on the variable "varbl". Since my data is pretty big (2Gb), I am trying to implement it via data.table. The problem is that I need to use external quartile breaks, which are group-specific. The group variable is "prd" or "prd1".

My data and breakpoints are as follows:

data <- data.table(id = c(1,2,3,4,5,1,2,3,4,5), prd1 = c(1,1,1,1,1,2,2,2,2,2), varbl = c(-1.6, -0.7, 0.1, 1.2, -0.5, -0.8, 0.4, 1.2, 1.9, 4))
bks <- data.table(prd=c(1,2), br0 = c(-5,-5), br1=c(-1,0), br2=c(0, 0.5), br3=c(1, 3), br4=c(5,5))

 > data
    id prd1 varbl
 1:  1    1  -1.6
 2:  2    1  -0.7
 3:  3    1   0.1
 4:  4    1   1.2
 5:  5    1  -0.5
 6:  1    2  -0.8
 7:  2    2   0.4
 8:  3    2   1.2
 9:  4    2   1.9
10:  5    2   4.0
> bks
   prd br0 br1 br2 br3 br4
1:   1  -5  -1 0.0   1   5
2:   2  -5   0 0.5   3   5

The desired output is:

> output
    id prd1 varbl ntile
 1:  1    1  -1.6     1
 2:  2    1  -0.7     2
 3:  3    1   0.1     3
 4:  4    1   1.2     4
 5:  5    1  -0.5     2
 6:  1    2  -0.8     1
 7:  2    2   0.4     2
 8:  3    2   1.2     3
 9:  4    2   1.9     3
10:  5    2   4.0     4

I tried the following code, but it fails, since I can not subset bks on the same prd as the current prd1 from data:

data[, ntile := cut(varbl, breaks = bks[prd==prd1], include.lowest=TRUE, labels = 1:4)]

As another attempt, I tried to join data and bks first (I would prefer not to as it will increase the size of data from 2Gb to 4Gb)
and then sort observations into quantiles. It fails, since I can not understand how to use column names to construct a vector of breakpoints for every row. None of the attempts worked.

setnames(data, "prd1", "prd")
data <- data[bks, on="prd", nomatch=0]
data[, ntile := cut(varbl, breaks = .(br0, br1, br2, br3, br4), include.lowest=TRUE, labels=1:4)]
data[, ntile := cut(varbl, breaks = colnames(bks)[-1], include.lowest=TRUE, labels=1:4)]
data[, ntile := cut(varbl, breaks = c("br0", "br1", "br2", "br3", "br4"), include.lowest=TRUE, labels=1:4)]

Body:
Rearranging bks a little means you can do this as a join:

bks <- bks[, data.frame(embed(unlist(.SD),2)[,2:1]), by=prd]
bks[, grp := seq_len(.N), by=prd]

#   prd   X1   X2 grp
#1:   1 -5.0 -1.0   1
#2:   1 -1.0  0.0   2
#3:   1  0.0  1.0   3
#4:   1  1.0  5.0   4
#5:   2 -5.0  0.0   1
#6:   2  0.0  0.5   2
#7:   2  0.5  3.0   3
#8:   2  3.0  5.0   4

data[bks, on=c("prd1"="prd","varbl>=X1","varbl<X2"), grp := i.grp]

#    id prd1 varbl  grp
# 1:  1    1  -1.6    1
# 2:  2    1  -0.7    2
# 3:  3    1   0.1    3
# 4:  4    1   1.2    4
# 5:  5    1  -0.5    2
# 6:  1    2  -0.8    1
# 7:  2    2   0.4    2
# 8:  3    2   1.2    3
# 9:  4    2   1.9    3
#10:  5    2   4.0    4


问:
How to load a local JavaScript file only within certain components
I have a JavaScript file that I want to include only in one component once mounted. For example, this JavaScript file (called dashboard.js) should only run when the Dashboard.vue component is active and mounted.

I have tried sticking the code in mounted(), but this won't work because the code relies on this being the window, not the Vue instance. I have also tried appending the script to the document.head in the mounted function, but this seems like a big hack and I know there has to be a better way to do this.

```<code>//Dashboard.vue
<template>
<div>
Dashboard content here
</div>
</template>
<script>
export default {
    mounted() {
      //code that relies on this being the window object here (jQuery stuff)
    }
}
</script>

//dashboard.js
$(function() {
  $div = $('div');
  $div.on('click', function() {
    //do stuff
  });
});
</code>```

I would like for this dashboard.js local script to only be loaded and called when my component gets mounted.

答:
you can import that script in the component:

```<code>// Dashboard.vue
import * as dashboard from "./dashboard";
</code>```

and then import jQuery inside dashboard.js

```<code>// dashboard.js
import jQuery from "jquery";
window.$ = window.jQuery = jQuery;

$(function() {
  var $div = $("div");
  $div.on("click", function() {
    //do stuff
    alert();
  });
});
</code>```

Body:
I have a JavaScript file that I want to include only in one component once mounted. For example, this JavaScript file (called dashboard.js) should only run when the Dashboard.vue component is active and mounted.

I have tried sticking the code in mounted(), but this won't work because the code relies on this being the window, not the Vue instance. I have also tried appending the script to the document.head in the mounted function, but this seems like a big hack and I know there has to be a better way to do this.

//Dashboard.vue
<template>

Dashboard content here

</template>

//dashboard.js
$(function() {
  $div = $('div');
  $div.on('click', function() {
    //do stuff
  });
});

I would like for this dashboard.js local script to only be loaded and called when my component gets mounted.

Body:
you can import that script in the component:

// Dashboard.vue
import * as dashboard from "./dashboard";

and then import jQuery inside dashboard.js

// dashboard.js
import jQuery from "jquery";
window.$ = window.jQuery = jQuery;

$(function() {
  var $div = $("div");
  $div.on("click", function() {
    //do stuff
    alert();
  });
});


问:
React Navigation Invarint Violation
I recently started to use React Navigation to go beetween screens. I'm stuck on an error and can't go foward. I'm no sure if it's an error of my project or I'm missing some crucial stuff. I'm tried to reproduce the code from the docs, but didn't work.

Here's the error:

My App.js:

import React from 'react';
import {View, Text, Button} from "react-navigation";
import { createAppContainer, createStackNavigator,  StackActions, NavigationActions } from 'react-navigation';

class LoginScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => {
            this.props.navigation.dispatch(StackActions.reset({
              index: 0,
              actions: [
                NavigationActions.navigate({ routeName: 'Home' })
              ],
            }))
          }}
        />
      </View>
    );
  }
}

class HomeScreen extends React.Component {
  render(){
    return(
      <View>
        <Text>
          Home Screen
        </Text>
      </View>
    );
  }
}

const AppNavigator = createStackNavigator({
  Home: {
    screen: HomeScreen,
  },
  Login: {
    screen: LoginScreen,
  },
}, {
    initialRouteName: 'Login',
});

export default createAppContainer(AppNavigator);
```

<p>This is my index.js:</p>

<pre class="lang-js prettyprint-override"><code>import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);
</code>```

This is my MainActivity.java with all the necessary modifications:

package com.ggwpapplication;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "ggWPapplication";
    }

    @Override
      protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
          @Override
          protected ReactRootView createRootView() {
           return new RNGestureHandlerEnabledRootView(MainActivity.this);
          }
        };
     }
}
```

Note: Before using React Navigation it was all fine.

答:
you have wrong imports on your App.js file:

change:

```<code>import {View, Text, Button} from "react-navigation";
</code>```

to:

```<code>import {View, Text, Button} from "react-native";
</code>```

Title: React Navigation Invarint Violation

Body:
I recently started to use React Navigation to go beetween screens. I'm stuck on an error and can't go foward. I'm no sure if it's an error of my project or I'm missing some crucial stuff. I'm tried to reproduce the code from the docs, but didn't work.

Here's the error:

My App.js:

import React from 'react';
import {View, Text, Button} from "react-navigation";
import { createAppContainer, createStackNavigator,  StackActions, NavigationActions } from 'react-navigation';

class LoginScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => {
            this.props.navigation.dispatch(StackActions.reset({
              index: 0,
              actions: [
                NavigationActions.navigate({ routeName: 'Home' })
              ],
            }))
          }}
        />
      </View>
    );
  }
}

class HomeScreen extends React.Component {
  render(){
    return(
      <View>
        <Text>
          Home Screen
        </Text>
      </View>
    );
  }
}

const AppNavigator = createStackNavigator({
  Home: {
    screen: HomeScreen,
  },
  Login: {
    screen: LoginScreen,
  },
}, {
    initialRouteName: 'Login',
});

export default createAppContainer(AppNavigator);

This is my index.js:

import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

This is my MainActivity.java with all the necessary modifications:

package com.ggwpapplication;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "ggWPapplication";
    }

    @Override
      protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
          @Override
          protected ReactRootView createRootView() {
           return new RNGestureHandlerEnabledRootView(MainActivity.this);
          }
        };
     }
}

Note: Before using React Navigation it was all fine.

Body:
you have wrong imports on your App.js file:

change:

import {View, Text, Button} from "react-navigation";

to:

import {View, Text, Button} from "react-native";


问:
why I have issues in importing views in the urls.py file?
from employee import views
does not work!...the server is giving a page not found (404) response
here is the project structure:

```<code>employee
  migrations folder
....other files
   views.py
hrdjango
 __init__.py
 settings.py
 urls.py
</code>```

I feel like the urls can't access my views
this is the views.py

```<code>from .models import Employee
# Create your views here.
def emp(request):
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})
def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})
def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})
def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")
</code>```

```<code>
from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('emp', views.emp),
    path('show',views.show),
    path('edit/<int:id>', views.edit),
    path('update/<int:id>', views.update),
    path('delete/<int:id>', views.destroy),
]
</code>```

urls.py

I am having unresolved import 'employee'message

答: Is this the project urls.py or the app-level urls.py? If this is your app level urls.py, then the import should be from . import views. If it is the project-level urls.py, then post up your file structure so we can see if the import structure is wrong.

Body:
from employee import views
does not work!...the server is giving a page not found (404) response
here is the project structure:

employee
  migrations folder
....other files
   views.py
hrdjango
 __init__.py
 settings.py
 urls.py

I feel like the urls can't access my views
this is the views.py

from .models import Employee
# Create your views here.
def emp(request):
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})
def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})
def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})
def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")

from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('emp', views.emp),
    path('show',views.show),
    path('edit/<int:id>', views.edit),
    path('update/<int:id>', views.update),
    path('delete/<int:id>', views.destroy),
]

urls.py

I am having unresolved import 'employee'message


问:
Bootstrap 4 - 3 column layout, in lg pull up right column right under left column
Bootstrap 4, 3 column layout

Problem: In lg view-port, the right column appears after the end of the main column content, how could it be "pulled up" so that it appears right under the left column?

Problem demo:
https://jsfiddle.net/2kqug64j/4/
https://fiddle.jshell.net/2kqug64j/4/show/

Code (also available in jsfiddle):

```<code><div class="container-fluid body-container">
  <div class="row">
    <div class="col-12 col-lg-4 col-xl-3 order-lg-first">
      <p>Left column - right should be right under this content in lg view - instead of after the end of the Main column content end</p>
    </div>
    <div id="main" class="col-12 col-lg-8 col-xl-6 order-first">
      <div class="row">
        <div class="col-sm-12">
          <p>
          Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, and some more text</p>
        </div>
      </div>
    </div>
    <div class="col-12 col-lg-4 col-xl-3 order-last">
      <p>
      Right column...</p>
    </div>
  </div>
</div>
</code>```

To visualise what I'm trying to achieve, right column should be right under the content of the left column and not at the level where main column text ends (if the text of the main column was 10x longer then the right column content would begin way down the page:

答:
You should add CSS to set height to 0 at large. This WILL cause issues with any styling like border. I think there are better solutions, however.

@media screen and (min-width: 992px) and (max-width: 1199.98px) {
  #main {
    height: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container-fluid body-container">
  <div class="row">
    <div class="col-12 col-lg-4 col-xl-3 order-lg-first">
      <p>Left column - right should be right under this content in lg view - instead of after the end of the Main column content end</p>
    </div>
    <div id="main" class="col-12 col-lg-8 col-xl-6 order-first">
      <div class="row">
        <div class="col-sm-12" id="main">
          <p>
          Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, and some more text</p>
        </div>
      </div>
    </div>
    <div class="col-12 col-lg-4 col-xl-3 order-last">
      <p>
      Right column...</p>
    </div>
  </div>
</div></code>```

JSFiddle here

Body:
Bootstrap 4, 3 column layout

Problem: In lg view-port, the right column appears after the end of the main column content, how could it be "pulled up" so that it appears right under the left column?

Problem demo:
https://jsfiddle.net/2kqug64j/4/
https://fiddle.jshell.net/2kqug64j/4/show/

Code (also available in jsfiddle):

Left column - right should be right under this content in lg view - instead of after the end of the Main column content end

          Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, and some more text

      Right column...

To visualise what I'm trying to achieve, right column should be right under the content of the left column and not at the level where main column text ends (if the text of the main column was 10x longer then the right column content would begin way down the page:

Body:
You should add CSS to set height to 0 at large. This WILL cause issues with any styling like border. I think there are better solutions, however.

@media screen and (min-width: 992px) and (max-width: 1199.98px) {
  #main {
    height: 0;
  }
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container-fluid body-container">
  <div class="row">
    <div class="col-12 col-lg-4 col-xl-3 order-lg-first">
      <p>Left column - right should be right under this content in lg view - instead of after the end of the Main column content end</p>
    </div>
    <div id="main" class="col-12 col-lg-8 col-xl-6 order-first">
      <div class="row">
        <div class="col-sm-12" id="main">
          <p>
          Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, Main column, and some more text</p>
        </div>
      </div>
    </div>
    <div class="col-12 col-lg-4 col-xl-3 order-last">
      <p>
      Right column...</p>
    </div>
  </div>
</div>

JSFiddle here


问:
@Transactional on aspect advice possible?
Can I apply the @Transactional tag to an aspect advice?  I'm trying to wrap all calls to the service layer (com.mycompany.app.myapp.service.*) in a transaction using aspects.  My aspect is properly intercepting the calls to the service layer, but I can't figure out how to start a transaction.  I thought I could apply the @Transactional tag and because I've got the  tag, it'd pick it up and begin the transaction.  What am I missing?

XML configuration:

```<code><bean id="systemArchitectureAspect" class="com.mycompany.app.myapp.aspect.SystemArchitecture"/>
<bean id="transactionAspect" class="com.mycompany.app.myapp.aspect.MyAspect"/>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.transaction.jta.JtaTransactionManager">
    <property name="transactionManager" ref="AtomikosTransactionManager" />
    <property name="userTransaction" ref="AtomikosUserTransaction" />
</bean>

<bean id="AtomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
    init-method="init" destroy-method="close">

    <property name="forceShutdown" value="false" />
</bean>

<bean id="AtomikosUserTransaction"
    class="com.atomikos.icatch.jta.UserTransactionImp">
    <property name="transactionTimeout" value="10" />
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" />
    </tx:attributes>
</tx:advice>
</code>```

Aspect w/pointcuts:

```<code>package com.mycompany.app.myapp.aspect;

@Aspect
public class SystemArchitecture {
    @Pointcut( "execution(* com.mycompany.app.myapp.service..*.*(..))" )
    public void inServiceLayer() {};

    @Pointcut( "execution(* com.mycompany.data..*.*(..))" )
    public void inDataAccessLayer() {};
}
</code>```

The advice I'm trying to apply to my pointcuts:

```<code>package com.mycompany.app.myapp.aspect;

@Aspect
public class TransactionAspect {

    @Transactional
    @Around( "com.mycompany.app.myapp.aspect.SystemArchitecture.inServiceLayer()" )
    public Object interceptServiceLayer( ProceedingJoinPoint pjp ) throws Throwable
    {
        return pjp.proceed();
    }
}
</code>```

答:
As @Espen said you should apply @Transactionalon your business methods directly as the Annotation itself causes Spring to create an Aspect that applies transactions to your method. So there is no need to create an aspect manually.

However, if you want to apply transactions to all you service methods and whatever else you selected with those pointcuts you should do use the xml configuration to create the transactions. Look for declarative transaction management in the documentation

Also I don't think you can apply @Transactional to an Advice. At least it is not working for me.

ContentLicense: CC BY-SA 2.5

Body:
Can I apply the @Transactional tag to an aspect advice?  I'm trying to wrap all calls to the service layer (com.mycompany.app.myapp.service.*) in a transaction using aspects.  My aspect is properly intercepting the calls to the service layer, but I can't figure out how to start a transaction.  I thought I could apply the @Transactional tag and because I've got the  tag, it'd pick it up and begin the transaction.  What am I missing?

XML configuration:

<bean id="systemArchitectureAspect" class="com.mycompany.app.myapp.aspect.SystemArchitecture"/>
<bean id="transactionAspect" class="com.mycompany.app.myapp.aspect.MyAspect"/>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.transaction.jta.JtaTransactionManager">
    <property name="transactionManager" ref="AtomikosTransactionManager" />
    <property name="userTransaction" ref="AtomikosUserTransaction" />
</bean>

<bean id="AtomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
    init-method="init" destroy-method="close">

    <property name="forceShutdown" value="false" />
</bean>

<bean id="AtomikosUserTransaction"
    class="com.atomikos.icatch.jta.UserTransactionImp">
    <property name="transactionTimeout" value="10" />
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" />
    </tx:attributes>
</tx:advice>

Aspect w/pointcuts:

package com.mycompany.app.myapp.aspect;

@Aspect
public class SystemArchitecture {
    @Pointcut( "execution(* com.mycompany.app.myapp.service..*.*(..))" )
    public void inServiceLayer() {};

    @Pointcut( "execution(* com.mycompany.data..*.*(..))" )
    public void inDataAccessLayer() {};
}

The advice I'm trying to apply to my pointcuts:

package com.mycompany.app.myapp.aspect;

@Aspect
public class TransactionAspect {

    @Transactional
    @Around( "com.mycompany.app.myapp.aspect.SystemArchitecture.inServiceLayer()" )
    public Object interceptServiceLayer( ProceedingJoinPoint pjp ) throws Throwable
    {
        return pjp.proceed();
    }
}


问:
Blazor: InvalidOperationException while attempting to activate custom service
I am testing out Blazor and now trying to get a grip regarding services and custom services.

The problem is I get this error message when starting the Blazor application:

WASM: System.InvalidOperationException: Unable to resolve service for
  type 'Blazor.Extensions.Storage.Interfaces.IStorage' while attempting
  to activate 'BlazorTest.Services.MyLocalStorage'.

My own custom service MyLocalStorage requires another service to access the browsers local storage; in this case I am using Blazor.Extensions.Storage

According to this page on learn.microsoft.com, a custom service that depends on another service needs to have a constructor to support it: "Constructor injection must be used instead. Required services are added by adding parameters to the service's constructor. When dependency injection creates the service, it recognizes the services it requires in the constructor and provides them accordingly."

So, my ConfigureServices in Startup.cs looks like this:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddStorage(); // <-- extension method for Blazor.Extensions.Storage
    services.AddSingleton<IMyLocalStorage, MyLocalStorage>();
}
</code>```

and my custom service:

```<code>public interface IMyLocalStorage
{
    Task<string> GetAuthToken();
    Task<string> GetDeviceUUID();
    Task SetAuthToken(string authToken);
    Task SetDeviceUuid(string deviceUuid);
}

public class MyLocalStorage : IMyLocalStorage
{

    private readonly IStorage storage;

    public MyLocalStorage(IStorage storage)
    {
        this.storage = storage;
    }
    // bla bla implementation
}
</code>```

I thought this was the only thing required, but it still fails as can be seen above.

Note that if I skip my own custom serivce and use the Blazor.Extensions.Storage package directly, it works without any issues.

Im running VS2019 Preview 16.2.0 and .NET Core 3.0.0.

答:
If you take a look at the Blazor Storage code here you can see it does not register the IStorage interface.

Further inspection of the SessionStorage and LocalStorage classes shows that both implement IStorage so even if you did register IStorage you would need to clarify which class you want to inject.

It looks like you need to inject SessionStorage or LocalStorage in your constructor instead.

```<code>public class MyLocalStorage : IMyLocalStorage
{
    private readonly LocalStorage storage;

    public MyLocalStorage(LocalStorage storage)
    {
        this.storage = storage;
    }
    // bla bla implementation
}
</code>```

Body:
I am testing out Blazor and now trying to get a grip regarding services and custom services.

The problem is I get this error message when starting the Blazor application:

WASM: System.InvalidOperationException: Unable to resolve service for
  type 'Blazor.Extensions.Storage.Interfaces.IStorage' while attempting
  to activate 'BlazorTest.Services.MyLocalStorage'.

My own custom service MyLocalStorage requires another service to access the browsers local storage; in this case I am using Blazor.Extensions.Storage

According to this page on learn.microsoft.com, a custom service that depends on another service needs to have a constructor to support it: "Constructor injection must be used instead. Required services are added by adding parameters to the service's constructor. When dependency injection creates the service, it recognizes the services it requires in the constructor and provides them accordingly."

So, my ConfigureServices in Startup.cs looks like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddStorage(); // <-- extension method for Blazor.Extensions.Storage
    services.AddSingleton<IMyLocalStorage, MyLocalStorage>();
}

and my custom service:

public interface IMyLocalStorage
{
    Task<string> GetAuthToken();
    Task<string> GetDeviceUUID();
    Task SetAuthToken(string authToken);
    Task SetDeviceUuid(string deviceUuid);
}

public class MyLocalStorage : IMyLocalStorage
{

    private readonly IStorage storage;

    public MyLocalStorage(IStorage storage)
    {
        this.storage = storage;
    }
    // bla bla implementation
}

I thought this was the only thing required, but it still fails as can be seen above.

Note that if I skip my own custom serivce and use the Blazor.Extensions.Storage package directly, it works without any issues.

Im running VS2019 Preview 16.2.0 and .NET Core 3.0.0.

Body:
If you take a look at the Blazor Storage code here you can see it does not register the IStorage interface.

Further inspection of the SessionStorage and LocalStorage classes shows that both implement IStorage so even if you did register IStorage you would need to clarify which class you want to inject.

It looks like you need to inject SessionStorage or LocalStorage in your constructor instead.

public class MyLocalStorage : IMyLocalStorage
{
    private readonly LocalStorage storage;

    public MyLocalStorage(LocalStorage storage)
    {
        this.storage = storage;
    }
    // bla bla implementation
}


问:
Add Hover effect to Font Awesome Stars
I would like a simple method, whereby you hover over them and they are a solid yellow.

```<code>const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "60%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
  }
});

function Tasks(props) {
  const { classes } = props;
  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>
              <div className="name-label">
              Name
              </div>
              <Typography variant="h6" gutterBottom>
              {props.name}
              </Typography>
              <div className="form-divider"></div>
                <Typography variant="body2" color="textSecondary">
                {props.description}
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">
      <i class="far fa-play-circle fa-2x"></i>
    </Grid>
    <div className="workers-assigned-label">
      Workers Assigned
    </div>
    <Typography variant="h6" gutterBottom>
        0/25
      </Typography>
      <div class="star-rating">
        <label class="far fa-star fa-2x"></label>
        <label class="far fa-star fa-2x"></label>
        <label class="far fa-star fa-2x"></label>
      </div>
    <div>
      unassigned
    </div>
  </Grid>
          </Grid>
        </Grid>
      </Paper>
    </div>
  );
}

export default withStyles(styles)(Tasks);
</code>```

If anyone has any suggestions as to how to get them to change from https://fontawesome.com/v4.7.0/icon/star-o to having the centre fill with yellow that would be much appreciated. Whether it be best done with CSS or something using React.

答:
Did you check the version of Font Awesome you use? This icon seems to be in the 4.7.0. I've had multiple problems with icons not showing and usually it was because I was using an outdated version or the icon I wanted to use was in a newer version of Font Awesome.

And if you use a newer one, check if the icon still exists for this version, it may have been removed or renamed.

Title: Add Hover effect to Font Awesome Stars

Body:
I would like a simple method, whereby you hover over them and they are a solid yellow.

const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "60%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
  }
});

function Tasks(props) {
  const { classes } = props;
  return (

      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>

              Name

              <Typography variant="h6" gutterBottom>
              {props.name}
              </Typography>

                <Typography variant="body2" color="textSecondary">
                {props.description}
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">

    </Grid>

      Workers Assigned

    <Typography variant="h6" gutterBottom>
        0/25
      </Typography>

      unassigned

  </Grid>
          </Grid>
        </Grid>
      </Paper>

  );
}

export default withStyles(styles)(Tasks);

If anyone has any suggestions as to how to get them to change from https://fontawesome.com/v4.7.0/icon/star-o to having the centre fill with yellow that would be much appreciated. Whether it be best done with CSS or something using React.


问:
Diagnosing Mac Help keyword indexing?
I am having difficulty coaxing the "Help → Search" function of my application to show topics related to the useful (and unique) keywords in my application.  Only one keyword shows up.

Background: I created several html help pages (examples: index, accuracy, convert) in a subdirectory of my program.  If I invoke the master help, the index.html file shows up fine.  From there, I can click through to any of the other topic pages.

Problem: If I try using the keyword search function, only "Accuracy" and a blank indicator (that pulls up the index.html) show up.  I have other keywords like "coordinates" that should point to a specific page, but aren't showing up.

What I've done so far: In addition to re-skimming the documentation (which at this time, I am a little bleary-eyed), I have run each page through BBEdit's syntax checker.  I also searched StackOverflow for information related to the problem.  Because the keywords are rather ubiquitous, this was the primary topical match, but I'm well-past that.

The Help Indexer log notes that it's indexed all of the html files, finding KEYWORDS and DESCRIPTION meta tags in each (as recommended by the Help Book):

```<code>droot.html -- File has KEYWORDS meta tag content being indexed.
gc.html -- File has KEYWORDS meta tag content being indexed.
index.html -- File has KEYWORDS meta tag content being indexed.
droot.html -- File has DESCRIPTION meta tag used for abstract.
gc.html -- File has DESCRIPTION meta tag used for abstract.
index.html -- Finished parsing
droot.html -- Finished parsing
gc.html -- Finished parsing
(etc)
</code>```

The *.helpindex file in the Release package (?/Contents/Resources/MacFizzyCalcHelp/ directory) is ~25k.  I do not know how to inspect its contents, though.

Any thoughts on what I'm missing?

答:
I just had the issue of the blank Apple help entry and after several days of trying everything I could think of, finally found the solution. Add META NAME="ROBOTS" CONTENT="NOINDEX" to the blank entry's page (in my case it was index.html, aka the landing page or access page). I then re-indexed the HTML pages and lo, no more blank entry. No need to even delete the help viewer cache.

[Edited as tags hid content :-]

Title: Diagnosing Mac Help keyword indexing?

Body:
I am having difficulty coaxing the "Help → Search" function of my application to show topics related to the useful (and unique) keywords in my application.  Only one keyword shows up.

Background: I created several html help pages (examples: index, accuracy, convert) in a subdirectory of my program.  If I invoke the master help, the index.html file shows up fine.  From there, I can click through to any of the other topic pages.

Problem: If I try using the keyword search function, only "Accuracy" and a blank indicator (that pulls up the index.html) show up.  I have other keywords like "coordinates" that should point to a specific page, but aren't showing up.

What I've done so far: In addition to re-skimming the documentation (which at this time, I am a little bleary-eyed), I have run each page through BBEdit's syntax checker.  I also searched StackOverflow for information related to the problem.  Because the keywords are rather ubiquitous, this was the primary topical match, but I'm well-past that.

The Help Indexer log notes that it's indexed all of the html files, finding KEYWORDS and DESCRIPTION meta tags in each (as recommended by the Help Book):

droot.html -- File has KEYWORDS meta tag content being indexed.
gc.html -- File has KEYWORDS meta tag content being indexed.
index.html -- File has KEYWORDS meta tag content being indexed.
droot.html -- File has DESCRIPTION meta tag used for abstract.
gc.html -- File has DESCRIPTION meta tag used for abstract.
index.html -- Finished parsing
droot.html -- Finished parsing
gc.html -- Finished parsing
(etc)

The *.helpindex file in the Release package (?/Contents/Resources/MacFizzyCalcHelp/ directory) is ~25k.  I do not know how to inspect its contents, though.

Any thoughts on what I'm missing?


问:
How do I do large non-blocking updates in PostgreSQL?
I want to do a large update on a table in PostgreSQL, but I don't need the transactional integrity to be maintained across the entire operation, because I know that the column I'm changing is not going to be written to or read during the update.  I want to know if there is an easy way in the psql console to make these types of operations faster.

For example, let's say I have a table called "orders" with 35 million rows, and I want to do this:

```<code>UPDATE orders SET status = null;
</code>```

To avoid being diverted to an offtopic discussion, let's assume that all the values of status for the 35 million columns are currently set to the same (non-null) value, thus rendering an index useless.

The problem with this statement is that it takes a very long time to go into effect (solely because of the locking), and all changed rows are locked until the entire update is complete.    This update might take 5 hours, whereas something like

```<code>UPDATE orders SET status = null WHERE (order_id > 0 and order_id < 1000000);
</code>```

might take 1 minute.   Over 35 million rows, doing the above and breaking it into chunks of 35 would only take 35 minutes and save me 4 hours and 25 minutes.

I could break it down even further with a script (using pseudocode here):

```<code>for (i = 0 to 3500) {
  db_operation ("UPDATE orders SET status = null
                 WHERE (order_id >" + (i*1000)"
             + " AND order_id <" + ((i+1)*1000) " +  ")");
}
</code>```

This operation might complete in only a few minutes, rather than 35.

So that comes down to what I'm really asking.  I don't want to write a freaking script to break down operations every single time I want to do a big one-time update like this.   Is there a way to accomplish what I want entirely within SQL?

答:
PostgreSQL version 11 handles this for you automatically with the Fast ALTER TABLE ADD COLUMN with a non-NULL default feature. Please do upgrade to version 11 if possible.

An explanation is provided in this blog post.

OwnerDisplayName: S D

LastEditorDisplayName: S D

Body:
I want to do a large update on a table in PostgreSQL, but I don't need the transactional integrity to be maintained across the entire operation, because I know that the column I'm changing is not going to be written to or read during the update.  I want to know if there is an easy way in the psql console to make these types of operations faster.

For example, let's say I have a table called "orders" with 35 million rows, and I want to do this:

UPDATE orders SET status = null;

To avoid being diverted to an offtopic discussion, let's assume that all the values of status for the 35 million columns are currently set to the same (non-null) value, thus rendering an index useless.

The problem with this statement is that it takes a very long time to go into effect (solely because of the locking), and all changed rows are locked until the entire update is complete.    This update might take 5 hours, whereas something like

UPDATE orders SET status = null WHERE (order_id > 0 and order_id < 1000000);

might take 1 minute.   Over 35 million rows, doing the above and breaking it into chunks of 35 would only take 35 minutes and save me 4 hours and 25 minutes.

I could break it down even further with a script (using pseudocode here):

for (i = 0 to 3500) {
  db_operation ("UPDATE orders SET status = null
                 WHERE (order_id >" + (i*1000)"
             + " AND order_id <" + ((i+1)*1000) " +  ")");
}

This operation might complete in only a few minutes, rather than 35.

So that comes down to what I'm really asking.  I don't want to write a freaking script to break down operations every single time I want to do a big one-time update like this.   Is there a way to accomplish what I want entirely within SQL?