问:
Reversing array elements in C programming
I am new to C and I have a problem. I need to reverse the elements of arrays in the following program. Can I get a very simple explanation of what I am doing wrong and how I could go on about fixing it?

Here's the output I get:

```Enter number 0: 0
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
Enter number 6: 6
Enter number 7: 7
Element 0 is: 7
Element 1 is: 6
Element 2 is: 5
Element 3 is: 4
Element 4 is: 4
Element 5 is: 5
Element 6 is: 6
Element 7 is: 7
```

My code:

```<code>#include <stdio.h>

void reverse(int a[], int i)
{
    int j=7,b;
    for (i=0; i<=7; i++)
    {
        b=a[i];
        a[i]=a[j];
        a[j]=b;
        printf("Element %d is: %d\n", i,a[i]);
        j--;
    }
}

int main(void)
{
    int a[8];
    int i;
    for(i=0;i<=7;i++)
    {
        printf("Enter number %d: ",i);
        scanf("%d", &a[i]);
    }
    reverse(a, 8);
    return 0;
}
</code>```

答:
To avoid being misled, write the output after the reversal, not during it:

```<code>#include <stdio.h>

void reverse(int a[], int i)
{
    int j = 7, b;
    for (i = 0; i <= 7; i++)
    {
        b = a[i];
        a[i] = a[j];
        a[j] = b;
        j--;
    }
}

int main(void)
{
    int a[8];
    int i;

    for (i = 0; i <= 7; i++)
    {
        printf("Enter number %d: ",i);
        scanf("%d", &a[i]);
    }

    reverse(a, 8);

    for (i = 0; i <= 7; i++)
    {
        printf("Element %d is: %d\n", i, a[i]);
    }

    return 0;
}
</code>```

Now you’ll notice the array isn’t changing at all. That’s because you’re swapping every element in the array twice: once to its reversed position, then back to its original position. To fix this, only loop over the first half the array, i.e. while i < 4.

It was probably also intended to make the second argument to reverse the length, so you should make use of that instead of hard-coding 7 or 4:

```<code>void reverse(int a[], int length)
{
    int i, j = length - 1, b;

    for (i = 0; i < length / 2; i++)
    {
        b = a[i];
        a[i] = a[j];
        a[j] = b;
        j--;
    }
}
</code>```

Body:
I am new to C and I have a problem. I need to reverse the elements of arrays in the following program. Can I get a very simple explanation of what I am doing wrong and how I could go on about fixing it?

Here's the output I get:

Enter number 0: 0
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
Enter number 6: 6
Enter number 7: 7
Element 0 is: 7
Element 1 is: 6
Element 2 is: 5
Element 3 is: 4
Element 4 is: 4
Element 5 is: 5
Element 6 is: 6
Element 7 is: 7

My code:

#include <stdio.h>

void reverse(int a[], int i)
{
    int j=7,b;
    for (i=0; i<=7; i++)
    {
        b=a[i];
        a[i]=a[j];
        a[j]=b;
        printf("Element %d is: %d\n", i,a[i]);
        j--;
    }
}

int main(void)
{
    int a[8];
    int i;
    for(i=0;i<=7;i++)
    {
        printf("Enter number %d: ",i);
        scanf("%d", &a[i]);
    }
    reverse(a, 8);
    return 0;
}

Body:
To avoid being misled, write the output after the reversal, not during it:

#include <stdio.h>

void reverse(int a[], int i)
{
    int j = 7, b;
    for (i = 0; i <= 7; i++)
    {
        b = a[i];
        a[i] = a[j];
        a[j] = b;
        j--;
    }
}

int main(void)
{
    int a[8];
    int i;

    for (i = 0; i <= 7; i++)
    {
        printf("Enter number %d: ",i);
        scanf("%d", &a[i]);
    }

    reverse(a, 8);

    for (i = 0; i <= 7; i++)
    {
        printf("Element %d is: %d\n", i, a[i]);
    }

    return 0;
}

Now you’ll notice the array isn’t changing at all. That’s because you’re swapping every element in the array twice: once to its reversed position, then back to its original position. To fix this, only loop over the first half the array, i.e. while i < 4.

It was probably also intended to make the second argument to reverse the length, so you should make use of that instead of hard-coding 7 or 4:

void reverse(int a[], int length)
{
    int i, j = length - 1, b;

    for (i = 0; i < length / 2; i++)
    {
        b = a[i];
        a[i] = a[j];
        a[j] = b;
        j--;
    }
}


来源: stackexchange

问:
Calculating the current member balance based on transactional data
I have a MySQL table of financial transactions.

The table is like so:

```<code>+----+-----------+--------+--------+---------+---------+
| id | member_id | status | amount | opening | closing |
+----+-----------+--------+--------+---------+---------+
| 1  | 2         | 1      | 1000   | 0       | 1000    |
| 2  | 2         | 2      | 100    | 1000    | 1000    |
| 3  | 2         | 1      | -20    | 1000    | 980     |
| 4  | 2         | 1      | 10     | 980     | 990     |
+----+-----------+--------+--------+---------+---------+
</code>```

Currently the opening and closing fields are empty. Status 1 is committed, and 2 is uncommitted.

Can some one please tell me how I would write a query to scan the entire table and update all the opening and closing balances?

There is almost 1,000,000 records in this table so it would be nice if the query was quite optimized. Also this is not going to be needed for real time mission critical data. It would only be the current estimation of the members balance.

答:
The solution requires a program - I'll show it via a stored procedure.

SQL is particularly bad at doing queries that rely on the order of rows in a table based on column(s) where the values are unknown - like your id column. The only way to tackle such cases is with some kind of executable code that scans through the data.

Although you haven't stated it, I'll assume the logic is:

Process rows ordered by member and id

Ignore rows where status = 2

Set opening to 0 if it's the first row found for a member

Update the closing to be the opening plus the amount

Note that there is one obvious issue here: What happens if a status changes (either from 2 to 1 or 1 to 2)? It will require a recalculation of that member's transactions from that point on

Here's the stored procedure that does this:

```<code>drop procedure if exists calculate_balances;
delimiter ~
create procedure calculate_balances()
comment 'calculates running balances'
begin
declare _id int;
declare _member_id int;
declare _amount int;
declare _balance int;
declare _current_member_id int default 0;
declare _done int default 0;

declare _cursor cursor for
select id, member_id, case when status = 1 then amount else 0 end
from member_txns
order by member_id, id;

declare continue handler for not found set _done = 1;

open _cursor;

repeat
  fetch _cursor into _id, _member_id, _amount;

  if not _done then
    if _current_member_id != _member_id then
      set _balance = 0;
      set _current_member_id = _member_id;
    end if;

    update member_txns set opening = _balance, closing = _balance + _amount where id = _id;

    set _balance = _balance + _amount;
  end if;
until _done end repeat;

end;~
delimiter ;
</code>```

Note that the treatment of status is handled in the query.

Here's the code to test:

```<code>create table member_txns (
id int,
member_id int,
status int,
amount int,
opening int,
closing int
);

insert into member_txns (id, member_id, status, amount) values
(1,2,1,1000),
(2,2,2,100),
(3,2,1,-20),
(4,2,1,10),
(5,3,1,-20),
(6,3,1,100);

call calculate_balances();

select * from member_txns;
</code>```

Executing these commands will show the stored procedure produces the correct result.

ContentLicense: CC BY-SA 2.5

Body:
I have a MySQL table of financial transactions.

The table is like so:

+----+-----------+--------+--------+---------+---------+
| id | member_id | status | amount | opening | closing |
+----+-----------+--------+--------+---------+---------+
| 1  | 2         | 1      | 1000   | 0       | 1000    |
| 2  | 2         | 2      | 100    | 1000    | 1000    |
| 3  | 2         | 1      | -20    | 1000    | 980     |
| 4  | 2         | 1      | 10     | 980     | 990     |
+----+-----------+--------+--------+---------+---------+

Currently the opening and closing fields are empty. Status 1 is committed, and 2 is uncommitted.

Can some one please tell me how I would write a query to scan the entire table and update all the opening and closing balances?

There is almost 1,000,000 records in this table so it would be nice if the query was quite optimized. Also this is not going to be needed for real time mission critical data. It would only be the current estimation of the members balance.

Body:
The solution requires a program - I'll show it via a stored procedure.

SQL is particularly bad at doing queries that rely on the order of rows in a table based on column(s) where the values are unknown - like your id column. The only way to tackle such cases is with some kind of executable code that scans through the data.

Although you haven't stated it, I'll assume the logic is:

Process rows ordered by member and id

Ignore rows where status = 2

Set opening to 0 if it's the first row found for a member

Update the closing to be the opening plus the amount

Note that there is one obvious issue here: What happens if a status changes (either from 2 to 1 or 1 to 2)? It will require a recalculation of that member's transactions from that point on

Here's the stored procedure that does this:

drop procedure if exists calculate_balances;
delimiter ~
create procedure calculate_balances()
comment 'calculates running balances'
begin
declare _id int;
declare _member_id int;
declare _amount int;
declare _balance int;
declare _current_member_id int default 0;
declare _done int default 0;

declare _cursor cursor for
select id, member_id, case when status = 1 then amount else 0 end
from member_txns
order by member_id, id;

declare continue handler for not found set _done = 1;

open _cursor;

repeat
  fetch _cursor into _id, _member_id, _amount;

  if not _done then
    if _current_member_id != _member_id then
      set _balance = 0;
      set _current_member_id = _member_id;
    end if;

    update member_txns set opening = _balance, closing = _balance + _amount where id = _id;

    set _balance = _balance + _amount;
  end if;
until _done end repeat;

end;~
delimiter ;

Note that the treatment of status is handled in the query.

Here's the code to test:

create table member_txns (
id int,
member_id int,
status int,
amount int,
opening int,
closing int
);

insert into member_txns (id, member_id, status, amount) values
(1,2,1,1000),
(2,2,2,100),
(3,2,1,-20),
(4,2,1,10),
(5,3,1,-20),
(6,3,1,100);

call calculate_balances();

select * from member_txns;

Executing these commands will show the stored procedure produces the correct result.


问:
.NET Reflection - How to get "real" type from out ParameterInfo
I'm trying to validate that a parameter is both an out parameter and extends an interface (ICollection). The reflection api doesn't seem to want to give me the "real" type of the parameter, only the one with an "&" at the end which will not evaluate correctly in an IsAssignableFrom statement. I've written some c# code that works but it seems like there should be a better way to do this.

```<code>bool isCachedArg(ParameterInfo pInfo)
{
    if (!pInfo.IsOut)
        return false;

    string typeName = pInfo.ParameterType.FullName;
    string nameNoAmpersand = typeName.Substring(0, typeName.Length - 1);
    Type realType = Type.GetType(nameNoAmpersand);

    if (!typeof(ICollection).IsAssignableFrom(realType))
        return false;

    return true;
}
</code>```

Is there a way to get realType without reloading the Type from its string name? I'm still on .NET 2.1.

Thanks,
Randy

答:
See this:</p>

```<code>var parameters = methodinfo.GetParameters();
foreach (var parameter in parameters)
{
    var HasValue = "";
    Type ParameterType = (parameter.IsOut || parameter.ParameterType.IsByRef) ? parameter.ParameterType.GetElementType() : parameter.ParameterType;
    if (ParameterType.GetProperties().Count() == 2 && ParameterType.GetProperties()[0].Name.Equals("HasValue"))
    {
        HasValue = "?";
        ParameterType = ParameterType.GetProperties()[1].PropertyType;
    }
    StringBuilder sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    {
        var expr = new CodeTypeReferenceExpression(ParameterType);
        var prov = new CSharpCodeProvider();
        prov.GenerateCodeFromExpression(expr, sw, new CodeGeneratorOptions());
    }
    var result = string.Concat(sb.ToString(), HasValue, " ", parameter.Name);
    Console.WriteLine(result);
}
</code>```

Body:
I'm trying to validate that a parameter is both an out parameter and extends an interface (ICollection). The reflection api doesn't seem to want to give me the "real" type of the parameter, only the one with an "&" at the end which will not evaluate correctly in an IsAssignableFrom statement. I've written some c# code that works but it seems like there should be a better way to do this.

bool isCachedArg(ParameterInfo pInfo)
{
    if (!pInfo.IsOut)
        return false;

    string typeName = pInfo.ParameterType.FullName;
    string nameNoAmpersand = typeName.Substring(0, typeName.Length - 1);
    Type realType = Type.GetType(nameNoAmpersand);

    if (!typeof(ICollection).IsAssignableFrom(realType))
        return false;

    return true;
}

Is there a way to get realType without reloading the Type from its string name? I'm still on .NET 2.1.

Thanks,
Randy

Body:
See this:

var parameters = methodinfo.GetParameters();
foreach (var parameter in parameters)
{
    var HasValue = "";
    Type ParameterType = (parameter.IsOut || parameter.ParameterType.IsByRef) ? parameter.ParameterType.GetElementType() : parameter.ParameterType;
    if (ParameterType.GetProperties().Count() == 2 && ParameterType.GetProperties()[0].Name.Equals("HasValue"))
    {
        HasValue = "?";
        ParameterType = ParameterType.GetProperties()[1].PropertyType;
    }
    StringBuilder sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    {
        var expr = new CodeTypeReferenceExpression(ParameterType);
        var prov = new CSharpCodeProvider();
        prov.GenerateCodeFromExpression(expr, sw, new CodeGeneratorOptions());
    }
    var result = string.Concat(sb.ToString(), HasValue, " ", parameter.Name);
    Console.WriteLine(result);
}

ContentLicense: CC BY-SA 3.0


问:
force ajax request on back and forward button with pjax
This call to pjax works and it replaces div-section with response from url.
For tabbed navigation, pjax successfully changes url as well

```<code>$.pjax({
        url: $this.attr("href"),
        container: '#div-section',
        push: true
}).done(function() {
        $object.init();
});
</code>```

But back and forward chrome button don't resend Ajax request and its cached in browser. Also below setting is enabled to not force full refresh.

```<code>$.pjax.defaults.timeout = false;
</code>```

how can ajax request be forced on back and forward button with pjax ?

答:
Found solution for it </p>

```<code>$.pjax.defaults.maxCacheLength = 0;
</code>```

Body:
This call to pjax works and it replaces div-section with response from url.
For tabbed navigation, pjax successfully changes url as well

$.pjax({
        url: $this.attr("href"),
        container: '#div-section',
        push: true
}).done(function() {
        $object.init();
});

But back and forward chrome button don't resend Ajax request and its cached in browser. Also below setting is enabled to not force full refresh.

$.pjax.defaults.timeout = false;

how can ajax request be forced on back and forward button with pjax ?

Body:
Found solution for it

$.pjax.defaults.maxCacheLength = 0;


问:
When does IntelliJ's Scala incremental compilation happen?
When does IntelliJ's Scala incremental compilation happen? I notice that making changes to a file does not cause the corresponding .class files (in /target) to be updated. When does this happen?</p>

答:
I think you misunderstand how Scala incremental compilation works.

There are 2 different things that might be called "IntelliJ's Scala incremental compilation ":

1) Proper Scala incremental compilation which is more or less a set of typcial strategies applicable for different programming languages to not (re-)compile everythings from the scratch again when you hit Compile button. The main idea behind that is that the build system might notice that certain files and all their dependency haven't changed since the last compilation and thus you don't have to re-compile them and can use result of the last compilation instead. Those heuristics are actually complicated for Scala as it is a complicated language. Some ideas on what can be done are described at the SBT document "Understanding Incremental Recompilation". At some point JetBrains decided that they are smarter and implemented their set of heuristics and they claim that they are better (i.e. incremental compilation is faster) so now you chose between SBT-based and Idea-based incremental compilation under Scala Compiler settings. But still it only works when you hit Compile (or Run or Debug or something similar). This not something Idea does in background.

2) There is another thing specific for IntelliJ Idea that also requires a kind of incremental recompilation and this one works in almost real time. It is the synxtax highlighting feature that is implemented by Idea's Scala plugin and it requires immediate re-processing of all the files you change in a way similar but now exactly the same as what the real compiler does. And actually you are not supposed to look into the details of that process (unless you are going to develop Scala plug-in itself). What those process provides is some syntax structure of the code but not the actual .class files.


问:
What are all of the generic collections/types in the 4.0 .NET Framework?
Is there an exhaustive list of all of the "base" (not used in an object-oriented sense but more in a common sense) generic types in the 4.0 .NET Framework? I have found this list that I often send newer/mid-level devs to so they can understand how non-generic types map to generic types, but this is by no means exhaustive. I'm looking for something that also includes things such as KeyValuePair<>, Tuple<>, and other basic generics that may not be very-well known. Interfaces such as IObservable<> would be nice but not necessarily required.

答:
This should give you some answers:

System.Collections.Generic Namespace;

System.Collections.Concurrent Namespace.

The System.Collections.Generic namespace provides most of the generic collections that we already know from .NET 3.5. There was already providing three thread-safe collections:

SynchronizedCollection Class;

SynchronizedKeyedCollection Class;

SynchronizedReadOnlyCollection Class.

The System.Collections.Concurrent namespace namespace provides thread-safe generic collections.


问:
the error of ImportError: No module named
I am trying to run a program, whose files are organized as follows, The subfolder of tensorflow_fcn and architecture.py share the same parent directory. In architecture.py, there is a line of code from tensorflow_fcn import fcn8_vgg

The folder of tensorflow_fcn already includes _init_.py

However, running the program gets error message as follows

```<code>File "FCN/KittiSeg_pretrained/model_files/architecture.py", line 5, in <module>
    from tensorflow_fcn import fcn8_vgg
ImportError: No module named 'tensorflow_fcn'
</code>```

I do not understand why tensorflow_fcn was not identified by architecture.py.

答:
Maybe this is related to the relative path of the file and module.
In my work, there is a subfolder "submodules" at the same level as the file, while subfolder "tensorflow_fcn" is under "submodules". So I use this form:
from submodules.tensorflow_fcn import fcn8_vgg

This page may solve your puzzle
http://85608547.blog.51cto.com/2093443/1576759

Body:
I am trying to run a program, whose files are organized as follows, The subfolder of tensorflow_fcn and architecture.py share the same parent directory. In architecture.py, there is a line of code from tensorflow_fcn import fcn8_vgg

The folder of tensorflow_fcn already includes _init_.py

However, running the program gets error message as follows

File "FCN/KittiSeg_pretrained/model_files/architecture.py", line 5, in <module>
    from tensorflow_fcn import fcn8_vgg
ImportError: No module named 'tensorflow_fcn'

I do not understand why tensorflow_fcn was not identified by architecture.py.


问:
Query JSON with SQLAlchemy using the `sqlalchemy.types.JSON` data type
I have the following table in SQLAlchemy:

```<code>class FooModel(Base):
    __tablename__ = 'table'
    id = sqla.Column('id', INTEGER, primary_key=True)
    info = sqla.Column(JSON)
</code>```

And I want to execute the following query:

```<code>result = session.query(FooModel).filter(
    FooModel.info['key1'].astext.cast(INTEGER) == 1).all()
</code>```

The above query works just fine as long as the info column in my table is of type sqlalchemy.dialects.postgresql.JSON. However, if I use JSON from sqlalchemy.JSON I get the following error: AttributeError: Neither 'BinaryExpression' object nor 'Comparator' object has an attribute 'astext'.

Since the above is the most basic filter one can have, does this mean that in order to do any kind of querying you have to use types from a specific SQL dialect? In other words: Is it possible to modify the above query and make it run when I use the sqlalchemy.JSON type? (which will allow the code to work on both PostreSQL and MySQL)

答:
Maybe you can try it as follow

from sqlalchemy import JSON
from sqlalchemy.sql.expression import cast
result = session.query(FooModel).filter(FooModel.info['key1'] == cast(1, JSON).all()

Body:
I have the following table in SQLAlchemy:

class FooModel(Base):
    __tablename__ = 'table'
    id = sqla.Column('id', INTEGER, primary_key=True)
    info = sqla.Column(JSON)

And I want to execute the following query:

result = session.query(FooModel).filter(
    FooModel.info['key1'].astext.cast(INTEGER) == 1).all()

The above query works just fine as long as the info column in my table is of type sqlalchemy.dialects.postgresql.JSON. However, if I use JSON from sqlalchemy.JSON I get the following error: AttributeError: Neither 'BinaryExpression' object nor 'Comparator' object has an attribute 'astext'.

Since the above is the most basic filter one can have, does this mean that in order to do any kind of querying you have to use types from a specific SQL dialect? In other words: Is it possible to modify the above query and make it run when I use the sqlalchemy.JSON type? (which will allow the code to work on both PostreSQL and MySQL)


问:
Interfacing Python with Fortran module by ctypes
I have this module in Fortran:

```<code>  MODULE utils
  IMPLICIT NONE
  PUBLIC
  INTEGER :: num_atom ! number of atoms in one configuration
    CONTAINS
      SUBROUTINE readin
      IMPLICIT NONE
      INTEGER :: iargc, ndim, i

     END SUBROUTINE readin

     SUBROUTINE convert
     IMPLICIT NONE
     REAL :: x,y,z
     END SUBROUTINE convert
</code>```

I compile it by:

```<code>gfortran -shared -fPIC -cpp -O2 thiscode.f90 -o somelib.so
</code>```

So, while trying to call the function "readin" from the following python code:

```<code>import os
_path = os.path.dirname(os.path.realpath(__file__)) + "/" + "somelib.so"

from ctypes import cdll, byref, c_int, c_double, c_char
lib_polint = cdll.LoadLibrary(_path)

def A():
    a = lib_polint.readin_

A()
</code>```

I can not identify the name of the function into "somelib.so" and the following error appear:

"undefined symbol: readin_".

If I remove the module and keep just the subroutine "readin", it works.
How to handle this?

答:
Dump the symbols from the shared library

```<code>$ nm -D somelib.so
0000000000201020 B __bss_start
                 w __cxa_finalize
0000000000201020 D _edata
0000000000201028 B _end
00000000000006f4 T _fini
                 w __gmon_start__
00000000000005a0 T _init
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable
                 w _Jv_RegisterClasses
00000000000006e0 T __utils_MOD_convert
0000000000201024 B __utils_MOD_num_at
00000000000006f0 T __utils_MOD_readin
</code>```

Looks like having your subroutine in a module affected the symbol name. Instead of readin_ you have __utils_MOD_readin. If you remove the surrounding module and leave your subroutines at the top level then you'll get the symbol names you expected.

For the record, I'm just reporting what I see on my system. I'm not familiar with fortran and don't know whether you can depend on this naming across compilers.

Body:
I have this module in Fortran:

  MODULE utils
  IMPLICIT NONE
  PUBLIC
  INTEGER :: num_atom ! number of atoms in one configuration
    CONTAINS
      SUBROUTINE readin
      IMPLICIT NONE
      INTEGER :: iargc, ndim, i

     END SUBROUTINE readin

     SUBROUTINE convert
     IMPLICIT NONE
     REAL :: x,y,z
     END SUBROUTINE convert

I compile it by:

gfortran -shared -fPIC -cpp -O2 thiscode.f90 -o somelib.so

So, while trying to call the function "readin" from the following python code:

import os
_path = os.path.dirname(os.path.realpath(__file__)) + "/" + "somelib.so"

from ctypes import cdll, byref, c_int, c_double, c_char
lib_polint = cdll.LoadLibrary(_path)

def A():
    a = lib_polint.readin_

A()

I can not identify the name of the function into "somelib.so" and the following error appear:

"undefined symbol: readin_".

If I remove the module and keep just the subroutine "readin", it works.
How to handle this?

Body:
Dump the symbols from the shared library

$ nm -D somelib.so
0000000000201020 B __bss_start
                 w __cxa_finalize
0000000000201020 D _edata
0000000000201028 B _end
00000000000006f4 T _fini
                 w __gmon_start__
00000000000005a0 T _init
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable
                 w _Jv_RegisterClasses
00000000000006e0 T __utils_MOD_convert
0000000000201024 B __utils_MOD_num_at
00000000000006f0 T __utils_MOD_readin

Looks like having your subroutine in a module affected the symbol name. Instead of readin_ you have __utils_MOD_readin. If you remove the surrounding module and leave your subroutines at the top level then you'll get the symbol names you expected.

For the record, I'm just reporting what I see on my system. I'm not familiar with fortran and don't know whether you can depend on this naming across compilers.


问:
How to effectively flatten nested lists and dataframes into a single dataframe?
I have some data that is formatted in a way that's difficult to use, so I'm trying to flatten it out. The minimum reproducible example is here.

```<code>> str(sampleData)
List of 4
 $ Events       :'data.frame':  2 obs. of  3 variables:
  ..$ CateringOptions:List of 2
  .. ..$ :'data.frame': 1 obs. of  3 variables:
  .. .. ..$ Agreed : logi TRUE
  .. .. ..$ Tnc    :'data.frame': 1 obs. of  5 variables:
  .. .. .. ..$ Identity      : chr "SpicyOWing"
  .. .. .. ..$ Schema        : logi NA
  .. .. .. ..$ ElementId     : chr "105031"
  .. .. .. ..$ ElementType   : logi NA
  .. .. .. ..$ ElementVersion: logi NA
  .. .. ..$ Address: chr "New York"
  .. ..$ :'data.frame': 1 obs. of  3 variables:
  .. .. ..$ Agreed : logi TRUE
  .. .. ..$ Tnc    :'data.frame': 1 obs. of  5 variables:
  .. .. .. ..$ Identity      : chr "BaconEggs"
  .. .. .. ..$ Schema        : logi NA
  .. .. .. ..$ ElementId     : chr "105032"
  .. .. .. ..$ ElementType   : logi NA
  .. .. .. ..$ ElementVersion: logi NA
  .. .. ..$ Address: chr "Seattle"
  ..$ Action         : num [1:2] 1 1
  ..$ Volume         : num [1:2] 1000 2000
 $ Host         :List of 5
  ..$ Identity      : chr "John"
  ..$ Schema        : logi NA
  ..$ ElementId     : chr "101505"
  ..$ ElementType   : logi NA
  ..$ ElementVersion: logi NA
 $ Sender       :List of 5
  ..$ Identity      : chr "Jane"
  ..$ Schema        : logi NA
  ..$ ElementId     : chr "101005"
  ..$ ElementType   : logi NA
  ..$ ElementVersion: logi NA
 $ CompletedDate: chr "/Date(1490112000000)/"
</code>```

Expected

```<code>> expectedOutcome
  Events.CateringOptions.Agreed Events.CateringOptions.Tnc.Identity Events.CateringOptions.Tnc.Schema Events.CateringOptions.Tnc.ElementId
1                            NA                          SpicyOWing                                TRUE                               105031
2                            NA                           BaconEggs                                TRUE                               105032
  Events.CateringOptions.Tnc.ElementType Events.CateringOptions.Tnc.ElementVersion Events.CateringOptions.Address Events.Action Events.Volume Host.Identity
1                                     NA                                        NA                       New York             1          1000          John
2                                     NA                                        NA                        Seattle             1          2000          John
  Host.Schema Host.ElementId Host.ElementType Host.ElementVersion Sender.Identity Sender.Schema Sender.ElementId Sender.ElementType Sender.ElementVersion
1          NA         101505               NA                  NA            Jane            NA           101005                 NA                    NA
2          NA         101505               NA                  NA            Jane            NA           101005                 NA                    NA
          CompletedDate
1 /Date(1490112000000)/
2 /Date(1490112000000)/
</code>```

The check function

```<code>check<-function(li){
  areDF<-sapply(1:length(li), function(i) class(li[[i]]) == "data.frame")
  areList<-sapply(1:length(li), function(i) class(li[[i]]) == "list")
  tmp1 <- NULL
  tmp2 <- NULL
  if(any(areDF)){
    for(j in which(areDF)){
      columns <- jsonlite::flatten(li[[j]])
      li[[j]]  <- check(columns)
    }
    tmp1<-plyr::rbind.fill(li[areDF])
    #return(tmp1)
  }
  if(any(areList)){
    for(j in which(areList)){
      li[[j]]<-check(li[[j]])
    }
    tmp2<-do.call(cbind,li)
    #return(tmp2)
  }
  if(!is.null(tmp1) & !is.null(tmp2)){
    return (cbind(tmp1,tmp2))
  }
  else if(!is.null(tmp1)){
    return (tmp1)
  }
  else if(!is.null(tmp2)){
    return (tmp2)
  }
  return(li)
}
</code>```

Results

```<code>> str(check(sampleData))
'data.frame': 2 obs. of  29 variables:
 $ CateringOptions.Agreed                   : logi  TRUE TRUE
 $ CateringOptions.Address                  : chr  "New York" "Seattle"
 $ CateringOptions.Tnc.Identity             : chr  "SpicyOWing" "BaconEggs"
 $ CateringOptions.Tnc.Schema               : logi  NA NA
 $ CateringOptions.Tnc.ElementId            : chr  "105031" "105032"
 $ CateringOptions.Tnc.ElementType          : logi  NA NA
 $ CateringOptions.Tnc.ElementVersion       : logi  NA NA
 $ Action                                   : num  1 1
 $ Volume                                   : num  1000 2000
 $ Events.CateringOptions.Agreed            : logi  TRUE TRUE
 $ Events.CateringOptions.Address           : chr  "New York" "Seattle"
 $ Events.CateringOptions.Tnc.Identity      : chr  "SpicyOWing" "BaconEggs"
 $ Events.CateringOptions.Tnc.Schema        : logi  NA NA
 $ Events.CateringOptions.Tnc.ElementId     : chr  "105031" "105032"
 $ Events.CateringOptions.Tnc.ElementType   : logi  NA NA
 $ Events.CateringOptions.Tnc.ElementVersion: logi  NA NA
 $ Events.Action                            : num  1 1
 $ Events.Volume                            : num  1000 2000
 $ Host.Identity                            : Factor w/ 1 level "John": 1 1
 $ Host.Schema                              : logi  NA NA
 $ Host.ElementId                           : Factor w/ 1 level "101505": 1 1
 $ Host.ElementType                         : logi  NA NA
 $ Host.ElementVersion                      : logi  NA NA
 $ Sender.Identity                          : Factor w/ 1 level "Jane": 1 1
 $ Sender.Schema                            : logi  NA NA
 $ Sender.ElementId                         : Factor w/ 1 level "101005": 1 1
 $ Sender.ElementType                       : logi  NA NA
 $ Sender.ElementVersion                    : logi  NA NA
 $ CompletedDate                            : Factor w/ 1 level "/Date(1490112000000)/": 1 1
</code>```

I almost have it, but the nested dataframe is being duped. Also, my code takes fairly long. Does anyone have any idea how I can go about flattening this?

Edit:

I added my solution in the end in the gist

答:
Not sure if this over-simplifies your problem, but with the sample you shared, it seems to work. Basically, if the column is not already a vector when you do data.frame(your_list), it unlists the data and makes a matrix.

```<code>FLAT <- function(inlist) {
  A <- data.frame(inlist)
  out <- lapply(A, function(y) {
    if (is.list(y)) {
      y <- unlist(y)
      m <- matrix(y, nrow(A), byrow = TRUE, dimnames = list(NULL, unique(names(y))))
      y <- data.frame(m, stringsAsFactors = FALSE)
      y[] <- lapply(y, type.convert)
    }
    y
  })
  do.call(cbind, out)
}
FLAT(sampleData)
</code>```

Here's the str on your sample data:

```<code>str(FLAT(sampleData))
## 'data.frame':    2 obs. of  20 variables:
##  $ Events.CateringOptions.Agreed            : logi  TRUE TRUE
##  $ Events.CateringOptions.Tnc.Identity      : Factor w/ 2 levels "BaconEggs","SpicyOWing": 2 1
##  $ Events.CateringOptions.Tnc.Schema        : logi  NA NA
##  $ Events.CateringOptions.Tnc.ElementId     : int  105031 105032
##  $ Events.CateringOptions.Tnc.ElementType   : logi  NA NA
##  $ Events.CateringOptions.Tnc.ElementVersion: logi  NA NA
##  $ Events.CateringOptions.Address           : Factor w/ 2 levels "New York","Seattle": 1 2
##  $ Events.Action                            : num  1 1
##  $ Events.Volume                            : num  1000 2000
##  $ Host.Identity                            : Factor w/ 1 level "John": 1 1
##  $ Host.Schema                              : logi  NA NA
##  $ Host.ElementId                           : Factor w/ 1 level "101505": 1 1
##  $ Host.ElementType                         : logi  NA NA
##  $ Host.ElementVersion                      : logi  NA NA
##  $ Sender.Identity                          : Factor w/ 1 level "Jane": 1 1
##  $ Sender.Schema                            : logi  NA NA
##  $ Sender.ElementId                         : Factor w/ 1 level "101005": 1 1
##  $ Sender.ElementType                       : logi  NA NA
##  $ Sender.ElementVersion                    : logi  NA NA
##  $ CompletedDate                            : Factor w/ 1 level "/Date(1490112000000)/": 1 1
</code>```

Body:
I have some data that is formatted in a way that's difficult to use, so I'm trying to flatten it out. The minimum reproducible example is here.

> str(sampleData)
List of 4
 $ Events       :'data.frame':  2 obs. of  3 variables:
  ..$ CateringOptions:List of 2
  .. ..$ :'data.frame': 1 obs. of  3 variables:
  .. .. ..$ Agreed : logi TRUE
  .. .. ..$ Tnc    :'data.frame': 1 obs. of  5 variables:
  .. .. .. ..$ Identity      : chr "SpicyOWing"
  .. .. .. ..$ Schema        : logi NA
  .. .. .. ..$ ElementId     : chr "105031"
  .. .. .. ..$ ElementType   : logi NA
  .. .. .. ..$ ElementVersion: logi NA
  .. .. ..$ Address: chr "New York"
  .. ..$ :'data.frame': 1 obs. of  3 variables:
  .. .. ..$ Agreed : logi TRUE
  .. .. ..$ Tnc    :'data.frame': 1 obs. of  5 variables:
  .. .. .. ..$ Identity      : chr "BaconEggs"
  .. .. .. ..$ Schema        : logi NA
  .. .. .. ..$ ElementId     : chr "105032"
  .. .. .. ..$ ElementType   : logi NA
  .. .. .. ..$ ElementVersion: logi NA
  .. .. ..$ Address: chr "Seattle"
  ..$ Action         : num [1:2] 1 1
  ..$ Volume         : num [1:2] 1000 2000
 $ Host         :List of 5
  ..$ Identity      : chr "John"
  ..$ Schema        : logi NA
  ..$ ElementId     : chr "101505"
  ..$ ElementType   : logi NA
  ..$ ElementVersion: logi NA
 $ Sender       :List of 5
  ..$ Identity      : chr "Jane"
  ..$ Schema        : logi NA
  ..$ ElementId     : chr "101005"
  ..$ ElementType   : logi NA
  ..$ ElementVersion: logi NA
 $ CompletedDate: chr "/Date(1490112000000)/"

Expected

> expectedOutcome
  Events.CateringOptions.Agreed Events.CateringOptions.Tnc.Identity Events.CateringOptions.Tnc.Schema Events.CateringOptions.Tnc.ElementId
1                            NA                          SpicyOWing                                TRUE                               105031
2                            NA                           BaconEggs                                TRUE                               105032
  Events.CateringOptions.Tnc.ElementType Events.CateringOptions.Tnc.ElementVersion Events.CateringOptions.Address Events.Action Events.Volume Host.Identity
1                                     NA                                        NA                       New York             1          1000          John
2                                     NA                                        NA                        Seattle             1          2000          John
  Host.Schema Host.ElementId Host.ElementType Host.ElementVersion Sender.Identity Sender.Schema Sender.ElementId Sender.ElementType Sender.ElementVersion
1          NA         101505               NA                  NA            Jane            NA           101005                 NA                    NA
2          NA         101505               NA                  NA            Jane            NA           101005                 NA                    NA
          CompletedDate
1 /Date(1490112000000)/
2 /Date(1490112000000)/

The check function

check<-function(li){
  areDF<-sapply(1:length(li), function(i) class(li[[i]]) == "data.frame")
  areList<-sapply(1:length(li), function(i) class(li[[i]]) == "list")
  tmp1 <- NULL
  tmp2 <- NULL
  if(any(areDF)){
    for(j in which(areDF)){
      columns <- jsonlite::flatten(li[[j]])
      li[[j]]  <- check(columns)
    }
    tmp1<-plyr::rbind.fill(li[areDF])
    #return(tmp1)
  }
  if(any(areList)){
    for(j in which(areList)){
      li[[j]]<-check(li[[j]])
    }
    tmp2<-do.call(cbind,li)
    #return(tmp2)
  }
  if(!is.null(tmp1) & !is.null(tmp2)){
    return (cbind(tmp1,tmp2))
  }
  else if(!is.null(tmp1)){
    return (tmp1)
  }
  else if(!is.null(tmp2)){
    return (tmp2)
  }
  return(li)
}

Results

> str(check(sampleData))
'data.frame': 2 obs. of  29 variables:
 $ CateringOptions.Agreed                   : logi  TRUE TRUE
 $ CateringOptions.Address                  : chr  "New York" "Seattle"
 $ CateringOptions.Tnc.Identity             : chr  "SpicyOWing" "BaconEggs"
 $ CateringOptions.Tnc.Schema               : logi  NA NA
 $ CateringOptions.Tnc.ElementId            : chr  "105031" "105032"
 $ CateringOptions.Tnc.ElementType          : logi  NA NA
 $ CateringOptions.Tnc.ElementVersion       : logi  NA NA
 $ Action                                   : num  1 1
 $ Volume                                   : num  1000 2000
 $ Events.CateringOptions.Agreed            : logi  TRUE TRUE
 $ Events.CateringOptions.Address           : chr  "New York" "Seattle"
 $ Events.CateringOptions.Tnc.Identity      : chr  "SpicyOWing" "BaconEggs"
 $ Events.CateringOptions.Tnc.Schema        : logi  NA NA
 $ Events.CateringOptions.Tnc.ElementId     : chr  "105031" "105032"
 $ Events.CateringOptions.Tnc.ElementType   : logi  NA NA
 $ Events.CateringOptions.Tnc.ElementVersion: logi  NA NA
 $ Events.Action                            : num  1 1
 $ Events.Volume                            : num  1000 2000
 $ Host.Identity                            : Factor w/ 1 level "John": 1 1
 $ Host.Schema                              : logi  NA NA
 $ Host.ElementId                           : Factor w/ 1 level "101505": 1 1
 $ Host.ElementType                         : logi  NA NA
 $ Host.ElementVersion                      : logi  NA NA
 $ Sender.Identity                          : Factor w/ 1 level "Jane": 1 1
 $ Sender.Schema                            : logi  NA NA
 $ Sender.ElementId                         : Factor w/ 1 level "101005": 1 1
 $ Sender.ElementType                       : logi  NA NA
 $ Sender.ElementVersion                    : logi  NA NA
 $ CompletedDate                            : Factor w/ 1 level "/Date(1490112000000)/": 1 1

I almost have it, but the nested dataframe is being duped. Also, my code takes fairly long. Does anyone have any idea how I can go about flattening this?

Edit:

I added my solution in the end in the gist

Body:
Not sure if this over-simplifies your problem, but with the sample you shared, it seems to work. Basically, if the column is not already a vector when you do data.frame(your_list), it unlists the data and makes a matrix.

FLAT <- function(inlist) {
  A <- data.frame(inlist)
  out <- lapply(A, function(y) {
    if (is.list(y)) {
      y <- unlist(y)
      m <- matrix(y, nrow(A), byrow = TRUE, dimnames = list(NULL, unique(names(y))))
      y <- data.frame(m, stringsAsFactors = FALSE)
      y[] <- lapply(y, type.convert)
    }
    y
  })
  do.call(cbind, out)
}
FLAT(sampleData)

Here's the str on your sample data:

str(FLAT(sampleData))
## 'data.frame':    2 obs. of  20 variables:
##  $ Events.CateringOptions.Agreed            : logi  TRUE TRUE
##  $ Events.CateringOptions.Tnc.Identity      : Factor w/ 2 levels "BaconEggs","SpicyOWing": 2 1
##  $ Events.CateringOptions.Tnc.Schema        : logi  NA NA
##  $ Events.CateringOptions.Tnc.ElementId     : int  105031 105032
##  $ Events.CateringOptions.Tnc.ElementType   : logi  NA NA
##  $ Events.CateringOptions.Tnc.ElementVersion: logi  NA NA
##  $ Events.CateringOptions.Address           : Factor w/ 2 levels "New York","Seattle": 1 2
##  $ Events.Action                            : num  1 1
##  $ Events.Volume                            : num  1000 2000
##  $ Host.Identity                            : Factor w/ 1 level "John": 1 1
##  $ Host.Schema                              : logi  NA NA
##  $ Host.ElementId                           : Factor w/ 1 level "101505": 1 1
##  $ Host.ElementType                         : logi  NA NA
##  $ Host.ElementVersion                      : logi  NA NA
##  $ Sender.Identity                          : Factor w/ 1 level "Jane": 1 1
##  $ Sender.Schema                            : logi  NA NA
##  $ Sender.ElementId                         : Factor w/ 1 level "101005": 1 1
##  $ Sender.ElementType                       : logi  NA NA
##  $ Sender.ElementVersion                    : logi  NA NA
##  $ CompletedDate                            : Factor w/ 1 level "/Date(1490112000000)/": 1 1


问:
Git opening Sublime in Windows
I ran the following instructions and they "worked" perfectly. Actually they did exactly what they said on the box. The issue I have is that when I run a command like git commit I want it to use sublime as the message editor.

Windows

Find the directory where Sublime is located for you.  For many people,
  this is C:/Program\ Files/Sublime\ Text\ 2/sublime_text.exe.  To test
  this, run ls C:/Program\ Files/Sublime\ Text\ 2 within Git Bash.  You
  should see sublime_text.exe listed.  If you get the error No such file
  or directory, Sublime is located somewhere else for you and you'll
  need to find it.  For example, it might be under C:/Program\ Files\
  (x86)`.

Run the following command in Git Bash: echo 'alias subl="C:/Program\
  Files/Sublime\ Text\ 2/sublime_text.exe"' >> ~/.bashrc If subl was in
  a different directory for you in step 1, use that directory.

Close and re-open Git Bash.  Typing subl in Git Bash should now open
  Sublime.

I know that I should run the command

```<code>git config --global core.editor "subl"
</code>```

But that then runs the error message below when I try to use git commit

error: cannot spawn subl: No such file or directory error: unable to
  start editor 'subl' Please supply the message using either -m or -F
  option.

Can anyone shed any light on what I should be doing?

答:
I changed the / to \ and it worked for me on Windows 10. I am using sublime text 3.</p>

```<code>git config --global core.editor "C:\Program Files\Sublime Text 3\sublime_text.exe -w -n"
</code>```

Title: Git opening Sublime in Windows

Body:
I ran the following instructions and they "worked" perfectly. Actually they did exactly what they said on the box. The issue I have is that when I run a command like git commit I want it to use sublime as the message editor.

Windows

Find the directory where Sublime is located for you.  For many people,
  this is C:/Program\ Files/Sublime\ Text\ 2/sublime_text.exe.  To test
  this, run ls C:/Program\ Files/Sublime\ Text\ 2 within Git Bash.  You
  should see sublime_text.exe listed.  If you get the error No such file
  or directory, Sublime is located somewhere else for you and you'll
  need to find it.  For example, it might be under C:/Program\ Files\
  (x86)`.

Run the following command in Git Bash: echo 'alias subl="C:/Program\
  Files/Sublime\ Text\ 2/sublime_text.exe"' >> ~/.bashrc If subl was in
  a different directory for you in step 1, use that directory.

Close and re-open Git Bash.  Typing subl in Git Bash should now open
  Sublime.

I know that I should run the command

git config --global core.editor "subl"

But that then runs the error message below when I try to use git commit

error: cannot spawn subl: No such file or directory error: unable to
  start editor 'subl' Please supply the message using either -m or -F
  option.

Can anyone shed any light on what I should be doing?

Body:
I changed the / to \ and it worked for me on Windows 10. I am using sublime text 3.

git config --global core.editor "C:\Program Files\Sublime Text 3\sublime_text.exe -w -n"


问:
JMapViewer: strange behavior of setMovementMouseButton() method
I am trying to change the mouse button to pan the map view from the right button to left.

There is a simple code changing the button after the left mouse button has been clicked:

```<code>public class Map extends JMapViewer {

    public Map()         {
            new DefaultMapController(this){
                    public void mousePressed(MouseEvent e) {
                            this.setMovementMouseButton(MouseEvent.BUTTON1);
                    }
            };
    }
}
</code>```

Main class:

```<code>public class JMapViewerDemo {
    public static void main(String[] args) {
           JFrame f = new JFrame();
           f.add(new Map());
           f.setSize(800, 600);
           f.setVisible(true);
           f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
</code>```

Surprisingly, the code does not work (no reassignment has been done). Why? However, after calling the parent class method

```<code>public void mousePressed(MouseEvent e) {
     super.mousePressed(e);      //Calling the parent-class method
     this.setMovementMouseButton(MouseEvent.BUTTON1);
}
</code>```

the following behavior was observed:

Click the left mouse button. When dragging no reassignment has
been done (the same situation).

Release the left mouse button.

Click the left mouse button again. When dragging, the panning is assign to the left mouse button.

I find this behavior strange. Maybe, I am using this method incorrectly...

How to change the panning button directly, without being released and clicked again? Thanks for your help...

答:
The results seen are not unexpected, but they may be a little counter-intuitive: Your example alters the internal state of the DefaultMapController in your implementation of mousePressed(). Instead, save a reference to the custom controller so that you can change the preferred button as desired:

```<code>    JMapViewer map = new JMapViewer();
    DefaultMapController dmc = new DefaultMapController(map){…};
    dmc.setMovementMouseButton(MouseEvent.BUTTON1);
</code>```

In a desktop application, you might let the user select a preferred mouse button using radio buttons and save the chosen value among the user's Preferences as shown here. Also consider overriding getPreferredSize(), as shown here, instead of invoking setSize().

Body:
I am trying to change the mouse button to pan the map view from the right button to left.

There is a simple code changing the button after the left mouse button has been clicked:

public class Map extends JMapViewer {

    public Map()         {
            new DefaultMapController(this){
                    public void mousePressed(MouseEvent e) {
                            this.setMovementMouseButton(MouseEvent.BUTTON1);
                    }
            };
    }
}

Main class:

public class JMapViewerDemo {
    public static void main(String[] args) {
           JFrame f = new JFrame();
           f.add(new Map());
           f.setSize(800, 600);
           f.setVisible(true);
           f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Surprisingly, the code does not work (no reassignment has been done). Why? However, after calling the parent class method

public void mousePressed(MouseEvent e) {
     super.mousePressed(e);      //Calling the parent-class method
     this.setMovementMouseButton(MouseEvent.BUTTON1);
}

the following behavior was observed:

Click the left mouse button. When dragging no reassignment has
been done (the same situation).

Release the left mouse button.

Click the left mouse button again. When dragging, the panning is assign to the left mouse button.

I find this behavior strange. Maybe, I am using this method incorrectly...

How to change the panning button directly, without being released and clicked again? Thanks for your help...

Body:
The results seen are not unexpected, but they may be a little counter-intuitive: Your example alters the internal state of the DefaultMapController in your implementation of mousePressed(). Instead, save a reference to the custom controller so that you can change the preferred button as desired:

    JMapViewer map = new JMapViewer();
    DefaultMapController dmc = new DefaultMapController(map){…};
    dmc.setMovementMouseButton(MouseEvent.BUTTON1);

In a desktop application, you might let the user select a preferred mouse button using radio buttons and save the chosen value among the user's Preferences as shown here. Also consider overriding getPreferredSize(), as shown here, instead of invoking setSize().


问:
Compare All Strings in a List - C#
I have List<String> clr9, which has a known Count of nine.

What I want to know is how to shorthand something that goes on later in the code.

```<code>else if(clr9[0].Equals(clr9[1]) && clr9[0].Equals(clr9[2]) && clr9[0].Equals(clr9[3]))
</code>```

I've already tried this:

```<code>else if(clr9[0].Equals(clr9[1].Equals(clr9[2].Equals(clr9[3]))))
</code>```

but it doesn't seem to work. Is there any way I can avoid the ampersands?
Basically just asking if there's a way to find out if all 4 strings are the same without cluttering up that if statement.

答:
Well, if you're only checking all the strings inside a single list like for example clr9. What you can do is use LINQ Distinct:

```<code>if (clr9.Distinct().Skip(1).Any())
{
  //Do something
}
</code>```

T

Hope it helps!

Title: Compare All Strings in a List - C#

Body:
I have List<String> clr9, which has a known Count of nine.

What I want to know is how to shorthand something that goes on later in the code.

else if(clr9[0].Equals(clr9[1]) && clr9[0].Equals(clr9[2]) && clr9[0].Equals(clr9[3]))

I've already tried this:

else if(clr9[0].Equals(clr9[1].Equals(clr9[2].Equals(clr9[3]))))

but it doesn't seem to work. Is there any way I can avoid the ampersands?
Basically just asking if there's a way to find out if all 4 strings are the same without cluttering up that if statement.

Body:
Well, if you're only checking all the strings inside a single list like for example clr9. What you can do is use LINQ Distinct:

if (clr9.Distinct().Skip(1).Any())
{
  //Do something
}

T

Hope it helps!


问:
Rectify graphviz lines
I'm trying to create a graph that looks like a lattice that keeps extending. Here's the code I have:

```<code>graph G {
0 [label=""];
1 [label=""];
2 [label=""];
3 [label=""];
4 [label=""];
5 [label=""];
6 [label=""];
7 [label=""];
8 [label=""];
9 [label="", shape="none"];
10 [label="", shape="none"];
11 [label="", shape="none"];
12 [label="", shape="none"];
13 [label="", shape="none"];
14 [label="", shape="none"];
15 [label="", shape="none"];
16 [label="", shape="none"];
17 [label="", shape="none"];
18 [label="", shape="none"];
19 [label="", shape="none"];
20 [label="", shape="none"];
0 -- 1;
0 -- 2;
0 -- 3;
0 -- 4;
1 -- 5;
2 -- 5;
2 -- 6;
3 -- 6;
3 -- 7;
4 -- 7;
4 -- 8;
1 -- 8;
1 -- 9;
2 -- 10;
3 -- 11;
4 -- 12;
5 -- 13;
6 -- 14;
7 -- 15;
8 -- 16;
5 -- 17;
6 -- 18;
7 -- 19;
8 -- 20;
}
</code>```

However, this produces output like:

Is there a way to get the edges on the corner nodes rectified so that it looks more regular?

答:
Well I ended up adding a few more invisible vertices and invisible edges, which works. It's not the most elegant solution though.</p>

```<code>graph G {
ratio="fill";
margin=0;
0 [label=""];
1 [label=""];
2 [label=""];
3 [label=""];
4 [label=""];
5 [label=""];
6 [label=""];
7 [label=""];
8 [label=""];
9 [label="", shape=none];
10 [label="", shape=none];
11 [label="", shape=none];
12 [label="", shape=none];
13 [label="", shape=none];
14 [label="", shape=none];
15 [label="", shape=none];
16 [label="", shape=none];
17 [label="", shape=none];
18 [label="", shape=none];
19 [label="", shape=none];
20 [label="", shape=none];
0 -- 1;
0 -- 2;
0 -- 3;
0 -- 4;
1 -- 5;
2 -- 5;
2 -- 6;
3 -- 6;
3 -- 7;
4 -- 7;
4 -- 8;
1 -- 8;
1 -- 9;
2 -- 10;
3 -- 11;
4 -- 12;
5 -- 13;
6 -- 14;
7 -- 15;
8 -- 16;
5 -- 17;
6 -- 18;
7 -- 19;
8 -- 20;
11 -- 18 [style=invis];
14 -- 10 [style=invis];
10 -- 17 [style=invis];
13 -- 9 [style=invis];
9 -- 16 [style=invis];
20 -- 12 [style=invis];
12 -- 15 [style=invis];
19 -- 11 [style=invis];
}
</code>```

Title: Rectify graphviz lines

Body:
I'm trying to create a graph that looks like a lattice that keeps extending. Here's the code I have:

graph G {
0 [label=""];
1 [label=""];
2 [label=""];
3 [label=""];
4 [label=""];
5 [label=""];
6 [label=""];
7 [label=""];
8 [label=""];
9 [label="", shape="none"];
10 [label="", shape="none"];
11 [label="", shape="none"];
12 [label="", shape="none"];
13 [label="", shape="none"];
14 [label="", shape="none"];
15 [label="", shape="none"];
16 [label="", shape="none"];
17 [label="", shape="none"];
18 [label="", shape="none"];
19 [label="", shape="none"];
20 [label="", shape="none"];
0 -- 1;
0 -- 2;
0 -- 3;
0 -- 4;
1 -- 5;
2 -- 5;
2 -- 6;
3 -- 6;
3 -- 7;
4 -- 7;
4 -- 8;
1 -- 8;
1 -- 9;
2 -- 10;
3 -- 11;
4 -- 12;
5 -- 13;
6 -- 14;
7 -- 15;
8 -- 16;
5 -- 17;
6 -- 18;
7 -- 19;
8 -- 20;
}

However, this produces output like:

Is there a way to get the edges on the corner nodes rectified so that it looks more regular?

Body:
Well I ended up adding a few more invisible vertices and invisible edges, which works. It's not the most elegant solution though.

graph G {
ratio="fill";
margin=0;
0 [label=""];
1 [label=""];
2 [label=""];
3 [label=""];
4 [label=""];
5 [label=""];
6 [label=""];
7 [label=""];
8 [label=""];
9 [label="", shape=none];
10 [label="", shape=none];
11 [label="", shape=none];
12 [label="", shape=none];
13 [label="", shape=none];
14 [label="", shape=none];
15 [label="", shape=none];
16 [label="", shape=none];
17 [label="", shape=none];
18 [label="", shape=none];
19 [label="", shape=none];
20 [label="", shape=none];
0 -- 1;
0 -- 2;
0 -- 3;
0 -- 4;
1 -- 5;
2 -- 5;
2 -- 6;
3 -- 6;
3 -- 7;
4 -- 7;
4 -- 8;
1 -- 8;
1 -- 9;
2 -- 10;
3 -- 11;
4 -- 12;
5 -- 13;
6 -- 14;
7 -- 15;
8 -- 16;
5 -- 17;
6 -- 18;
7 -- 19;
8 -- 20;
11 -- 18 [style=invis];
14 -- 10 [style=invis];
10 -- 17 [style=invis];
13 -- 9 [style=invis];
9 -- 16 [style=invis];
20 -- 12 [style=invis];
12 -- 15 [style=invis];
19 -- 11 [style=invis];
}


问:
Howto delete every second and third element from an array?
I want to delete every second and third element from an array in Javascript.

My array looks like this:

```<code>var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];
</code>```

Now I want to delete every second and third element. The result would look like this:

```<code>["Banana", "Orange", "Apple"]
</code>```

I tried to use a for-loop and splice:

```<code>for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};
</code>```

Of course this returns an empty array because the elements are removed while the loop is still executed.

How can I do this correctly?

答: You'll want to move through the array backwards, then if i % 2 == 0 || i%3 == 0 then splice the element from the array

ContentLicense: CC BY-SA 4.0

Body:
I want to delete every second and third element from an array in Javascript.

My array looks like this:

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];

Now I want to delete every second and third element. The result would look like this:

["Banana", "Orange", "Apple"]

I tried to use a for-loop and splice:

for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};

Of course this returns an empty array because the elements are removed while the loop is still executed.

How can I do this correctly?


问:
detect page from shebang in url with php or javascript
In a PHP file, i am using a javascript to integrate Spreadshop app into my website.

When an user clicks on an article, it display the article using an URL like this:

```<code>https://www.example.com/#!-A108148940
</code>```

I need to extract the article ID from this url ( 108148940 ) to display an image ( /images/108148940.jpg ) using PHP or Javascript, but only if we are currently viewing the article page (i.e. look for #!-A in the url)

This is the first time i'm forced to use shebang. Why isn't there an easy way to extract the variable just like $_GET['whatever'] with php ?

答:
This can be accomplished in both languages by using a split like function.  Split and explode will divide a string about a character.  So then we can get the second index:

JavaScript

There is a very handy built in way in JavaScript, window.location.hash.

```<code>console.log(window.location.hash);
</code>```

Body:
In a PHP file, i am using a javascript to integrate Spreadshop app into my website.

When an user clicks on an article, it display the article using an URL like this:

https://www.example.com/#!-A108148940

I need to extract the article ID from this url ( 108148940 ) to display an image ( /images/108148940.jpg ) using PHP or Javascript, but only if we are currently viewing the article page (i.e. look for #!-A in the url)

This is the first time i'm forced to use shebang. Why isn't there an easy way to extract the variable just like $_GET['whatever'] with php ?

Body:
This can be accomplished in both languages by using a split like function.  Split and explode will divide a string about a character.  So then we can get the second index:

JavaScript

There is a very handy built in way in JavaScript, window.location.hash.

console.log(window.location.hash);


问:
How to stop DispatchGroup after time? iOS
I'm working with DispatchGroup, I use this to execute two requests from two different servers. When the response comes from two servers, DispatchGroup is called notify(), the problem is that one response from the server may not come (it happened once) how can DispatchGroup notify itself after some time? Or how can I stop the DispatchGroup? I made an example, but I think this is not what I need.

```<code>Timer.scheduledTimer(withTimeInterval: 7.5, repeats: false) { [weak self] (timer) in
        guard let _self = self else { return }
        DispatchQueue.main.async {
            if _self.leaveDispatchGroupDigit == 0 {
                _self.requestGroup.leave()
                _self.requestGroup.leave()
            }
            if _self.leaveDispatchGroupDigit == 1 {
                _self.requestGroup.leave()
            }
        }
    }
</code>```

答: Creating a timeout for the request is the cleanest solution in this case :)</p>

Body:
I'm working with DispatchGroup, I use this to execute two requests from two different servers. When the response comes from two servers, DispatchGroup is called notify(), the problem is that one response from the server may not come (it happened once) how can DispatchGroup notify itself after some time? Or how can I stop the DispatchGroup? I made an example, but I think this is not what I need.

Timer.scheduledTimer(withTimeInterval: 7.5, repeats: false) { [weak self] (timer) in
        guard let _self = self else { return }
        DispatchQueue.main.async {
            if _self.leaveDispatchGroupDigit == 0 {
                _self.requestGroup.leave()
                _self.requestGroup.leave()
            }
            if _self.leaveDispatchGroupDigit == 1 {
                _self.requestGroup.leave()
            }
        }
    }


问:
Search for multiple string occurrence in String via PHP
I am working on an ecommerce website using MVC,php. I have a field called description. The user can enter multiple product id's in the description field.

For example {productID = 34}, {productID = 58}

I am trying to get all product ID's from this field. Just the product ID.

How do i go about this?

答:
This solution doesn't use a capture group.  Rather, it uses \K so that the full string elements become what would otherwise be captured using parentheses.  This is a good practice because it reduces the array element count by 50%.

```<code>$description="{productID = 34}, {productID = 58}";
if(preg_match_all('/productID = \K\d+/',$description,$ids)){
  var_export($ids[0]);
}

// output: array(0=>'34',1=>'58')

// \K in the regex means: keep text from this point
</code>```

Body:
This solution doesn't use a capture group.  Rather, it uses \K so that the full string elements become what would otherwise be captured using parentheses.  This is a good practice because it reduces the array element count by 50%.

$description="{productID = 34}, {productID = 58}";
if(preg_match_all('/productID = \K\d+/',$description,$ids)){
  var_export($ids[0]);
}

// output: array(0=>'34',1=>'58')

// \K in the regex means: keep text from this point


答:
You could distinct the list to remove duplicates and check the length.

e.g.

clr9.Distinct().Count() == 1

or, if you want it to be case insensitive

clr9.Distinct(StringComparer.CurrentCultureIgnoreCase).Count() == 1

Title: Compare All Strings in a List - C#


问:
Deliver multicast to several different geo-locations
I need to use one logical PGM based multicast address in application while enable such application "seamlessly" running across several different geo-locations (i.e. think US/Europe/Australia).

Application is quite throughput (several million biz. messages a day) and latency demanding whith a lot of small but very frequently send messages. Classical Atom pub will not work here due some external limits of latencies.

I have come up with several options to connect those datacenters but can’t find the best one.
Options which I have considered are:
  1)    Forward multicast messages via VPN’s (can VPN handle such big load).
  2)    Translate all multicast messages to “wrapper messages” and forward them via AMQP.
  3)    Write specialized in-house gate which tunnels multicast messages via TCP to other two locations.
  4)    Any other solution

I would prefer option 1 as it does not need additional code writes from devs. but I’m afraid it will not be reliable connection.

Are there any rules to apply for such connectivity?

What the best network configuration with regard to the geographical configuration is for above constrains.

答:
at CohesiveFT we ran into a very similar problem when we designed our "VPN-Cubed" product for connecting multiple clouds up to servers behind our own firewall, in one VPN.  We wanted to be able to run apps that talked to each other using multicast, but for example Amazon EC2 does not support multicast for reasons that should be fairly obvious if you consider the potential for network storms across a whole data center.  We also wanted to route traffic across a wide area federation of nodes using the internet.

Without going into too much detail, the solution involved combining tunneling with standard routing protocols like BGP, and open technologies for VPNs.  We used RabbitMQ AMQP to deliver messages in a pubsub style without needing physical multicast.  This means you can fake multicast over wide area subnets, even across domains and firewalls, provided you are in the VPN-Cubed safe harbour.  It works because it is a 'network overlay' as described in technical note here: http://blog.elasticserver.com/2008/12/vpn-cubed-technical-overview.html

I don't intend to actually offer you a specific solution, but I do hope this answer gives you confidence to try some of these approaches.

Cheers, alexis

OwnerDisplayName: Libor

OwnerDisplayName: alexis


问:
How do I package a website to be served by tomcat?
First, let me apologize, I'm new at web development, so I'm not quite sure how this works, but it's a simple proof of concept, so I don't think it needs to be too advanced.

I have a jar that accesses a server and pulls information that needs to be displayed for the user, I also have a local site that is set up to display this information to the user via html and javascript (but obviously doesn't connect to the server or that jar).  I plan on using tomcat to act as a middleware server that will display the web page and handle the code that accesses the server.

I've seen it done before, but I'm not quite sure how to set it up.  Can somebody just give me the basics on where things need to go to make this work?  I think I'd be ok after that.

My Google-Fu has failed me in finding this, so really any help is appreciated.

Thanks!

答:
I would probably start by download an edition of Eclipse that is aimed at Web Development and creating a new web project directly in there.

This is the Eclipse you want:

http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliossr1

This article could be outdated, but the general idea and the general workflow is still valid:

http://www.ibm.com/developerworks/opensource/library/os-eclipse-tomcat/index.html

Basically, you have to download Eclipse and Tomcat, and create a new web application in Eclipse that uses Tomcat for debugging, and then from Eclipse itself you can generate the WAR file with everything on the right place - this is the file that you will need when deploying the application in your production environment. To do that, you simply copy the file to the ./webapps folder that is sitting in the folder where Tomcat is installed.

PS: I don't know what the state of things is, I personally like using Tomcat 5.5, but I am pretty sure Tomcat 6 will work just fine for what you need.


问:
Jasmine async test error handling
I have this test in Karma/Jasmine:

```<code>    it('async error test', done => {

        function foo(){
            throw new Error('test error');
        }

        function async(){
            setTimeout(() => {
                try{
                    let res = foo();
                    expect(res).toBe(5);
                } catch(e){
                    console.log('in error');
                    done(e);
                }
            });
        }

        async();
    });
</code>```

The done(e) supposed to fail the test but somehow it shows me that the test has been succeeded.

In Mocha/Chai stack it works as expected and the test is failed, do anyone know how should I handle async errors with Karma/Jasmine?

答:
The jasmine and mocha/chai APIs are slightly different in this situation. In jasmine, the done function does not take any arguments. So, if an error is passed in, it is just ignored.

In mocha/chai, an error passed in to the done function will fail the test.

If you are using jasmine, instead of passing in the error, you will need to do something like this in the catch block:

```<code>} catch(e) {
  expect(true).toBe(false);
  done();
}
</code>```

As you have written this for jasmine, the test is passing as it should. Your foo() function throws an error, it is caught, and the test ends. Simple as that. expect(res).toBe(5) is never reached. And the test ends normally without any errors.

Title: Jasmine async test error handling

Body:
I have this test in Karma/Jasmine:

    it('async error test', done => {

        function foo(){
            throw new Error('test error');
        }

        function async(){
            setTimeout(() => {
                try{
                    let res = foo();
                    expect(res).toBe(5);
                } catch(e){
                    console.log('in error');
                    done(e);
                }
            });
        }

        async();
    });

The done(e) supposed to fail the test but somehow it shows me that the test has been succeeded.

In Mocha/Chai stack it works as expected and the test is failed, do anyone know how should I handle async errors with Karma/Jasmine?

Body:
The jasmine and mocha/chai APIs are slightly different in this situation. In jasmine, the done function does not take any arguments. So, if an error is passed in, it is just ignored.

In mocha/chai, an error passed in to the done function will fail the test.

If you are using jasmine, instead of passing in the error, you will need to do something like this in the catch block:

} catch(e) {
  expect(true).toBe(false);
  done();
}

As you have written this for jasmine, the test is passing as it should. Your foo() function throws an error, it is caught, and the test ends. Simple as that. expect(res).toBe(5) is never reached. And the test ends normally without any errors.


问:
Weird and Improper Array size behavior in C++ when initialized in a class
I am trying to create a class called Player which has an array called scores, declared with a size in the Player class properties. Yet, when I initialize a new player, the sizeof(scores) method is giving me 20, and, does, in fact, initialize a score array of size 20 as opposed to 5. I am wondering why and how to fix this. Here is the code and output.

```<code>    #include <iostream>
    #include <iomanip>
    #include <sstream>

    using namespace std;

    struct stats {
        unsigned int min;
        unsigned int max;
        unsigned int mode;
        unsigned int modeFreq;
        unsigned int mean;
        unsigned int total;
    };

    class Player {
        public:
            int scores[5];
            stats pStats;
            void inputScores();
            void calculateStats();
            void printScores();
    };

    void Player::printScores(){
        cout << "Printing Scores..." << endl;
        for (int i = 0; i < sizeof(scores); i++) {
            cout << scores[i] << endl;
        }
    }

    void Player::inputScores(){
        for (int i = 0; i < sizeof(scores); i++) {
            cout << "Enter a score for [" << i << "]: ";
            int input;
            cin >> input;
            scores[i] = input;
        }
    }

    int main() {
        Player p;
        cout << sizeof(p.scores);
        p.inputScores();
        p.printScores();
    }
</code>```

Which gives me this:

```<code>    20
    Enter a score for [0]: 1
    Enter a score for [1]: 2
    Enter a score for [2]: 3
    Enter a score for [3]: 4
    Enter a score for [4]: 5
    Enter a score for [5]: 6
    Enter a score for [6]: 7
    Enter a score for [7]: 8
    Enter a score for [8]: 20
    Enter a score for [0]: 1
    Enter a score for [1]: 2
    Enter a score for [2]: 3
    Enter a score for [3]: 4
    Enter a score for [4]: 5
    Enter a score for [5]: 6
    Enter a score for [6]: 7
    Enter a score for [7]: 8
    Enter a score for [8]:
    ....
</code>```

So on, up to 20...

答:
sizeof(scores) is byte-size of scores object, which is 5 * sizeof(int). On popular platforms that would produce 20. So, you are iterating from 0 to 19 and accessing array elements that do not exist.

The strange output that you observe is nothing more than just a manifestation of undefined behavior caused by out-of-bounds array access.

So, why are you trying to use sizeof(scores) as array size?

There's a sizeof-based technique that can determine array size, but it involves division of byte-size of the entire array by the byte-size of a single element

```<code>sizeof scores / sizeof *scores
</code>```

And keep in mind that it only works for objects of array type (not for pointers).

Alternatively, in modern C++ you can use

```<code>std::extent<decltype(scores)>::value
</code>```

to determine array size.

Body:
I am trying to create a class called Player which has an array called scores, declared with a size in the Player class properties. Yet, when I initialize a new player, the sizeof(scores) method is giving me 20, and, does, in fact, initialize a score array of size 20 as opposed to 5. I am wondering why and how to fix this. Here is the code and output.

    #include <iostream>
    #include <iomanip>
    #include <sstream>

    using namespace std;

    struct stats {
        unsigned int min;
        unsigned int max;
        unsigned int mode;
        unsigned int modeFreq;
        unsigned int mean;
        unsigned int total;
    };

    class Player {
        public:
            int scores[5];
            stats pStats;
            void inputScores();
            void calculateStats();
            void printScores();
    };

    void Player::printScores(){
        cout << "Printing Scores..." << endl;
        for (int i = 0; i < sizeof(scores); i++) {
            cout << scores[i] << endl;
        }
    }

    void Player::inputScores(){
        for (int i = 0; i < sizeof(scores); i++) {
            cout << "Enter a score for [" << i << "]: ";
            int input;
            cin >> input;
            scores[i] = input;
        }
    }

    int main() {
        Player p;
        cout << sizeof(p.scores);
        p.inputScores();
        p.printScores();
    }

Which gives me this:

    20
    Enter a score for [0]: 1
    Enter a score for [1]: 2
    Enter a score for [2]: 3
    Enter a score for [3]: 4
    Enter a score for [4]: 5
    Enter a score for [5]: 6
    Enter a score for [6]: 7
    Enter a score for [7]: 8
    Enter a score for [8]: 20
    Enter a score for [0]: 1
    Enter a score for [1]: 2
    Enter a score for [2]: 3
    Enter a score for [3]: 4
    Enter a score for [4]: 5
    Enter a score for [5]: 6
    Enter a score for [6]: 7
    Enter a score for [7]: 8
    Enter a score for [8]:
    ....

So on, up to 20...

Body:
sizeof(scores) is byte-size of scores object, which is 5 * sizeof(int). On popular platforms that would produce 20. So, you are iterating from 0 to 19 and accessing array elements that do not exist.

The strange output that you observe is nothing more than just a manifestation of undefined behavior caused by out-of-bounds array access.

So, why are you trying to use sizeof(scores) as array size?

There's a sizeof-based technique that can determine array size, but it involves division of byte-size of the entire array by the byte-size of a single element

sizeof scores / sizeof *scores

And keep in mind that it only works for objects of array type (not for pointers).

Alternatively, in modern C++ you can use

std::extent<decltype(scores)>::value

to determine array size.


问:
PhoneGap Build pre-populated SQLite DB
I've successfully used PhoneGap Build with pre-populated SQLite DBs in the past via the https://build.phonegap.com/plugins/2368 plugin. However, Adobe deprecated the use of all plugins from the PG Build repository. Thus, I've been forced to use the npm alternatives.

https://www.npmjs.com/package/cordova-sqlite-storage is the recommended alternative to brodybits' original plugin. However, it's not compatible with PG Build due to them not honoring before_plugin_install hook.

https://github.com/litehelpers/Cordova-sqlite-evcore-extbuild-free and https://github.com/litehelpers/Cordova-sqlite-legacy-build-support are the recommended PG Build solutions. These work successfully to create and save/load to a new SQLite DB. However, they do not inherently support pre-populated DBs. It seems the solution to this was to copy the directory from the www/ directory to the app's DB dir before opening the DB. This is made possible by using https://github.com/an-rahulpandey/cordova-plugin-dbcopy. I've had success using this plugin, but have also experience the app initially crashing (likely due to some case where the DB was trying to be opened before it was copied..?).

It's frustrating to now have to use two plugins to do what one accomplished simply because Adobe deprecated use of its repository. Furthermore, I find it strange that the newer versions of Cordova-sqlite-storage don't support pre-populated DBs anymore when version 1.0.6 did.

I tried adding https://github.com/litehelpers/Cordova-sqlite-storage/tree/a97198d as the plugin source in my config.xml file. However, I can't seem to be able to specify a tag for the git repo (it only seems to pull the master version). Also, I tried adding https://github.com/litehelpers/Cordova-sqlite-storage/tree/a97198d as a custom plugin for PG Build and got an error for invalid url.

Does anyone know a possible solution to this? I'd really just like to be able to use the same plugin I've used for almost two years. Thanks!

答: was the right way to add the plugin to my config.xml file</p>

Title: PhoneGap Build pre-populated SQLite DB


问:
Java guessing letter game
Hi im currently creating a guessing letter game! So far i have made it so you guess between the numbers 1 and 26 using the java.util.random class. However this random number should be converted into the corresponding number within the alphabet! ie a=1 etc..This is where my problem is i dont know how to convert this randomly generated number into a letter! This needs to be related to the integer as i have to able to tell the user if they are above the letter in the alphabet or to low based on the guess they entered! One more thing is that the users guess will be a letter also! Below is my code! Any help will be greatly appreciated!</p>

```<code>{

    Random rand = new Random(); //This is were the computer selects the Target

    int guess;
    int numGuesses = 0;
    int Target;
    String userName;
    String playagain;
    boolean play = true;
    int session = 0;
    int sessions = 0;
    int bestScore = 0;

    Scanner consoleIn = new Scanner(System.in);
    Scanner name = new Scanner(System.in);

    System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
    userName= name.nextLine();

    System.out.println("Hello "+ userName + " :) Welcome to the game!\n");

    while (play = true)
    {
        session++;
        Target = rand.nextInt(26) + 1;
        System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

        do {
            guess = consoleIn.nextInt();
            numGuesses++;

            if (guess > 26)
                System.out.println("Error! Above MAXIMUM range");
            else if (guess <= 0)
                System.out.println("Error! Below MINIMUM range");
            else if (guess > Target)
                System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
            else if (guess < Target)
                System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
           }
            while(guess != Target && numGuesses <5);

            if(guess == Target) {
            System.out.println("Congratulations "+  userName + ", it took you "+ numGuesses +" attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
                    }

            else
            {
            System.out.println("Sorry "+ userName + ", You've used up all of your guesses! The correct answer was "+ Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
            Scanner answer = new Scanner(System.in);
            System.out.println("Would you like another GO "+ userName +"? [Y/N]");//This asks the player if they would like to play again
            playagain = answer.nextLine();
           if(playagain.equalsIgnoreCase("Y"))//This is what happens if the player opts to play again
            {
            play = true;
            numGuesses = 0;

            } else if(playagain.equalsIgnoreCase("N"))//This is what happens if the player opts to exit the game
            {
                play = false;
                System.out.println("Thanks for playing "+ userName +"! :) Please come back soon!");
                System.out.println("You had  "+ session +" Goes");
                System.out.println("The number of times you guessed correctly: "+ sessions +"");
                break;
            }

         }
    }
}
</code>```

答:
```<code> Random random = new Random();
 char c = (char) (random.nextInt(26) + 'a');
</code>```

This maps (0 to 25 ) to ('a' to 'z')

Title: Java guessing letter game

Body:
Hi im currently creating a guessing letter game! So far i have made it so you guess between the numbers 1 and 26 using the java.util.random class. However this random number should be converted into the corresponding number within the alphabet! ie a=1 etc..This is where my problem is i dont know how to convert this randomly generated number into a letter! This needs to be related to the integer as i have to able to tell the user if they are above the letter in the alphabet or to low based on the guess they entered! One more thing is that the users guess will be a letter also! Below is my code! Any help will be greatly appreciated!

{

    Random rand = new Random(); //This is were the computer selects the Target

    int guess;
    int numGuesses = 0;
    int Target;
    String userName;
    String playagain;
    boolean play = true;
    int session = 0;
    int sessions = 0;
    int bestScore = 0;

    Scanner consoleIn = new Scanner(System.in);
    Scanner name = new Scanner(System.in);

    System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
    userName= name.nextLine();

    System.out.println("Hello "+ userName + " :) Welcome to the game!\n");

    while (play = true)
    {
        session++;
        Target = rand.nextInt(26) + 1;
        System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

        do {
            guess = consoleIn.nextInt();
            numGuesses++;

            if (guess > 26)
                System.out.println("Error! Above MAXIMUM range");
            else if (guess <= 0)
                System.out.println("Error! Below MINIMUM range");
            else if (guess > Target)
                System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
            else if (guess < Target)
                System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
           }
            while(guess != Target && numGuesses <5);

            if(guess == Target) {
            System.out.println("Congratulations "+  userName + ", it took you "+ numGuesses +" attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
                    }

            else
            {
            System.out.println("Sorry "+ userName + ", You've used up all of your guesses! The correct answer was "+ Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
            Scanner answer = new Scanner(System.in);
            System.out.println("Would you like another GO "+ userName +"? [Y/N]");//This asks the player if they would like to play again
            playagain = answer.nextLine();
           if(playagain.equalsIgnoreCase("Y"))//This is what happens if the player opts to play again
            {
            play = true;
            numGuesses = 0;

            } else if(playagain.equalsIgnoreCase("N"))//This is what happens if the player opts to exit the game
            {
                play = false;
                System.out.println("Thanks for playing "+ userName +"! :) Please come back soon!");
                System.out.println("You had  "+ session +" Goes");
                System.out.println("The number of times you guessed correctly: "+ sessions +"");
                break;
            }

         }
    }
}

Body:
 Random random = new Random();
 char c = (char) (random.nextInt(26) + 'a');

This maps (0 to 25 ) to ('a' to 'z')


问:
Specify css for specific div
In the process of making a single page website, the css for my form is interfering with the rest of my page. Can the div be specified without going one by one through the css and specifying the div. Any help appreciated.</p>

答:
I recommend you to read up on CSS Selectors, which are different ways in CSS that you can select specific parts of your HTML elements.

The most basic ones are:

The Element Selector

```<code>p { color: #ff0000; }
</code>```

This selects any element in your HTML that match the CSS rule. In this case it would match all
.

The ID Selector

```<code>#paragraph { color: #ff0000; }
</code>```

This selects the element that got a unique ID set to "paragraph". In this case it would select any of the following elements:

```<code><div id="paragraph"></div>
<p id="paragraph"></p>
<span id="paragraph"></span>
</code>```

Note that ID's are suppose to be unique. You are not suppose to have multiple elements with the same ID in your HTML.

The Class Selector

```<code>.paragraph { color: #ff0000; }
</code>```

The class selector selects all element with a class name that match the CSS rule. Note that class names do not need to be unique, unlike ID's, many elements can share the same class name.

The rule above match all of the following elements

```<code><div class="paragraph"></div>
<p class="paragraph header"></p>
<span class="image paragraph"></span>
</code>```

You can also combine these (and other CSS selectors) to be more specific of what you want to select and style with your rule. For example, if you only want to select all
 with the class name paragraph, but no other elements with the same class. You would write the following:

```<code>p.paragraph { color: #ff0000; }
</code>```

Fix your problem

With the knowledge above you can easily fix the issue you are having. The CSS of your form is very generic and it uses Element Selectors to select all elements on the page. You can fix this by setting classes and ID's on your HTML elements, and then adjusting your CSS rules to select the specific elements that you want to change.

Title: Specify css for specific div

Body:
I recommend you to read up on CSS Selectors, which are different ways in CSS that you can select specific parts of your HTML elements.

The most basic ones are:

The Element Selector

p { color: #ff0000; }

This selects any element in your HTML that match the CSS rule. In this case it would match all <p>.

The ID Selector

#paragraph { color: #ff0000; }

This selects the element that got a unique ID set to "paragraph". In this case it would select any of the following elements:

<div id="paragraph"></div>
<p id="paragraph"></p>
<span id="paragraph"></span>

Note that ID's are suppose to be unique. You are not suppose to have multiple elements with the same ID in your HTML.

The Class Selector

.paragraph { color: #ff0000; }

The class selector selects all element with a class name that match the CSS rule. Note that class names do not need to be unique, unlike ID's, many elements can share the same class name.

The rule above match all of the following elements

<div class="paragraph"></div>
<p class="paragraph header"></p>
<span class="image paragraph"></span>

You can also combine these (and other CSS selectors) to be more specific of what you want to select and style with your rule. For example, if you only want to select all <p> with the class name paragraph, but no other elements with the same class. You would write the following:

p.paragraph { color: #ff0000; }

Fix your problem

With the knowledge above you can easily fix the issue you are having. The CSS of your form is very generic and it uses Element Selectors to select all elements on the page. You can fix this by setting classes and ID's on your HTML elements, and then adjusting your CSS rules to select the specific elements that you want to change.


问:
Manipulating the quotes on strings when coding in R
This is actually a series of questions about the referencing character type of values in R. Would add more bullets when I recalled any other related questions I believe which is interesting and related to this topic. For simplification, here I shall use some simple random examples to explain my questions. Hope this helps:

When building up a set of datasets using for loops and wanted to output a series of vectors with names restored in a list called name_list = ("a", "b", "c", "d", "e", "f") in the loop we would like to define as

```<code>for(i in 1:4){
    a <- data[data$Year == 2010,]
    b <- unique(data$Name)
    c <- summarise(group_by(data,Year,Name), avg = mean(quantity))
    ...
    f <- left_join(data,data1, by = c("Year", "Names)
}
</code>```

Is there any function that allows me to use function(name_list[1]) through function(name_list[6]) to replace the a through f in the for loop? This question also goes for trying to create columns using column names in some tables/data frames embedded a chunk of code. (as.name and noquote function work when just referencing the vector/dataset but don't work when attempting to assign values to the target variable, if possible could anyone share why this happens?)

When we extract some information from SQL or other data sources we might have some information separated by comma or some other delimiters as one variable. How could we test if certain values is among one of the values separated by commas? See the example below:

```<code>1567 %in% c(1567,1456,123)
TRUE
a <- "c(1567,1456,123)"
noquote(a)
c(1567,1456,123)
1567 %in% noquote(a)
FALSE
1567 %in% list(noquote(a))
FALSE
b <- "1567,1456,123"
noquote(b)
1567,1456,123
1567 %in% noquote(strsplit(a,","))
FALSE
1567 %in% list(noquote(strsplit(a,",")))
FALSE
</code>```

I kind of get why the %in% here doesn't work, seems like R is taking 1567,1456,123 as one element. So I used the strsplit to separate them. But seems that it's still not working. Wondering is there any way that allows us to get R taking the string as commands?

答:
If all you need to do is convert comma-separated lists like "1567,1456,123" into R vectors like c(1567, 1456, 123), you definitely do not need to wrap them in c(...) and try to evaluate them directly as vectors. You should just use strsplit to split the data:

```<code>data_str <- "1567,1456,123"
data_vec <- as.integer(strsplit(string_data, ","))
stopifnot(1567 %in% data_vec)
</code>```

Note that strsplit returns a list, because it can also character vectors of length greater than one:

```<code>stopifnot(
  all.equal(
    list(c("a", "b"), c("x", "y")),
    strsplit(c("a,b", "x,y"), ",")) == TRUE)
</code>```

which makes it useful for operating on columns of SQL output:

```<code>| id | concatenated_field |
|----|--------------------|
|  1 |    5362,395,9000,7 |
|  2 |       319,75624,63 |
           (etc.)

d <- data.frame(
  id = c(1, 2),
  concatenated_field = c("5362,395,9000,7", "319,75624,63"))
d$split_field <- strsplit(d$concatenated_field, ",")
sapply(d, class)
#             id concatenated_field        split_field
#      "numeric"        "character"             "list"
d$split_field[[1]]
# [1] "5362" "395"  "9000" "7"
</code>```

Alternatively, if you're reading in one big stream of comma-separated data, you can use scan:

```<code>data_vec <- scan(
  what = 0,  # arcane way to say "expect numeric input"
  sep = ",",
  text = "1,2,3,4,5,6,7,8,9,10")
stopifnot(all.equal(data_vec, 1:10) == TRUE)
</code>```

scan is more heavy-duty than strsplit and can handle more complicated inputs as well, such as data with quoted fields:

```<code>weird_data <- scan(what="", sep=",", text='marvin,ruby,"joe,joseph",dean')
print(weird_data)
# [1] "marvin"     "ruby"       "joe,joseph" "dean"
</code>```

If you are really really sure you need to be able to accept and evaluate R code passed as an input (this can be VERY DANGEROUS since it means you will be executing arbitrary unverified R code), you can use

```<code>r_code_string <- 'c("a", "b"), c("x", "y"))'
stopifnot(
  all.equal(
    c("a", "b"), c("x", "y")),
    eval(parse(r_code_string))) == TRUE)
</code>```

parse converts raw text into an unevaluated "expression", which is a representation of R code in the form of a special R object, eval passes the expression to the interpreter for execution.

As for noquote, it doesn't do what you think it does. It doesn't actually modify the string, it just adds a flag to the variable so that it will print without quotation marks. You can emulate this behavior with print(..., quote = FALSE).

Body:
This is actually a series of questions about the referencing character type of values in R. Would add more bullets when I recalled any other related questions I believe which is interesting and related to this topic. For simplification, here I shall use some simple random examples to explain my questions. Hope this helps:

When building up a set of datasets using for loops and wanted to output a series of vectors with names restored in a list called name_list = ("a", "b", "c", "d", "e", "f") in the loop we would like to define as

for(i in 1:4){
    a <- data[data$Year == 2010,]
    b <- unique(data$Name)
    c <- summarise(group_by(data,Year,Name), avg = mean(quantity))
    ...
    f <- left_join(data,data1, by = c("Year", "Names)
}

Is there any function that allows me to use function(name_list[1]) through function(name_list[6]) to replace the a through f in the for loop? This question also goes for trying to create columns using column names in some tables/data frames embedded a chunk of code. (as.name and noquote function work when just referencing the vector/dataset but don't work when attempting to assign values to the target variable, if possible could anyone share why this happens?)

When we extract some information from SQL or other data sources we might have some information separated by comma or some other delimiters as one variable. How could we test if certain values is among one of the values separated by commas? See the example below:

1567 %in% c(1567,1456,123)
TRUE
a <- "c(1567,1456,123)"
noquote(a)
c(1567,1456,123)
1567 %in% noquote(a)
FALSE
1567 %in% list(noquote(a))
FALSE
b <- "1567,1456,123"
noquote(b)
1567,1456,123
1567 %in% noquote(strsplit(a,","))
FALSE
1567 %in% list(noquote(strsplit(a,",")))
FALSE

I kind of get why the %in% here doesn't work, seems like R is taking 1567,1456,123 as one element. So I used the strsplit to separate them. But seems that it's still not working. Wondering is there any way that allows us to get R taking the string as commands?

Body:
If all you need to do is convert comma-separated lists like "1567,1456,123" into R vectors like c(1567, 1456, 123), you definitely do not need to wrap them in c(...) and try to evaluate them directly as vectors. You should just use strsplit to split the data:

data_str <- "1567,1456,123"
data_vec <- as.integer(strsplit(string_data, ","))
stopifnot(1567 %in% data_vec)

Note that strsplit returns a list, because it can also character vectors of length greater than one:

stopifnot(
  all.equal(
    list(c("a", "b"), c("x", "y")),
    strsplit(c("a,b", "x,y"), ",")) == TRUE)

which makes it useful for operating on columns of SQL output:

| id | concatenated_field |
|----|--------------------|
|  1 |    5362,395,9000,7 |
|  2 |       319,75624,63 |
           (etc.)

d <- data.frame(
  id = c(1, 2),
  concatenated_field = c("5362,395,9000,7", "319,75624,63"))
d$split_field <- strsplit(d$concatenated_field, ",")
sapply(d, class)
#             id concatenated_field        split_field
#      "numeric"        "character"             "list"
d$split_field[[1]]
# [1] "5362" "395"  "9000" "7"

Alternatively, if you're reading in one big stream of comma-separated data, you can use scan:

data_vec <- scan(
  what = 0,  # arcane way to say "expect numeric input"
  sep = ",",
  text = "1,2,3,4,5,6,7,8,9,10")
stopifnot(all.equal(data_vec, 1:10) == TRUE)

scan is more heavy-duty than strsplit and can handle more complicated inputs as well, such as data with quoted fields:

weird_data <- scan(what="", sep=",", text='marvin,ruby,"joe,joseph",dean')
print(weird_data)
# [1] "marvin"     "ruby"       "joe,joseph" "dean"

If you are really really sure you need to be able to accept and evaluate R code passed as an input (this can be VERY DANGEROUS since it means you will be executing arbitrary unverified R code), you can use

r_code_string <- 'c("a", "b"), c("x", "y"))'
stopifnot(
  all.equal(
    c("a", "b"), c("x", "y")),
    eval(parse(r_code_string))) == TRUE)

parse converts raw text into an unevaluated "expression", which is a representation of R code in the form of a special R object, eval passes the expression to the interpreter for execution.

As for noquote, it doesn't do what you think it does. It doesn't actually modify the string, it just adds a flag to the variable so that it will print without quotation marks. You can emulate this behavior with print(..., quote = FALSE).