问:
Java - empty orc file
I am trying to write orc files using orc-core to be later read by hive.

The files being written have the correct number of rows, but there's no content in the columns. I can see that both trying to read the file with a select query in hive, and both with hive --orcfiledump -d.

I tried the example provided in the guide, which writes two long type columns, and the file produced is correctly read by hive. I suspect this has to do with the fact that I am writing instead string columns, but I still cannot make it work.

That's how I am currently writing the file:

```<code>    //  File schema
    String outputFormat = "struct<";
    for(int i=0;i<outputSchema.length;i++){
        outputFormat+=outputSchema[i]+":string,";
    }
    outputFormat+="lastRecordHash:string,currentHash:string>";
    TypeDescription orcSchema = TypeDescription.fromString(outputFormat);

    //  Initializes buffers
    VectorizedRowBatch batch = orcSchema.createRowBatch();
    ArrayList<BytesColumnVector> orcBuffers = new ArrayList<>(numFields+2);
    for(int i=0;i<numFields+2;i++){
        BytesColumnVector bcv = (BytesColumnVector) batch.cols[i];
        orcBuffers.add(i, bcv);
    }

    ...

    //  Initializes writer
    Writer writer=null;
    try{
        writer = OrcFile.createWriter(new Path(hdfsUri+outputPath), OrcFile.writerOptions(conf).setSchema(orcSchema));
        partitionCounter++;
    }
    catch(IOException e){
        log.error("Cannot open hdfs file. Reason: "+e.getMessage());
        session.transfer(flowfile, hdfsFailure);
        return;
    }

    //  Writes content
    String[] records = ...

    for(int i=0;i<records.length;i++){
        fields = records[i].split(fieldSeparator);

        int row=batch.size++;

        //  Filling the orc buffers
        for(int j=0;j<numFields;j++){
            orcBuffers.get(j).vector[row] = fields[j].getBytes();
            hashDigest.append(fields[j]);
        }
        if (batch.size == batch.getMaxSize()) {
            try{
                writer.addRowBatch(batch);
                batch.reset();
            }
            catch(IOException e){
                log.error("Cannot write to hdfs. Reason: "+e.getMessage());
                return;
            }
        }
    }
    if (batch.size != 0) {
        try{
            writer.addRowBatch(batch);
            batch.reset();
        }
        catch(IOException e){
            log.error("Cannot write to hdfs. Reason: "+e.getMessage());
            return;
        }
    }
    writer.close();
</code>```

Any suggestion or helpful reference is really appreciated.

Thank you all.

答:
Looks like an-in depth review of the API doc was what I needed. What I was missing:

Call initBuffer() on each BytesColumnVector in the initialization phase

Assign the value of the columns calling setVal(). This can be accomplished using also setRef(). It is documented to be the fastest of the two, but I don't know if fits my specific case, I will try it.

This is the updated code:

```<code>//  File schema
String outputFormat = "struct<";
for(int i=0;i<outputSchema.length;i++){
    outputFormat+=outputSchema[i]+":string,";
}
outputFormat+="lastRecordHash:string,currentHash:string>";
TypeDescription orcSchema = TypeDescription.fromString(outputFormat);

//  Initializes buffers
VectorizedRowBatch batch = orcSchema.createRowBatch();
ArrayList<BytesColumnVector> orcBuffers = new ArrayList<>(numFields+2);
for(int i=0;i<numFields+2;i++){
    BytesColumnVector bcv = (BytesColumnVector) batch.cols[i];
    bcv.initBuffer();
    orcBuffers.add(i, bcv);
}

...

//  Initializes writer
Writer writer=null;
try{
    writer = OrcFile.createWriter(new Path(hdfsUri+outputPath), OrcFile.writerOptions(conf).setSchema(orcSchema));
    partitionCounter++;
}
catch(IOException e){
    log.error("Cannot open hdfs file. Reason: "+e.getMessage());
    session.transfer(flowfile, hdfsFailure);
    return;
}

//  Writes content
String[] records = ...

for(int i=0;i<records.length;i++){
    fields = records[i].split(fieldSeparator);

    int row=batch.size++;

    //  Filling the orc buffers
    for(int j=0;j<numFields;j++){
        orcBuffers.get(j).setVal(row, fields[j].getBytes());
        hashDigest.append(fields[j]);
    }
    if (batch.size == batch.getMaxSize()) {
        try{
            writer.addRowBatch(batch);
            batch.reset();
        }
        catch(IOException e){
            log.error("Cannot write to hdfs. Reason: "+e.getMessage());
            return;
        }
    }
}
if (batch.size != 0) {
    try{
        writer.addRowBatch(batch);
        batch.reset();
    }
    catch(IOException e){
        log.error("Cannot write to hdfs. Reason: "+e.getMessage());
        return;
    }
}
writer.close();
</code>```

Title: Java - empty orc file

Body:
I am trying to write orc files using orc-core to be later read by hive.

The files being written have the correct number of rows, but there's no content in the columns. I can see that both trying to read the file with a select query in hive, and both with hive --orcfiledump -d.

I tried the example provided in the guide, which writes two long type columns, and the file produced is correctly read by hive. I suspect this has to do with the fact that I am writing instead string columns, but I still cannot make it work.

That's how I am currently writing the file:

    //  File schema
    String outputFormat = "struct<";
    for(int i=0;i<outputSchema.length;i++){
        outputFormat+=outputSchema[i]+":string,";
    }
    outputFormat+="lastRecordHash:string,currentHash:string>";
    TypeDescription orcSchema = TypeDescription.fromString(outputFormat);

    //  Initializes buffers
    VectorizedRowBatch batch = orcSchema.createRowBatch();
    ArrayList<BytesColumnVector> orcBuffers = new ArrayList<>(numFields+2);
    for(int i=0;i<numFields+2;i++){
        BytesColumnVector bcv = (BytesColumnVector) batch.cols[i];
        orcBuffers.add(i, bcv);
    }

    ...

    //  Initializes writer
    Writer writer=null;
    try{
        writer = OrcFile.createWriter(new Path(hdfsUri+outputPath), OrcFile.writerOptions(conf).setSchema(orcSchema));
        partitionCounter++;
    }
    catch(IOException e){
        log.error("Cannot open hdfs file. Reason: "+e.getMessage());
        session.transfer(flowfile, hdfsFailure);
        return;
    }

    //  Writes content
    String[] records = ...

    for(int i=0;i<records.length;i++){
        fields = records[i].split(fieldSeparator);

        int row=batch.size++;

        //  Filling the orc buffers
        for(int j=0;j<numFields;j++){
            orcBuffers.get(j).vector[row] = fields[j].getBytes();
            hashDigest.append(fields[j]);
        }
        if (batch.size == batch.getMaxSize()) {
            try{
                writer.addRowBatch(batch);
                batch.reset();
            }
            catch(IOException e){
                log.error("Cannot write to hdfs. Reason: "+e.getMessage());
                return;
            }
        }
    }
    if (batch.size != 0) {
        try{
            writer.addRowBatch(batch);
            batch.reset();
        }
        catch(IOException e){
            log.error("Cannot write to hdfs. Reason: "+e.getMessage());
            return;
        }
    }
    writer.close();

Any suggestion or helpful reference is really appreciated.

Thank you all.

Body:
Looks like an-in depth review of the API doc was what I needed. What I was missing:

Call initBuffer() on each BytesColumnVector in the initialization phase

Assign the value of the columns calling setVal(). This can be accomplished using also setRef(). It is documented to be the fastest of the two, but I don't know if fits my specific case, I will try it.

This is the updated code:

//  File schema
String outputFormat = "struct<";
for(int i=0;i<outputSchema.length;i++){
    outputFormat+=outputSchema[i]+":string,";
}
outputFormat+="lastRecordHash:string,currentHash:string>";
TypeDescription orcSchema = TypeDescription.fromString(outputFormat);

//  Initializes buffers
VectorizedRowBatch batch = orcSchema.createRowBatch();
ArrayList<BytesColumnVector> orcBuffers = new ArrayList<>(numFields+2);
for(int i=0;i<numFields+2;i++){
    BytesColumnVector bcv = (BytesColumnVector) batch.cols[i];
    bcv.initBuffer();
    orcBuffers.add(i, bcv);
}

...

//  Initializes writer
Writer writer=null;
try{
    writer = OrcFile.createWriter(new Path(hdfsUri+outputPath), OrcFile.writerOptions(conf).setSchema(orcSchema));
    partitionCounter++;
}
catch(IOException e){
    log.error("Cannot open hdfs file. Reason: "+e.getMessage());
    session.transfer(flowfile, hdfsFailure);
    return;
}

//  Writes content
String[] records = ...

for(int i=0;i<records.length;i++){
    fields = records[i].split(fieldSeparator);

    int row=batch.size++;

    //  Filling the orc buffers
    for(int j=0;j<numFields;j++){
        orcBuffers.get(j).setVal(row, fields[j].getBytes());
        hashDigest.append(fields[j]);
    }
    if (batch.size == batch.getMaxSize()) {
        try{
            writer.addRowBatch(batch);
            batch.reset();
        }
        catch(IOException e){
            log.error("Cannot write to hdfs. Reason: "+e.getMessage());
            return;
        }
    }
}
if (batch.size != 0) {
    try{
        writer.addRowBatch(batch);
        batch.reset();
    }
    catch(IOException e){
        log.error("Cannot write to hdfs. Reason: "+e.getMessage());
        return;
    }
}
writer.close();


来源: stackexchange

问:
windows form c# ftp uploader
I'm having a problem using c# to upload files to an ftp server.

The window form opens but when I click on the upload button nothing happens.
I created a structure for the ftp logging information and the file to upload.
I think it's the do_work function where the problem is, but I can't seem to find it.

```<code>struct FtpSetting
{
    public string Server { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FileName { get; set; }
    public string Fullname { get; set; }
}

FtpSetting inputParameter;

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string filename = ((FtpSetting)e.Argument).FileName;
    string fullname = ((FtpSetting)e.Argument).Fullname;
    string username = ((FtpSetting)e.Argument).Username;
    string password = ((FtpSetting)e.Argument).Password;
    string server = ((FtpSetting)e.Argument).Server;
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}",server,filename)));
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(username, password);
    Stream ftpStream = request.GetRequestStream();
    FileStream fs = File.OpenRead(fullname);
    byte[] buffer = new byte[1024];
    double total = (double)fs.Length ;
    int byteRead = 0;
    double read = 0;
    do
    {
        if (!backgroundWorker.CancellationPending)
        {
            byteRead = fs.Read(buffer, 0, 1024);
            ftpStream.Write(buffer, 0, byteRead);
            read += (double)byteRead;
            double pourcentage = read / total * 100;
            backgroundWorker.ReportProgress((int)pourcentage);
        }

    } while (byteRead != 0);
    fs.Close();
    ftpStream.Close();

}
</code>```

答:
Try something like this</p>

```<code>class Test
    {
        public Test()
        {
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
            backgroundWorker.RunWorkerAsync();
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: windows form c# ftp uploader

Body:
I'm having a problem using c# to upload files to an ftp server.

The window form opens but when I click on the upload button nothing happens.
I created a structure for the ftp logging information and the file to upload.
I think it's the do_work function where the problem is, but I can't seem to find it.

struct FtpSetting
{
    public string Server { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FileName { get; set; }
    public string Fullname { get; set; }
}

FtpSetting inputParameter;

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string filename = ((FtpSetting)e.Argument).FileName;
    string fullname = ((FtpSetting)e.Argument).Fullname;
    string username = ((FtpSetting)e.Argument).Username;
    string password = ((FtpSetting)e.Argument).Password;
    string server = ((FtpSetting)e.Argument).Server;
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}",server,filename)));
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(username, password);
    Stream ftpStream = request.GetRequestStream();
    FileStream fs = File.OpenRead(fullname);
    byte[] buffer = new byte[1024];
    double total = (double)fs.Length ;
    int byteRead = 0;
    double read = 0;
    do
    {
        if (!backgroundWorker.CancellationPending)
        {
            byteRead = fs.Read(buffer, 0, 1024);
            ftpStream.Write(buffer, 0, byteRead);
            read += (double)byteRead;
            double pourcentage = read / total * 100;
            backgroundWorker.ReportProgress((int)pourcentage);
        }

    } while (byteRead != 0);
    fs.Close();
    ftpStream.Close();

}

Body:
Try something like this

class Test
    {
        public Test()
        {
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
            backgroundWorker.RunWorkerAsync();
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
        }
    }


问:
Fluent NHibernate Upgrade to NH3.0 alpha
Hy
We want to use the latest alpha version of NHibernate. Unfortunately the latest fluent nhibernate release is built for 2.1 GA. When do you plan to upgrade to latest NH? Is there a source tree which I can fork to build the latest version from?

Daniel

答: You could try to download their latest binaries from Git here and build against NH3 assemblies (it includes a project file where you would just need to update references from 2.1 to 3).. but probably they already did that in "Unstable/future binaries".</p>

ContentLicense: CC BY-SA 2.5


问:
Accessing Table without primary Key -Spring data jpa
I am using spring data jpa and I have to port an existing application to Spring boot.

I am encountered with the database table which does not have the primary key column. How can I write the entity without @Id annotation.

If am trying, I am getting error :

```<code>Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.example.domain.Employee
    at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:243) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3845) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3799) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1412) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    ... 29 common frames omitted
</code>```

Is there any way to use this without modifying the existing database?

答:
yes, using @IdClass annotation.  </p>

```<code>@Entity
@IdClass(EmployeeKey.class)
public class Employee {
   @Id
   private int id;
   @Id
   private int departmendId;

}

public class EmployeeKey implements Serializable {
   private int id;
   private int departmendId;
}

public interface EmployeeRepository extends JpaRepository<Employee, EmployeeKey>,{}
</code>```

Body:
I am using spring data jpa and I have to port an existing application to Spring boot.

I am encountered with the database table which does not have the primary key column. How can I write the entity without @Id annotation.

If am trying, I am getting error :

Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.example.domain.Employee
    at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:243) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3845) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3799) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1412) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    ... 29 common frames omitted

Is there any way to use this without modifying the existing database?

Body:
yes, using @IdClass annotation.

@Entity
@IdClass(EmployeeKey.class)
public class Employee {
   @Id
   private int id;
   @Id
   private int departmendId;

}

public class EmployeeKey implements Serializable {
   private int id;
   private int departmendId;
}

public interface EmployeeRepository extends JpaRepository<Employee, EmployeeKey>,{}


问:
Call function after function return
i have the folowing situation:
I have a function "foo" and want the the foo-return the function bar sould be call. Here a little example what i mean:

```<code>function foo() {
     echo "FOO";
     return "1";
}
function bar() {
    echo "BAR";
}
echo foo();
</code>```

And the output should be display this

FOO

  1

  BAR

All this in PHP!!!
Have anyone a idea how to can realise this WITHOUT call bar() in after each foo()?

答:
You only need to return the call of the function like so:</p>

```<code>function foo() {
    echo "FOO";
    return bar();
}
</code>```

Title: Call function after function return

Body:
i have the folowing situation:
I have a function "foo" and want the the foo-return the function bar sould be call. Here a little example what i mean:

function foo() {
     echo "FOO";
     return "1";
}
function bar() {
    echo "BAR";
}
echo foo();

And the output should be display this

FOO

  1

  BAR

All this in PHP!!!
Have anyone a idea how to can realise this WITHOUT call bar() in after each foo()?

Body:
You only need to return the call of the function like so:

function foo() {
    echo "FOO";
    return bar();
}


问:
meaning of RuntimeException("Stub!") in Android
I was surfing in Android code because I wanted to see what is into Activity.finish() method.

I just wanted to have the confirmation that in Activity.finish() there would be a call to onDestroy() method.

But what I found in this method (and in many others) was:

```<code>public void finish() {
    throw new RuntimeException("Stub!");
}
</code>```

So WHERE Can I find the code that really destroys the Activity?
Thanks!

答: You are checking in .class not .java file.</p>

Body:
I was surfing in Android code because I wanted to see what is into Activity.finish() method.

I just wanted to have the confirmation that in Activity.finish() there would be a call to onDestroy() method.

But what I found in this method (and in many others) was:

public void finish() {
    throw new RuntimeException("Stub!");
}

So WHERE Can I find the code that really destroys the Activity?
Thanks!


问:
How to assign selected date Value in Selected angular 2 ngModel?
I have three date fields in my form. I'm using jquery datepicker for that fields.
I have a code for adding the changed date in ngModel attribute. but that is for one field only.

For Example This is my Component Code

$(".date").datepicker({
  changeMonth: true,
  yearRange: "1:100",
  format: 'mm/dd/yyyy',
  changeYear: true
}).on('change', e => this.SelectedData.Misc1 = e.target.value);
```

<p>This is my html code</p>

<pre class="lang-html prettyprint-override"><code><input type="text" class="form-control date" id="Dat_Misc1" name="Misc1" [(ngModel)]="SelectedData.Misc1">
<input type="text" class="form-control date" id="Dat_Misc2" name="Misc2" [(ngModel)]="SelectedData.Misc2">
<input type="text" class="form-control date" id="Dat_Misc3" name="Misc3" [(ngModel)]="SelectedData.Misc3">
</code>```

Here the change function assigning the value in one property only. But I need that one as dynamic. Whatever Date Field I select that should fetch the date value on that ngModel.

Please help me. Thanks in Advance..!

答:
Use jquery on input alongside with the on change event</p>

```<code>$(".date").datepicker({
  changeMonth: true,
  yearRange: "1:100",
  format: 'mm/dd/yyyy',
  changeYear: true
}).on('input change', e => this.SelectedData.Misc1 = e.target.value);
</code>```

Body:
I have three date fields in my form. I'm using jquery datepicker for that fields.
I have a code for adding the changed date in ngModel attribute. but that is for one field only.

For Example This is my Component Code

$(".date").datepicker({
  changeMonth: true,
  yearRange: "1:100",
  format: 'mm/dd/yyyy',
  changeYear: true
}).on('change', e => this.SelectedData.Misc1 = e.target.value);

This is my html code

<input type="text" class="form-control date" id="Dat_Misc1" name="Misc1" [(ngModel)]="SelectedData.Misc1">
<input type="text" class="form-control date" id="Dat_Misc2" name="Misc2" [(ngModel)]="SelectedData.Misc2">
<input type="text" class="form-control date" id="Dat_Misc3" name="Misc3" [(ngModel)]="SelectedData.Misc3">

Here the change function assigning the value in one property only. But I need that one as dynamic. Whatever Date Field I select that should fetch the date value on that ngModel.

Please help me. Thanks in Advance..!

Body:
Use jquery on input alongside with the on change event

$(".date").datepicker({
  changeMonth: true,
  yearRange: "1:100",
  format: 'mm/dd/yyyy',
  changeYear: true
}).on('input change', e => this.SelectedData.Misc1 = e.target.value);


问:
C# adding random values "string" to a column in database
I have been adding random values to my database using the following Statement in visual studio and it works just fine for two values.

```<code>  Random rd;
  TextBox_Language.Text = rd.Next(2) == 0 ? "EN" : "FR";
</code>```

Now I need to have more than just two strings and I have tried the bellow Code, but that doesn't work. Any one got a hint on how to get around with it?

```<code> TextBox_Language.Text = rd.Next(3) == 0 ? "EN" : "FR" : "DE"; // doesn't work
</code>```

答:
The way you are trying to expand the conditional operator will make it unnecessarily complex. You can put the values in string array and use the randon number as index of that array to get the strings.

```<code>string []valuesArray = new string[] {"EN",  "FR", "DE"};
TextBox_Language.Text = valuesArray[rd.Next(valuesArray.Length)];
</code>```

Note: This method will allow you to given any number of element with random number. Using the List will make it even more flexible. You can add / remove any element at any time unlike array.

```<code>List<string> valuesList = new List<string> {"EN" , "FR" , "DE"};
valuesList.Add("FE"); //Added one more element
string s = valuesList[rd.Next(valuesList.Count)];
</code>```

Body:
I have been adding random values to my database using the following Statement in visual studio and it works just fine for two values.

  Random rd;
  TextBox_Language.Text = rd.Next(2) == 0 ? "EN" : "FR";

Now I need to have more than just two strings and I have tried the bellow Code, but that doesn't work. Any one got a hint on how to get around with it?

 TextBox_Language.Text = rd.Next(3) == 0 ? "EN" : "FR" : "DE"; // doesn't work

Body:
The way you are trying to expand the conditional operator will make it unnecessarily complex. You can put the values in string array and use the randon number as index of that array to get the strings.

string []valuesArray = new string[] {"EN",  "FR", "DE"};
TextBox_Language.Text = valuesArray[rd.Next(valuesArray.Length)];

Note: This method will allow you to given any number of element with random number. Using the List will make it even more flexible. You can add / remove any element at any time unlike array.

List<string> valuesList = new List<string> {"EN" , "FR" , "DE"};
valuesList.Add("FE"); //Added one more element
string s = valuesList[rd.Next(valuesList.Count)];


问:
DOT Language Parser
Does anyone know of a DOT Language (or other GraphViz-ish format)  Parser for .NET?
I have been experimenting with QuickGraph, but it seems to only support serialization, and not parsing from a stream/string/file. </p>

答: Well you could use a XML-based format like GraphML which per se does not require its own parser, it also has xsd's specified , so its rather trivial to add to .NET</p>

Title: DOT Language Parser


问:
filter_var_array with floats causes too many decimal places in result
I have a problem with the filter_var_array function, in particular with the 'FILTER_VALIDATE_FLOAT' flag, which returns me floats with way too many decimal places

Code first:

```<code>if (property_exists($this->rawRequest, $varName)) {
    $res = filter_var_array($this->rawRequest->$varName, FILTER_VALIDATE_FLOAT);
}
</code>```

This is my code, where I validate parameters that I received from a client via JSON

The rawRequest is a stdClass, like the following (printed with var_export):

```<code>stdClass::__set_state(
     array(
        'Action' => 'CreateObject',
        'Template' => 'none',
        'LatLng' => array (
            0 => '48.14914653539144',
            1 => '11.577623201171932',
        )
)
</code>```

After the 'LatLng' parameter was filtered with filter_var_array, the result looks like the following:

```<code>'LatLng' => array (
    0 => 48.149146535391433732957206666469573974609375,
    1 => 11.5776232011719315551090403459966182708740234375,
)
</code>```

Why does this happen?

I even can not fix this with round(), typecasting to float, to string and back to float, I tried to subtract 0.00000001 and then adding 0.00000001 again, nothing helps

UPDATE:

I wrote following little test script on the same machine, same apache server:

```<code><?php

$test = '48.158308230848306';
$test2 = (float) $test;
$test3 = floatval($test);

echo($test2);
echo('<br />');
echo($test3);
exit(0);
</code>```

output is here:

```<code>48.158308230848
48.158308230848
</code>```

THAT is what I expect

I retested it with my prod code and used floatval() and typecasting to float, but it DID NOT work. I don't know, the only difference is that in the prod code the input comes as json and I parse it with the following code:

```<code>json_decode(file_get_contents('php://input'))
</code>```

答:
So, I finally found the answer to my problem

The problem was never the filter_var_array() function, actually, the problem occurred far earlier.

After retrieving the POST parameters via file_get_contents("php://input") everything is still fine.

But when I decode the returned string with json_decode(), the float values are serialized in this process, resulting in the higher precision.

I found two ways to "solve" this:

Change the "serialize_precision" parameter in the php.ini (mine was per default 100, setting it to the same as my "precision" parameter was successful)

I DO NOT RECOMMEND this approach, since the effects of changing this parameter might be devastating somewhere else

Enclose the float in the request in quotes

So change in your JSON {"test": 48.58495135846} to {"test": "48.58495135846"}

This prevents the serialization of the float, as it is effectively a string now

Hope this helps someone else, maybe this is already common knowledge, but I was tearing my hair out about this.

Body:
I have a problem with the filter_var_array function, in particular with the 'FILTER_VALIDATE_FLOAT' flag, which returns me floats with way too many decimal places

Code first:

if (property_exists($this->rawRequest, $varName)) {
    $res = filter_var_array($this->rawRequest->$varName, FILTER_VALIDATE_FLOAT);
}

This is my code, where I validate parameters that I received from a client via JSON

The rawRequest is a stdClass, like the following (printed with var_export):

stdClass::__set_state(
     array(
        'Action' => 'CreateObject',
        'Template' => 'none',
        'LatLng' => array (
            0 => '48.14914653539144',
            1 => '11.577623201171932',
        )
)

After the 'LatLng' parameter was filtered with filter_var_array, the result looks like the following:

'LatLng' => array (
    0 => 48.149146535391433732957206666469573974609375,
    1 => 11.5776232011719315551090403459966182708740234375,
)

Why does this happen?

I even can not fix this with round(), typecasting to float, to string and back to float, I tried to subtract 0.00000001 and then adding 0.00000001 again, nothing helps

UPDATE:

I wrote following little test script on the same machine, same apache server:

<?php

$test = '48.158308230848306';
$test2 = (float) $test;
$test3 = floatval($test);

echo($test2);
echo('
');
echo($test3);
exit(0);

output is here:

48.158308230848
48.158308230848

THAT is what I expect

I retested it with my prod code and used floatval() and typecasting to float, but it DID NOT work. I don't know, the only difference is that in the prod code the input comes as json and I parse it with the following code:

json_decode(file_get_contents('php://input'))


问:
Find size of an array in Perl
I seem to have come across several different ways to find the size of an array. What is the difference between these three methods?</p>

```<code>my @arr = (2);
print scalar @arr; # First way to print array size

print $#arr; # Second way to print array size

my $arrSize = @arr;
print $arrSize; # Third way to print array size
</code>```

答:
To find the size of an array use the scalar keyword:

```<code>print scalar @array;
</code>```

To find out the last index of an array there is $# (Perl default variable). It gives the last index of an array. As an array starts from 0, we get the size of array by adding one to $#:

```<code>print "$#array+1";
</code>```

Example:

```<code>my @a = qw(1 3 5);
print scalar @a, "\n";
print $#a+1, "\n";
</code>```

Output:

```<code>3

3
</code>```

Title: Find size of an array in Perl

Body:
I seem to have come across several different ways to find the size of an array. What is the difference between these three methods?

my @arr = (2);
print scalar @arr; # First way to print array size

print $#arr; # Second way to print array size

my $arrSize = @arr;
print $arrSize; # Third way to print array size

Body:
To find the size of an array use the scalar keyword:

print scalar @array;

To find out the last index of an array there is $# (Perl default variable). It gives the last index of an array. As an array starts from 0, we get the size of array by adding one to $#:

print "$#array+1";

Example:

my @a = qw(1 3 5);
print scalar @a, "\n";
print $#a+1, "\n";

Output:

3

3


问:
Transform array by cutting in half but extend elements
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

```<code># source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]
</code>```

How would you achieve it?

答:
Just one more solution:</p>

```<code>a.each_slice(a.size / 2).to_a.transpose.map(&:flatten)
#=> [[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]
</code>```

Body:
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

# source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]

How would you achieve it?

Body:
Just one more solution:

a.each_slice(a.size / 2).to_a.transpose.map(&:flatten)
#=> [[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]


问:
Ploting pie chart in django by highcharts
I am trying to plot pie chart in django.My Django model "Results" has two filed like below:

```<code>+--------+------------+
| result |    date    |
+--------+------------+
| passed | 2017-03-30 |
| passed | 2017-02-30 |
| passed | 2017-03-30 |
| failed | 2017-03-30 |
| failed | 2017-03-29 |
| passed | 2017-03-29 |
| passed | 2017-03-30 |
-----------------------
</code>```

I would like to count following way and show this in pie chart as total number of passed and failed value.

2017-03-30 passed-4 and failed-1

chart_test.html:

```<code>{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>
    <script type="text/javascript">
        $(function () {
        $('#chart_container').highcharts({
        chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
    },
    title: {
        text: 'hello'
    },
    tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                style: {
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                }
            }
        }
    },
    series: [{
        name: 'Brands',
        colorByPoint: true,
        data: [
          {% for cat in responses_pie %}
            [
            {{ cat.count }}
            ],
            {% endfor %}
            ]
    }]
        });
        });
    </script>
    <div id="chart_container" style="height: 300px"></div>
</body>
{% endblock %}
</code>```

views.py:

```<code>def chart_test(request):
    responses_pie =  Results.objects.filter(date=date.today()).annotate(count=Count('result'))
    return render(request,'mbr/chart_test.html',{'responses_pie': responses_pie})
</code>```

答:
I suggest to use an external app (integration with Highcharts available).
I suggest to use chartkick https://github.com/mher/chartkick.py.
Just pass to the view a list of tuples and let the app render the chart.
example:

```<code>browser_stats = [('Chrome', 52.9), ('Firefox', 27.7), ('Opera', 1.6),
                 ('Internet Explorer', 12.6), ('Safari', 4)]
</code>```

in your template use:

```<code>{% pie_chart browser_stats %}
</code>```

here the result http://mher.github.io/chartkick.py/?type=highcharts

Less work best performance

:)

Body:
I am trying to plot pie chart in django.My Django model "Results" has two filed like below:

+--------+------------+
| result |    date    |
+--------+------------+
| passed | 2017-03-30 |
| passed | 2017-02-30 |
| passed | 2017-03-30 |
| failed | 2017-03-30 |
| failed | 2017-03-29 |
| passed | 2017-03-29 |
| passed | 2017-03-30 |
-----------------------

I would like to count following way and show this in pie chart as total number of passed and failed value.

2017-03-30 passed-4 and failed-1

chart_test.html:

{% extends "base.html" %}
{% load staticfiles %}
{% block content %}

{% endblock %}

views.py:

def chart_test(request):
    responses_pie =  Results.objects.filter(date=date.today()).annotate(count=Count('result'))
    return render(request,'mbr/chart_test.html',{'responses_pie': responses_pie})

Body:
I suggest to use an external app (integration with Highcharts available).
I suggest to use chartkick https://github.com/mher/chartkick.py.
Just pass to the view a list of tuples and let the app render the chart.
example:

browser_stats = [('Chrome', 52.9), ('Firefox', 27.7), ('Opera', 1.6),
                 ('Internet Explorer', 12.6), ('Safari', 4)]

in your template use:

{% pie_chart browser_stats %}

here the result http://mher.github.io/chartkick.py/?type=highcharts

Less work best performance

:)


问:
Client Server library for uploading files on C#?
What client-server library/framework on C# do you know for sending files? I need to create custom tool for uploading files to server; But i need something very simple. It will be very tiny utility;) I guess such library must wrap work with sockets because i cannot upload files using path like "\\ip\store".

Thank you for any advice!!!

答: Any reason not to just use HTTP and WebClient.UploadFile() in the client? The handling of the server side will depend on what you use to implement it, but HttpRequest.Files is likely to be useful.


问:
Updating controller data doesnt update the view - Angular JS - Ionic
I have this controller :

```<code>.controller("mainctrl",function($scope,$state){
        var self = this;

        var usuario = window.localStorage.getItem('usuario');
        this.msjs=[];

        var res = window.localStorage.getItem(usuario+'_msjs');
        if(res===null)
        {
            this.msjs=[];
        }
        else{
            this.msjs=JSON.parse(res);
        }

        $scope.$on('newMessageReceived', function(e, msg) {
            //alert('message received:'+msg);
            self.msjs.push(msg);
            alert('mensaje recibido');
            alert(JSON.stringify(self.msjs));

            window.localStorage.setItem(usuario+'_msjs',JSON.stringify(self.msjs));
            $state.reload();

        });
  }
</code>```

And the view:

```<code><ion-view ng-controller="mainctrl as m" >
             <ion-nav-buttons side="right">
                 <button class="button" ng-click="m.logout()">Logout</button>
             </ion-nav-buttons>
             <ion-content id="msjcontent">
                 <h1 class="button-positive" id="log">Mensajes</h1>
                 <div class='card' ng-repeat="msj in m.msjs track by $id($index)">
                     {{msj}}
                 </div>

             </ion-content>
</ion-view>
</code>```

When the $scope receives the event it pushes a new element in the  'msjs' array.
The view doesnt update the data. I had to put $state.reload() to refresh the $state (ui-router from Angular-Ionic) and watch the changes. This refresh is giving me problems such as multiple copies of $scopes (1 for each $state.reload() ). i've already tried with $scope.apply() and it didnt work. I think the problem may be  Ionic/angular ui-router stuff.

I want to know a better way to bind the msjs array to the view without refresh the $state.

Thanks.

答:
.state(url: '/url', controller: Ctl,  templateUrl: 'template.html', cache: false)

cache: false ==> solved my problem ^^

Body:
I have this controller :

.controller("mainctrl",function($scope,$state){
        var self = this;

        var usuario = window.localStorage.getItem('usuario');
        this.msjs=[];

        var res = window.localStorage.getItem(usuario+'_msjs');
        if(res===null)
        {
            this.msjs=[];
        }
        else{
            this.msjs=JSON.parse(res);
        }

        $scope.$on('newMessageReceived', function(e, msg) {
            //alert('message received:'+msg);
            self.msjs.push(msg);
            alert('mensaje recibido');
            alert(JSON.stringify(self.msjs));

            window.localStorage.setItem(usuario+'_msjs',JSON.stringify(self.msjs));
            $state.reload();

        });
  }

And the view:

<ion-view ng-controller="mainctrl as m" >
             <ion-nav-buttons side="right">
                 <button class="button" ng-click="m.logout()">Logout</button>
             </ion-nav-buttons>
             <ion-content id="msjcontent">

Mensajes

                     {{msj}}

             </ion-content>
</ion-view>

When the $scope receives the event it pushes a new element in the  'msjs' array.
The view doesnt update the data. I had to put $state.reload() to refresh the $state (ui-router from Angular-Ionic) and watch the changes. This refresh is giving me problems such as multiple copies of $scopes (1 for each $state.reload() ). i've already tried with $scope.apply() and it didnt work. I think the problem may be  Ionic/angular ui-router stuff.

I want to know a better way to bind the msjs array to the view without refresh the $state.

Thanks.


问:
Difference between hadoop fs -put and hadoop distcp
We are going to do the ingestion phase in our data lake project and I have mostly used hadoop fs -put throughout my Hadoop developer experience. So what's the difference with hadoop distcp and the difference in usage?

答:
Distcp is a special tool used for copying the data from one cluster to another. Basically you usually copy from one hdfs to hdfs, but not for local file system. Another very important thing is that the process in done as a mapreduce job with 0 reduce task which makes it more fast due to the distribution of operations. It expands a list of files and directories into input to map tasks, each of which will copy a partition of the files specified in the source list

hdfs put - copies the data from local system to hdfs. Uses hdfs client for this behind the scene and does all the work sequentially through accessing NameNode and Datanodes. Does not create MapReduce jobs for processing the data.


问:
Add Whatsapp function to website, like sms, tel
I have a website that a lot of people view on mobile.
I have link for : Call and SMS and I want to add one for Whatsapp, so a user can click the whatsapp link I create and start a conversation with me.

If this is possible can someone point me in the right direction on how?

答:
This is possible by creating the following link:

whatsapp://send?text=Hello this has been opened from the browser&phone=+PHONENUMBER&abid=+PHONENUMBER

Thanks to:

https://forum.ionicframework.com/t/open-whatsapp-intent-with-msg-specific-contact/73903/4

I have tested this on iOS, Windows Phone and Android


问:
jQuery filter function is not showing exact match :(

My problem is something like this,

I am using filter function to show the matched elements(LI)in tree,its working fine but its showing all li elements which starts from passed string,for example

if i passed "Application" to filter function,then it's showing me all li, which text start from "Application"

```<code>function callme(filterData){
$("ul.treeview").find("li").hide();
if(filterData.indexOf("|")!=-1){
    var filterData = filterData.split("|");<br>
    for(i=0;i<filterData.length;i++){<br>
        jQuery("ul.treeview").find("li").filter(function(index) {
            return jQuery.trim($(this).text()) == filterData.trim();
        }).show();
    }<br>
}else{
    jQuery("ul.treeview").find("li").filter(function(index) {
        return jQuery.trim($(this).text()) == filterData.trim();
    }).show();<br>
}
}</code>  </p>

<p>here is my html...  </p>

<code><ul id="leftNavigation" class="treeview">
   <li>
        <ul>
      <li >
        <a href="#">Application</a><font   class="leftNavHitsFont"> - (3)</font>
      </li>
       </ul>
       <ul>
    <li >
    <a href="#">Application Notes</a><font class="leftNavHitsFont"> - (1)</font>
   </li>
      </ul>
   </li>
</ul>
</code>```

答:
Yeah, that is the definition of something containing something else.

Maybe you meant to get an exact match?

```<code>jQuery("ul.treeview").find("li").filter(function(index) {
    return jQuery.trim($(this).text()) == jQuery.trim(filterData);
}).show();
</code>```

jsFiddle example

Body:
My problem is something like this,

I am using filter function to show the matched elements(LI)in tree,its working fine but its showing all li elements which starts from passed string,for example

if i passed "Application" to filter function,then it's showing me all li, which text start from "Application"

function callme(filterData){
$("ul.treeview").find("li").hide();
if(filterData.indexOf("|")!=-1){
    var filterData = filterData.split("|");

    for(i=0;i<filterData.length;i++){

        jQuery("ul.treeview").find("li").filter(function(index) {
            return jQuery.trim($(this).text()) == filterData.trim();
        }).show();
    }

}else{
    jQuery("ul.treeview").find("li").filter(function(index) {
        return jQuery.trim($(this).text()) == filterData.trim();
    }).show();

}
}

here is my html...

        Application - (3)

    Application Notes - (1)

Body:
Yeah, that is the definition of something containing something else.

Maybe you meant to get an exact match?

jQuery("ul.treeview").find("li").filter(function(index) {
    return jQuery.trim($(this).text()) == jQuery.trim(filterData);
}).show();

jsFiddle example


问:
php sum multidimensional subarray
I want to calculate distance of array. I have multidimensional array like this

```<code>Array
(
    [0] => Array
        (
            [0] => 3136
        )

    [1] => Array
        (
            [0] => 9
        )

)
Array
(
    [0] => Array
        (
            [0] => 3025
        )

    [1] => Array
        (
            [0] => 169
        )

)
</code>```

This is my code:

```<code>function hitung(){
    $dataTest       = array(60,50);
    $dataHitung     = array();
    $dataHitung2    = array();
    $dataRuspini    = $this->m_knn->getRuspini();
    foreach ($dataRuspini as $key => $val) {
        # code...
        // looping kolom 1 sampai 3
        for ($i=0; $i < count($val)-1; $i++) {
            # code...
            // looping setiap baris per kolomnya
            for ($j=0; $j < count($val[$i]); $j++) {
                # code...
                // data test dikurangi data training
                $dataHitung[$i][$j] = $dataTest[$i] - $val[$i];
                // hasil pengurangan dikuadratkan
                $dataHitung[$i][$j] = pow($dataHitung[$i][$j], 2);
                $dataHitung2[$i][$j] = $dataHitung[$i][$j];
            }

        }
        //var_dump(array_sum($dataHitung2));
        echo "```";
        print_r($dataHitung2);

    }
```

<p>How tu sum each row of array ?</p>

```3136 + 9
3025 + 169
```

Please help me :(

答:
Try this,

```<code>$b = array_map(function($item){
     return array_sum($item);
 }, $dataRuspini);
print_r($b);
</code>```

array_map - Applies the callback to the elements of the given arrays

array_sum - Calculate the sum of values in an array

Title: php sum multidimensional subarray

Body:
I want to calculate distance of array. I have multidimensional array like this

Array
(
    [0] => Array
        (
            [0] => 3136
        )

    [1] => Array
        (
            [0] => 9
        )

)
Array
(
    [0] => Array
        (
            [0] => 3025
        )

    [1] => Array
        (
            [0] => 169
        )

)

This is my code:

function hitung(){
    $dataTest       = array(60,50);
    $dataHitung     = array();
    $dataHitung2    = array();
    $dataRuspini    = $this->m_knn->getRuspini();
    foreach ($dataRuspini as $key => $val) {
        # code...
        // looping kolom 1 sampai 3
        for ($i=0; $i < count($val)-1; $i++) {
            # code...
            // looping setiap baris per kolomnya
            for ($j=0; $j < count($val[$i]); $j++) {
                # code...
                // data test dikurangi data training
                $dataHitung[$i][$j] = $dataTest[$i] - $val[$i];
                // hasil pengurangan dikuadratkan
                $dataHitung[$i][$j] = pow($dataHitung[$i][$j], 2);
                $dataHitung2[$i][$j] = $dataHitung[$i][$j];
            }

        }
        //var_dump(array_sum($dataHitung2));
        echo "
";
        print_r($dataHitung2);

    }

How tu sum each row of array ?

3136 + 9
3025 + 169

Please help me :(

Body:
Try this,

$b = array_map(function($item){
     return array_sum($item);
 }, $dataRuspini);
print_r($b);

array_map - Applies the callback to the elements of the given arrays

array_sum - Calculate the sum of values in an array


问:
Find name using like operator in SQL Server
I have table with columns

```<code>surname    forename
Dane jr    Carlo
Dane Br    Carlo
Daniel     Gerard
</code>```

forename should be same and surname partially same (means string before space  should be same after space should not same)

Output like

```<code>surname    forename
Dane jr    Carlo
Dane Br    Carlo
</code>```

答:
Another option:

```<code>Declare @tbl table(surname varchar(30),forename varchar(30))
insert into @tbl(surname,forename)values
('Dane jr','Carlo'),
('Dane Br','Carlo'),
('Daniel','Gerard')

select a.surname,forename from
(select sdx,rcount,surname,forename from
(select soundex(surname) as sdx,row_number() over(partition by soundex(surname) order by soundex(surname)) as rcount, surname,forename from @tbl) as a
) as a
right join

(select sdx,rcount,surname from
(select soundex(surname) as sdx,row_number() over(partition by soundex(surname) order by soundex(surname)) as rcount, surname from @tbl) as a
where rcount >1)  as b
on a.sdx = b.sdx
</code>```

Output:

```<code>Dane jr Carlo
Dane Br Carlo
</code>```

Body:
I have table with columns

surname    forename
Dane jr    Carlo
Dane Br    Carlo
Daniel     Gerard

forename should be same and surname partially same (means string before space  should be same after space should not same)

Output like

surname    forename
Dane jr    Carlo
Dane Br    Carlo

Body:
Another option:

Declare @tbl table(surname varchar(30),forename varchar(30))
insert into @tbl(surname,forename)values
('Dane jr','Carlo'),
('Dane Br','Carlo'),
('Daniel','Gerard')

select a.surname,forename from
(select sdx,rcount,surname,forename from
(select soundex(surname) as sdx,row_number() over(partition by soundex(surname) order by soundex(surname)) as rcount, surname,forename from @tbl) as a
) as a
right join

(select sdx,rcount,surname from
(select soundex(surname) as sdx,row_number() over(partition by soundex(surname) order by soundex(surname)) as rcount, surname from @tbl) as a
where rcount >1)  as b
on a.sdx = b.sdx

Output:

Dane jr Carlo
Dane Br Carlo


问:
django-rosetta file is read only
I am getting the following message at the top of my rosetta admin page:

```<code>File is read-only: download the file when done editing!
</code>```

This never used to be there before, and I'm unsure at what point this started showing up since we've had a lot of dev changes recently and haven't had any text to translate. The outcome is that any translation changes we make do not take effect in the admin section after we click save and translate next block (ie. These changes do not save at all). Which kinda makes sense since the "file" is read only.

I've tried setting the .po and .mo file's permissions to 777 but the message remains. Even after resetting the server etc.

My question is: has anyone come across this issue? What file is it that is read-only? How do I set it to writeable? Or is something else at play here?

答:
As said before, you need to change the permissions.
You need to restart the server also.</p>

ContentLicense: CC BY-SA 4.0

Title: django-rosetta file is read only

Body:
I am getting the following message at the top of my rosetta admin page:

File is read-only: download the file when done editing!

This never used to be there before, and I'm unsure at what point this started showing up since we've had a lot of dev changes recently and haven't had any text to translate. The outcome is that any translation changes we make do not take effect in the admin section after we click save and translate next block (ie. These changes do not save at all). Which kinda makes sense since the "file" is read only.

I've tried setting the .po and .mo file's permissions to 777 but the message remains. Even after resetting the server etc.

My question is: has anyone come across this issue? What file is it that is read-only? How do I set it to writeable? Or is something else at play here?


问:
.write not working in Python
I'm fairly new to Python so hopefully I'm just missing something obvious here, but it has me stumped.  Snippet of my program below:

```<code>outFile = open('P4Output.txt', 'w')
outFile.write(output)
print output
print "Output saved to \"P4Output.txt\"\n"
</code>```

output prints correctly to the console, but if I go open up the file it's blank.  If I delete the file and execute my program again, the file is created but still is empty.  I used this exact same block of code in another program of mine previously and it worked, and still works.  However, if I open up Python and try something simple like:

```<code>f = open('test.txt', 'w')
f.write("test")
</code>```

Again, test.txt is created but is left blank.  What gives?

答: maybe you should use absolute path instead of relative one.</p>

Title: .write not working in Python

Body:
I'm fairly new to Python so hopefully I'm just missing something obvious here, but it has me stumped.  Snippet of my program below:

outFile = open('P4Output.txt', 'w')
outFile.write(output)
print output
print "Output saved to \"P4Output.txt\"\n"

output prints correctly to the console, but if I go open up the file it's blank.  If I delete the file and execute my program again, the file is created but still is empty.  I used this exact same block of code in another program of mine previously and it worked, and still works.  However, if I open up Python and try something simple like:

f = open('test.txt', 'w')
f.write("test")

Again, test.txt is created but is left blank.  What gives?


问:
Data mining termin "fledged"?
Please tell what is termin "full fledged KI"? As i understand it is part of data mining for text analyzing. Am i right? Some interesting and useful links will be fine!

Thank you!!!

答:
By "full fledged", he likely means "fully fledged", defined as

developed or matured to the fullest degree

of full rank or status

source: thefreedictionary.com

Not sure about KI, but possibly it means:

http://en.wikipedia.org/wiki/Knowledge_integration

Title: Data mining termin "fledged"?


问:
Special symbol in header / event title not formatted correctly
In FullCalendar, I can choose whether i'd like the title of events or the header title of the agenda week to be formatted correctly depending on if i save my index.php with UTF-8 or UTF-8 without BOM (equivalent to adding <meta charset="UTF-8"> in ).

How do I get both in the right format? I have tried adding meta tag, saving my index.php with different encoding but no matter the combination, one or the other is badly formatted.

Edit: Using notepad++ as text editor.

答:
Problem was that database content was encoded in ISO because of a ISO meta tag in the header of the webpage at a previous time.

```<code>mysql_query("SET NAMES UTF8");
</code>```

Before the database connect call solved the problem as well as a <meta charset="UTF-8"> in the header of the main webpage.

Body:
Problem was that database content was encoded in ISO because of a ISO meta tag in the header of the webpage at a previous time.

mysql_query("SET NAMES UTF8");

Before the database connect call solved the problem as well as a <meta charset="UTF-8"> in the header of the main webpage.


问:
Apache2 user (www-data) permission denied for folder owned by www-data
I am using FreeNAS and have mounted a volume onto a VM I am running. I have a silverstripe website running in this VM with everything on this volume and everything is working fine, except the web server can't access my assets folder (permission denied). phpinfo returns that the apache user is www-data. ls -la returns that the uid and gid for the assets folder and everything in it are both www-data and permissions are set to 777. I can upload files into the assets folder through the silverstripe cms (which sets perms to -rw-r--r-- if that matters), but I cannot link to anything inside the assets folder.

Any help would be great!

答: So the error was due to an incorrect build of the database, leading to file paths not being resolved. So instead of linking to the files in my assets folder, it was trying to go to the assets/ directory which is why I was getting the error. I dropped and recreated the database and the links started working correctly again. Thanks for the help anyway everyone!</p>


问:
Mysql - Comparing query result with String in Python
I would like to check whether the email returned by a query is empty. I am using the following code:

```<code>query = "select email from u_code where code = '"+code+"'"
cursor.execute(query)
result_set = cursor.fetchall()

length = cursor.rowcount
if (length==1):
   print ' result: ' + str(result_set[0]) + ' OK'
   print ' length of result: ' + str(len(result_set[0]))

   if (result_set[0] == ''):
       print("empty email")
       result = 1;
   else:
       print("email taken")
       result = 0

print "result: " + str(result)
</code>```

The output is wrong. It should return 1 since the email field is empty

```<code> result: (u'',) OK
 length of result: 1
 email taken
 result: 0
</code>```

Any advice?

答:
For checking an existing value in table, i would recommend COUNT query</p>

```<code>query = "SELECT COUNT(email) FROM u_code WHERE code = %s"
cursor.execute(query, [code,])

# COUNT query always return value, if no matching data
# it simply return integer value 0, so we can safely take data
# from result[0]
result_check = cursor.fetchone()

if not result_check[0]:
    print("empty email")
    result = 1;
else:
    print("email taken")
    result = 0

print "result: " + str(result)
</code>```

Body:
I would like to check whether the email returned by a query is empty. I am using the following code:

query = "select email from u_code where code = '"+code+"'"
cursor.execute(query)
result_set = cursor.fetchall()

length = cursor.rowcount
if (length==1):
   print ' result: ' + str(result_set[0]) + ' OK'
   print ' length of result: ' + str(len(result_set[0]))

   if (result_set[0] == ''):
       print("empty email")
       result = 1;
   else:
       print("email taken")
       result = 0

print "result: " + str(result)

The output is wrong. It should return 1 since the email field is empty

 result: (u'',) OK
 length of result: 1
 email taken
 result: 0

Any advice?

Body:
For checking an existing value in table, i would recommend COUNT query

query = "SELECT COUNT(email) FROM u_code WHERE code = %s"
cursor.execute(query, [code,])

# COUNT query always return value, if no matching data
# it simply return integer value 0, so we can safely take data
# from result[0]
result_check = cursor.fetchone()

if not result_check[0]:
    print("empty email")
    result = 1;
else:
    print("email taken")
    result = 0

print "result: " + str(result)


问:
How to make a Type-constructor part of the Functor typeclass if it has more than one Type-parameter?
I am trying to understand the way the Functor-Typeclass works in Haskell. If you have a function f :: a -> b -> c and you want to partially apply it to the argB to get a function that takes one argument, you can simply do:

```<code>f' :: a -> c
f' x = f x argB
</code>```

and use that. Is it possible to get such behavior when making something part of the Functor-Typeclass with something like this:

```<code>instance Functor (MyTypeconstructor _ argB) where
   fmap <implementation of fmap>
</code>```

I know you can partially apply a Type-constructor to its first type-parameter (standart currying):

```<code>instance Functor (MyTypeconstructor argA) where
   fmap <implementation of fmap>
</code>```

but how can you partially apply it to its second / third / all except one type-parameter, if this is possible?

thank you.

答:
Suppose you have data F a b = ..., define

```<code>newtype Fx a = Fx { unFx :: F a X }
</code>```

to partially apply F to X in the second argument. Now you can use

```<code>instance Functor Fx where
    fmap f fa = ...
</code>```

to define your instance for F _ X.

Body:
I am trying to understand the way the Functor-Typeclass works in Haskell. If you have a function f :: a -> b -> c and you want to partially apply it to the argB to get a function that takes one argument, you can simply do:

f' :: a -> c
f' x = f x argB

and use that. Is it possible to get such behavior when making something part of the Functor-Typeclass with something like this:

instance Functor (MyTypeconstructor _ argB) where
   fmap <implementation of fmap>

I know you can partially apply a Type-constructor to its first type-parameter (standart currying):

instance Functor (MyTypeconstructor argA) where
   fmap <implementation of fmap>

but how can you partially apply it to its second / third / all except one type-parameter, if this is possible?

thank you.

Body:
Suppose you have data F a b = ..., define

newtype Fx a = Fx { unFx :: F a X }

to partially apply F to X in the second argument. Now you can use

instance Functor Fx where
    fmap f fa = ...

to define your instance for F _ X.


问:
Unable to connect to Azure Table Storage in windows 2012 r2 and .net core 1.0.1
I recently upgrade my asp.net core project from the rc2 version to 1.0.1. I am having trouble figuring out how to connect to Azure Table Storage. It seems that something is blocking my connection.

Note that this code is working on my local dev box, Win10 15063. It does not work on my dev server, running Win2012R2. It was also working with the .net core preview version 1.0.0-preview2-003133, but not the .net core final version 1.0.1

I'm using the latest Azure Storage package, 8.1.1

Here's my code

```<code>var azureTableStorageConnectionString = "DefaultEndpointsProtocol=https;AccountName=blah_blahstoragedev;AccountKey=Blahblah;EndpointSuffix=core.windows.net"; //Configuration["AzureStorageConnectionString"];

storageAccount = CloudStorageAccount.Parse(connectionString);
tableClient = storageAccount.CreateCloudTableClient();

buildTable = tableClient.GetTableReference(BuildTableName);
buildTable.CreateIfNotExists();
</code>```

It failed with this exception:

Microsoft.WindowsAzure.Storage.StorageException: 'Unable to connect to the remote server'

InnerException  {"No connection could be made because the target machine actively refused it 127.0.0.1:8888"}   System.Exception {System.Net.Sockets.SocketException}

StackTrace    "   at
  Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1
  cmd, IRetryPolicy policy, OperationContext operationContext)

at
  Microsoft.WindowsAzure.Storage.Table.TableOperation.Execute(CloudTableClient
  client, CloudTable table, TableRequestOptions requestOptions,
  OperationContext operationContext)

at
  Microsoft.WindowsAzure.Storage.Table.CloudTable.Exists(Boolean
  primaryOnly, TableRequestOptions requestOptions, OperationContext
  operationContext)

at
  Microsoft.WindowsAzure.Storage.Table.CloudTable.CreateIfNotExists(TableRequestOptions
  requestOptions, OperationContext operationContext)

答:
I tested following code on my Windows Server 2012 R2 with .NET Core 1.0.1 installed and it worked fine on my side.

```<code>public async static void CreateTable(string tableName)
{
    var connectionString = "my connection string";

    var storageAccount = CloudStorageAccount.Parse(connectionString);
    var tableClient = storageAccount.CreateCloudTableClient();

    Microsoft.WindowsAzure.Storage.Table.CloudTable buildTable = tableClient.GetTableReference(tableName);
    await buildTable.CreateIfNotExistsAsync();
    Console.WriteLine("Create success");
}
</code>```

The differences of code between yours and mine is that I can’t use CreateIfNotExists method when I build my application. I showed me the following error. So I used CreateIfNotExistsAsync method instead.

error CS1061: 'CloudTable' does not contain a definition for 'CreateIfNotExists' and no extension method 'CreateIfNotExists' accepting a first argument of type 'CloudTable' could be found

Please use asynchronous method and tested your code again. Here is a discussion which related to it from GitHub.

Our NetCore/Netstandard support does not yet include Sync implementation of the APIs.

Missing syncronous methods for dotnet core?

the target machine actively refused it 127.0.0.1:8888

8888 often use as a port for a proxy or antivirus software. Please mark sure whether the creating table request was blocking by your firewall or antivirus software. I suggest you use a tool(for example, Wireshark) to check whether the network packets has been sent from your server successfully. Following is the request which send from my Windows Server 2012 R2 when I created a new table using .NET Core 1.0.1 and Azure Storage SDK (captured by Fiddler).

```<code>POST https://mystroagename.table.core.windows.net/Tables() HTTP/1.1
Connection: Keep-Alive
Content-Type: application/json
Accept: application/json; odata=minimalmetadata
Accept-Charset: UTF-8
Authorization: SharedKey mystroagename:mykey
User-Agent: Azure-Storage/8.1.1 (.NET Core)
MaxDataServiceVersion: 3.0;NetFx
Prefer: return-no-content
DataServiceVersion: 3.0;
x-ms-client-request-id: 5eeb6570-0ca0-42c7-844a-6acdcc3b7bb9
x-ms-version: 2016-05-31
x-ms-date: Mon, 03 Apr 2017 07:26:43 GMT
Content-Length: 23
Host: mystroagename.table.core.windows.net

{"TableName":"newtablename"}
</code>```

Body:
I recently upgrade my asp.net core project from the rc2 version to 1.0.1. I am having trouble figuring out how to connect to Azure Table Storage. It seems that something is blocking my connection.

Note that this code is working on my local dev box, Win10 15063. It does not work on my dev server, running Win2012R2. It was also working with the .net core preview version 1.0.0-preview2-003133, but not the .net core final version 1.0.1

I'm using the latest Azure Storage package, 8.1.1

Here's my code

var azureTableStorageConnectionString = "DefaultEndpointsProtocol=https;AccountName=blah_blahstoragedev;AccountKey=Blahblah;EndpointSuffix=core.windows.net"; //Configuration["AzureStorageConnectionString"];

storageAccount = CloudStorageAccount.Parse(connectionString);
tableClient = storageAccount.CreateCloudTableClient();

buildTable = tableClient.GetTableReference(BuildTableName);
buildTable.CreateIfNotExists();

It failed with this exception:

Microsoft.WindowsAzure.Storage.StorageException: 'Unable to connect to the remote server'

InnerException  {"No connection could be made because the target machine actively refused it 127.0.0.1:8888"}   System.Exception {System.Net.Sockets.SocketException}

StackTrace    "   at
  Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1
  cmd, IRetryPolicy policy, OperationContext operationContext)

at
  Microsoft.WindowsAzure.Storage.Table.TableOperation.Execute(CloudTableClient
  client, CloudTable table, TableRequestOptions requestOptions,
  OperationContext operationContext)

at
  Microsoft.WindowsAzure.Storage.Table.CloudTable.Exists(Boolean
  primaryOnly, TableRequestOptions requestOptions, OperationContext
  operationContext)

at
  Microsoft.WindowsAzure.Storage.Table.CloudTable.CreateIfNotExists(TableRequestOptions
  requestOptions, OperationContext operationContext)

Body:
I tested following code on my Windows Server 2012 R2 with .NET Core 1.0.1 installed and it worked fine on my side.

public async static void CreateTable(string tableName)
{
    var connectionString = "my connection string";

    var storageAccount = CloudStorageAccount.Parse(connectionString);
    var tableClient = storageAccount.CreateCloudTableClient();

    Microsoft.WindowsAzure.Storage.Table.CloudTable buildTable = tableClient.GetTableReference(tableName);
    await buildTable.CreateIfNotExistsAsync();
    Console.WriteLine("Create success");
}

The differences of code between yours and mine is that I can’t use CreateIfNotExists method when I build my application. I showed me the following error. So I used CreateIfNotExistsAsync method instead.

error CS1061: 'CloudTable' does not contain a definition for 'CreateIfNotExists' and no extension method 'CreateIfNotExists' accepting a first argument of type 'CloudTable' could be found

Please use asynchronous method and tested your code again. Here is a discussion which related to it from GitHub.

Our NetCore/Netstandard support does not yet include Sync implementation of the APIs.

Missing syncronous methods for dotnet core?

the target machine actively refused it 127.0.0.1:8888

8888 often use as a port for a proxy or antivirus software. Please mark sure whether the creating table request was blocking by your firewall or antivirus software. I suggest you use a tool(for example, Wireshark) to check whether the network packets has been sent from your server successfully. Following is the request which send from my Windows Server 2012 R2 when I created a new table using .NET Core 1.0.1 and Azure Storage SDK (captured by Fiddler).

POST https://mystroagename.table.core.windows.net/Tables() HTTP/1.1
Connection: Keep-Alive
Content-Type: application/json
Accept: application/json; odata=minimalmetadata
Accept-Charset: UTF-8
Authorization: SharedKey mystroagename:mykey
User-Agent: Azure-Storage/8.1.1 (.NET Core)
MaxDataServiceVersion: 3.0;NetFx
Prefer: return-no-content
DataServiceVersion: 3.0;
x-ms-client-request-id: 5eeb6570-0ca0-42c7-844a-6acdcc3b7bb9
x-ms-version: 2016-05-31
x-ms-date: Mon, 03 Apr 2017 07:26:43 GMT
Content-Length: 23
Host: mystroagename.table.core.windows.net

{"TableName":"newtablename"}


问:
SQL Server Windows Authentication and Hibernate
Trying to connect, using Hibernate 4.3, to SQL Server with Windows Authentication, i'm getting a:

"No Persistence provider for EntityManager named instanceTest"

I have loaded the sqljdbc_auth.dll library and im using this url:

```<code>jdbc:sqlserver://localhost:1433;databaseName=WIN_AUTHDB;integratedSecurity=true
</code>```

The parameters which i am using to create the entity manager factory are:

```<code>properties.put("background-validation", "true");
properties.put("hibernate.c3p0.idle_test_period", "3600");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.max_fetch_depth", "3");
properties.put("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
properties.put("hibernate.connection.url","jdbc:sqlserver://localhost:1433;databaseName=WIN_AUTHDB;integratedSecurity=true");
</code>```

Im missing something? Maybe is the dll not loaded? The error is thrown at this line:

```<code>Persistence.createEntityManagerFactory("instanceTest", initProperties(properties));
</code>```

The database is correctly configured, i have connected through Windows Authentication with the SQL Server Management. Also, in a previous test, i achieved to create a database using the driver without hibernate.

Thanks in advance.

答:
Resolved!

Much more simple than I thought. When I was compiling the maven project, i was unintentionally deleting the persistence.xml file. Thats the reason because it never found the persistence provider at the war.

Body:
Trying to connect, using Hibernate 4.3, to SQL Server with Windows Authentication, i'm getting a:

"No Persistence provider for EntityManager named instanceTest"

I have loaded the sqljdbc_auth.dll library and im using this url:

jdbc:sqlserver://localhost:1433;databaseName=WIN_AUTHDB;integratedSecurity=true

The parameters which i am using to create the entity manager factory are:

properties.put("background-validation", "true");
properties.put("hibernate.c3p0.idle_test_period", "3600");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.max_fetch_depth", "3");
properties.put("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
properties.put("hibernate.connection.url","jdbc:sqlserver://localhost:1433;databaseName=WIN_AUTHDB;integratedSecurity=true");

Im missing something? Maybe is the dll not loaded? The error is thrown at this line:

Persistence.createEntityManagerFactory("instanceTest", initProperties(properties));

The database is correctly configured, i have connected through Windows Authentication with the SQL Server Management. Also, in a previous test, i achieved to create a database using the driver without hibernate.

Thanks in advance.


问:
I can't use HTML select within Dojo Tooltip
I need a Dojo tooltip with a drop-down-list. Unfortunately the tooltip closes when the cursor is moved over the drop-down-list, because the list overhangs the tooltip's div.

Is there any workaround? Could the close-automatism be disabled temporarily?

```<code><div class="dojoPopupContainer dojoTooltip showComboBox"
        style="position: absolute; z-index: 1001; left: 287px; top: 15px;"
        dojoattachpoint="containerNode">
    <div id="showComboBox6e" wicket:id="showComboBox">
        <form>
            <select class="selectOneListbox" size="1">
                <option value="1">option 1</option>
                <option value="2">option 2</option>
                <option value="3">option 3</option>
            </select>
            <button value="submit" type="button" name="submit">send</button>
    </form>
    </div>
</div>
</code>```

Update Looks like this is a browser-specific issue. The problem occurs with Firefox (3.6), but works with Internet Explorer (8). I still need a solution.

答: I think you can try and create the tooltip using dijit.showTooltip() and close it using dijit.hideTooltip() whenever you want to close it.

Body:
I need a Dojo tooltip with a drop-down-list. Unfortunately the tooltip closes when the cursor is moved over the drop-down-list, because the list overhangs the tooltip's div.

Is there any workaround? Could the close-automatism be disabled temporarily?

        <form>
            <select class="selectOneListbox" size="1">
                <option value="1">option 1</option>
                <option value="2">option 2</option>
                <option value="3">option 3</option>
            </select>
            <button value="submit" type="button" name="submit">send</button>
    </form>

Update Looks like this is a browser-specific issue. The problem occurs with Firefox (3.6), but works with Internet Explorer (8). I still need a solution.


问:
Collapse tableView rows on a row select in swift
i have a tableView where i show user created circle name and i want when the user select a circle name rest circle name collapse and show only one circle name. but i don't know how to do that. please help help me guys.

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if indexPath.section == 0
    {
        // here is the code to collapse the row
    }
 }
</code>```

Section == 0 have the rows of circle names.

答:
First I have make a structure for managing Expand collapse feature.
All Macros:

```<code>let IndexVal = -4
let ISSELECTED = "ISSELECTED"
let SELECTED = "SELECTED"
let UNSELECTED = "UNSELECTED"
let FLAGE = "FLAGE"
let DATA = "DATA"
</code>```

I create an array  arrTA = NSMutableArray() in which our whole processed data will be stored.
here I have used arrFolderList in which the JSON data is storing.

Now when you call an API and in that response you need to call this function with IndexVal

```<code> self.reloadTableForExpandCollapse(IndexVal)
</code>```

This will set the default view i.e collpased view.

And use it in this way:

```<code>func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.reloadTableForExpandCollapse(indexPath.row)
    }
</code>```

Now function defination:

```<code>func reloadTableForExpandCollapse( indexValue: Int)  {
        var index = indexValue
        if(index == IndexVal) {  /// This is the case when we run first time
            arrTA = NSMutableArray()
            for i in 0..<self.arrFolderList.count {
                let strFlage = "MA"
                let dict = NSMutableDictionary()
                dict.setObject(strFlage, forKey: FLAGE)
                dict.setObject(UNSELECTED, forKey: ISSELECTED)
                dict.setObject(self.arrFolderList[i] , forKey: DATA)
                arrTA.addObject(dict)
            }
        } else { /// When we are performing the operations
            /// When we collapsed
             if(index == IndexVal) {
            arrTA = NSMutableArray()
            for i in 0..<self.arrFolderList.count {
                let strFlage = "MA"
                let dict = NSMutableDictionary()
                dict.setObject(strFlage, forKey: FLAGE)
                dict.setObject(UNSELECTED, forKey: ISSELECTED)
                dict.setObject(self.arrFolderList[i], forKey: DATA)
                arrTA.addObject(dict)
            }
                self.tblView_Expandable.reloadData()
             } else {

                if(index < arrTA.count) {
                    let dict = arrTA.objectAtIndex(index) as! NSMutableDictionary
                    dict.setObject(SELECTED, forKey: ISSELECTED)
                    let strFlage = dict[FLAGE] as! String
                    if(strFlage == "MA") { /// Means it is main array
                        var isAdding: Bool = true
                        var isRemoving: Bool = true
                        if (index  < self.arrTA.count) {
                            for var j in index + 1..<self.arrTA.count   {  /// removed + 1from index
                                let dict1 = self.arrTA[j]
                                let strFlage1 = (dict1[FLAGE] as! String)
                                if (strFlage1 == "SA") && isRemoving {
                                    isAdding = false
                                    dict[ISSELECTED] = UNSELECTED
                                    self.arrTA.removeObjectAtIndex(j)
                                    j -= 1
                                    break
                                } else if isAdding {
                                    isRemoving = false
                                      break
                                } else if (strFlage1 == "MA") && isRemoving {
                                      break
                                }
                            }
                        }

                        if ((dict[FLAGE] as! String) == "MA") {
                            var k = 0
                            while k < self.arrTA.count {
                                let dict1 = self.arrTA[k] as! NSMutableDictionary
                                dict1[ISSELECTED] = UNSELECTED
                                let strFlage1 = (dict1[FLAGE] as! String)
                                if (strFlage1 == "SA") {
                                    self.arrTA.removeObjectAtIndex(k)
                                    if k < index {
                                        index -= 1
                                    }
                                    k -= 1
                                }
                                k += 1
                            }
                        }

                        if isAdding {
                            let dict = self.arrTA[index] as! NSMutableDictionary
                            let strFlage = (dict[FLAGE] as! String)
                            //  dict[ISSELECTED] = UNSELECTED
                            self.arrTA.replaceObjectAtIndex(index, withObject: dict)
                            if (strFlage == "MA") {
                                let dictData = (dict[DATA] as! NSDictionary)
                                let dictSA = NSMutableDictionary()
                                let strFlage = "SA"
                                dictSA[FLAGE] = strFlage
                                dictSA[DATA] = dictData
                                dictSA[ISSELECTED] = UNSELECTED
                                self.arrTA.insertObject(dictSA, atIndex: index + 1)
                            }
                            if(self.tblView_Expandable.lastIndexpath().row == index) {
                               self.scrollTableViewToBottom()
                            }
                        }
                    }else {  }
                    }
                }
            }
        if(tblView_Expandable != nil) {
                 tblView_Expandable.reloadData()
        }

      }
</code>```

And I hope this will help.... :)

Body:
i have a tableView where i show user created circle name and i want when the user select a circle name rest circle name collapse and show only one circle name. but i don't know how to do that. please help help me guys.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if indexPath.section == 0
    {
        // here is the code to collapse the row
    }
 }

Section == 0 have the rows of circle names.

Body:
First I have make a structure for managing Expand collapse feature.
All Macros:

let IndexVal = -4
let ISSELECTED = "ISSELECTED"
let SELECTED = "SELECTED"
let UNSELECTED = "UNSELECTED"
let FLAGE = "FLAGE"
let DATA = "DATA"

I create an array  arrTA = NSMutableArray() in which our whole processed data will be stored.
here I have used arrFolderList in which the JSON data is storing.

Now when you call an API and in that response you need to call this function with IndexVal

 self.reloadTableForExpandCollapse(IndexVal)

This will set the default view i.e collpased view.

And use it in this way:

func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.reloadTableForExpandCollapse(indexPath.row)
    }

Now function defination:

func reloadTableForExpandCollapse( indexValue: Int)  {
        var index = indexValue
        if(index == IndexVal) {  /// This is the case when we run first time
            arrTA = NSMutableArray()
            for i in 0..<self.arrFolderList.count {
                let strFlage = "MA"
                let dict = NSMutableDictionary()
                dict.setObject(strFlage, forKey: FLAGE)
                dict.setObject(UNSELECTED, forKey: ISSELECTED)
                dict.setObject(self.arrFolderList[i] , forKey: DATA)
                arrTA.addObject(dict)
            }
        } else { /// When we are performing the operations
            /// When we collapsed
             if(index == IndexVal) {
            arrTA = NSMutableArray()
            for i in 0..<self.arrFolderList.count {
                let strFlage = "MA"
                let dict = NSMutableDictionary()
                dict.setObject(strFlage, forKey: FLAGE)
                dict.setObject(UNSELECTED, forKey: ISSELECTED)
                dict.setObject(self.arrFolderList[i], forKey: DATA)
                arrTA.addObject(dict)
            }
                self.tblView_Expandable.reloadData()
             } else {

                if(index < arrTA.count) {
                    let dict = arrTA.objectAtIndex(index) as! NSMutableDictionary
                    dict.setObject(SELECTED, forKey: ISSELECTED)
                    let strFlage = dict[FLAGE] as! String
                    if(strFlage == "MA") { /// Means it is main array
                        var isAdding: Bool = true
                        var isRemoving: Bool = true
                        if (index  < self.arrTA.count) {
                            for var j in index + 1..<self.arrTA.count   {  /// removed + 1from index
                                let dict1 = self.arrTA[j]
                                let strFlage1 = (dict1[FLAGE] as! String)
                                if (strFlage1 == "SA") && isRemoving {
                                    isAdding = false
                                    dict[ISSELECTED] = UNSELECTED
                                    self.arrTA.removeObjectAtIndex(j)
                                    j -= 1
                                    break
                                } else if isAdding {
                                    isRemoving = false
                                      break
                                } else if (strFlage1 == "MA") && isRemoving {
                                      break
                                }
                            }
                        }

                        if ((dict[FLAGE] as! String) == "MA") {
                            var k = 0
                            while k < self.arrTA.count {
                                let dict1 = self.arrTA[k] as! NSMutableDictionary
                                dict1[ISSELECTED] = UNSELECTED
                                let strFlage1 = (dict1[FLAGE] as! String)
                                if (strFlage1 == "SA") {
                                    self.arrTA.removeObjectAtIndex(k)
                                    if k < index {
                                        index -= 1
                                    }
                                    k -= 1
                                }
                                k += 1
                            }
                        }

                        if isAdding {
                            let dict = self.arrTA[index] as! NSMutableDictionary
                            let strFlage = (dict[FLAGE] as! String)
                            //  dict[ISSELECTED] = UNSELECTED
                            self.arrTA.replaceObjectAtIndex(index, withObject: dict)
                            if (strFlage == "MA") {
                                let dictData = (dict[DATA] as! NSDictionary)
                                let dictSA = NSMutableDictionary()
                                let strFlage = "SA"
                                dictSA[FLAGE] = strFlage
                                dictSA[DATA] = dictData
                                dictSA[ISSELECTED] = UNSELECTED
                                self.arrTA.insertObject(dictSA, atIndex: index + 1)
                            }
                            if(self.tblView_Expandable.lastIndexpath().row == index) {
                               self.scrollTableViewToBottom()
                            }
                        }
                    }else {  }
                    }
                }
            }
        if(tblView_Expandable != nil) {
                 tblView_Expandable.reloadData()
        }

      }

And I hope this will help.... :)


问:
what is the fastest way to randomly select some numbers in a range that contains a given set of numbers?
Here is the function I want

```<code>random_select(contain_list, ttl_num, sample_num)
</code>```

There're ttl_num integers from 0 to ttl_num-1 to select from, I want to return a list of sample_num unique integers, where numbers provided in contain_list have to be in the list, and other numbers are selected randomly.

I have to do this query very often, every time with a different contain_list, but ttl_num, sample_num are the same for all the queries.

Currently what I'm doing is, first generate a set of ttl_num integers, subtract contain_list from the set, randomly select some numbers with no replacement from the rest, then concatenate it with the contain_list to get the result.

I believe this is not the fastest way, any better thoughts?

It's okay to use global variables if needed.

Edit:

sample_num is no less than contain_list length and I want to get contain_list plus sample_num - contain_list.length other random numbers

it's guaranteed that numbers in contain_list are all within the range 0 to ttl_num-1.

答:
I just wrote some code similar to method 1 from James Droscha's answer in a vectorized way using numpy, which turned out to be just several lines of code,</p>

```<code>def random_select(batch, ttl_num, sample_num):
    # add the following line if elements in batch are not guaranteed to be unique
    # batch = np.unique(batch)
    batch_size = len(batch)
    # step 1
    candidates = np.arange(ttl_num)
    # step 4
    candidates[batch] = candidates[-batch_size:]  # so that elements in candidates[:ttl_num-batch_size] are not contained in batch
    # step 5
    idx = np.random.choice(ttl_num-batch_size, sample_num-batch_size, replace=False)
    return np.concatenate([candidates[idx], batch])
</code>```

Body:
Here is the function I want

random_select(contain_list, ttl_num, sample_num)

There're ttl_num integers from 0 to ttl_num-1 to select from, I want to return a list of sample_num unique integers, where numbers provided in contain_list have to be in the list, and other numbers are selected randomly.

I have to do this query very often, every time with a different contain_list, but ttl_num, sample_num are the same for all the queries.

Currently what I'm doing is, first generate a set of ttl_num integers, subtract contain_list from the set, randomly select some numbers with no replacement from the rest, then concatenate it with the contain_list to get the result.

I believe this is not the fastest way, any better thoughts?

It's okay to use global variables if needed.

Edit:

sample_num is no less than contain_list length and I want to get contain_list plus sample_num - contain_list.length other random numbers

it's guaranteed that numbers in contain_list are all within the range 0 to ttl_num-1.

Body:
I just wrote some code similar to method 1 from James Droscha's answer in a vectorized way using numpy, which turned out to be just several lines of code,

def random_select(batch, ttl_num, sample_num):
    # add the following line if elements in batch are not guaranteed to be unique
    # batch = np.unique(batch)
    batch_size = len(batch)
    # step 1
    candidates = np.arange(ttl_num)
    # step 4
    candidates[batch] = candidates[-batch_size:]  # so that elements in candidates[:ttl_num-batch_size] are not contained in batch
    # step 5
    idx = np.random.choice(ttl_num-batch_size, sample_num-batch_size, replace=False)
    return np.concatenate([candidates[idx], batch])


问:
How to superseed Glassfish's built-in libraries with dependencies shipped in EAR?
GlassFish 4.1 provides EclipseLink 2.5.x in glassfish/modules. I want to use 2.6.4 in my application and am including it when packaging it with maven-ear-plugin:2.10.1 with

```<code><configuration>
    <finalName>linuxtracker2</finalName>
    <version>7</version>
    <defaultLibBundleDir>lib</defaultLibBundleDir>
    <archive>
        <manifest>
            <addClasspath>true</addClasspath>
        </manifest>
    </archive>
</configuration>
</code>```

and the EJB and WAR module as dependency (and default values otherwise). The application deploys and works fine, but I suspect that EclipseLink 2.5 has an issue and I want to overwrite it anyway because I don't want to (double) configure the server to provide dependencies.

I figured out so far that GlassFish has a classloader hierarchy and that load requests are delegated to the topmost parent which can satisfy it, but the docs fail of course to explain how to use that. There's Circumventing Class Loader Isolation which I'd say from my understanding does the opposite of what I want to acchieve (isolate the class loader to use my packaged dependencies).

My application setup is the standard: entity classes and EJB interfaces, EJB implemetations, web frontend and EAR maven module.

Related troubles:

Glassfish 4 documentation is hard to find via google, search terms with "glassfish 4" return results for 3.x only, I didn't manage

the Oracle documentation database http://docs.oracle.com doesn't provide documentation for GlassFish 4.x - that's low, even for Oracle

links in the 3.x documentation - why not try it since I have unlimited time - include dead links like http://blogs.sun.com/sivakumart/entry/classloaders_in_glassfish_an_attempt on http://docs.oracle.com/cd/E19226-01/820-7695/gatej/index.html

WildFly has a quite cryptic feedback which is only targeting core developer judging from its form and the possility to understand it (see https://stackoverflow.com/questions/43090661/how-to-figure-out-what-missing-service-dependencies-in-wildfly-10-mean for example); afaik it's the only other FLOSS Java EE application server which is Java EE 7 certified

I can't user GlassFish 4.1.1 because of https://java.net/jira/browse/GLASSFISH-21437.

答:
GlassFish is no longer supported by Oracle, and therefore just an open source project now. The documentation can be found at https://glassfish.java.net/documentation.html - you will need to download the "Administration Guide" PDF, though the others are quite useful too.

What you're trying to do here isn't possible in GlassFish, but is a feature added to Payara Server, which is derived from GlassFish (disclaimer: I work for them).

For EAR files, Payara Server has added the option to add <classloading-delegate>false</classloading-delegate> in your META-INF/glassfish-application.xml file. This should stop your application using libraries from Payara Server when you have your own versions packaged in your EAR.

For your specific use-case, though, you would not need to use this since Payara Server already comes with EclipseLink 2.6.4 in the latest build, 171.1

Body:
GlassFish 4.1 provides EclipseLink 2.5.x in glassfish/modules. I want to use 2.6.4 in my application and am including it when packaging it with maven-ear-plugin:2.10.1 with

<configuration>
    <finalName>linuxtracker2</finalName>
    <version>7</version>
    <defaultLibBundleDir>lib</defaultLibBundleDir>
    <archive>
        <manifest>
            <addClasspath>true</addClasspath>
        </manifest>
    </archive>
</configuration>

and the EJB and WAR module as dependency (and default values otherwise). The application deploys and works fine, but I suspect that EclipseLink 2.5 has an issue and I want to overwrite it anyway because I don't want to (double) configure the server to provide dependencies.

I figured out so far that GlassFish has a classloader hierarchy and that load requests are delegated to the topmost parent which can satisfy it, but the docs fail of course to explain how to use that. There's Circumventing Class Loader Isolation which I'd say from my understanding does the opposite of what I want to acchieve (isolate the class loader to use my packaged dependencies).

My application setup is the standard: entity classes and EJB interfaces, EJB implemetations, web frontend and EAR maven module.

Related troubles:

Glassfish 4 documentation is hard to find via google, search terms with "glassfish 4" return results for 3.x only, I didn't manage

the Oracle documentation database http://docs.oracle.com doesn't provide documentation for GlassFish 4.x - that's low, even for Oracle

links in the 3.x documentation - why not try it since I have unlimited time - include dead links like http://blogs.sun.com/sivakumart/entry/classloaders_in_glassfish_an_attempt on http://docs.oracle.com/cd/E19226-01/820-7695/gatej/index.html

WildFly has a quite cryptic feedback which is only targeting core developer judging from its form and the possility to understand it (see https://stackoverflow.com/questions/43090661/how-to-figure-out-what-missing-service-dependencies-in-wildfly-10-mean for example); afaik it's the only other FLOSS Java EE application server which is Java EE 7 certified

I can't user GlassFish 4.1.1 because of https://java.net/jira/browse/GLASSFISH-21437.


问:
Restrict access to Java Packages for other Java Packages
Let us say I have three public java packages:

```<code>my.com.model
my.com.view
my.com.controler
</code>```

Now I want to restrict which package is allowed to import classes from a dedicated package.

So e.g. the classes from view package are only allowed to import classes from controler package
but not from model package and the controler package is only allowed to import classes from model package but
not from the view package and the model package has no access at all to the model and view packages.

How can I achieve this? I know that Java does not support such a requirement so maybe some static code
analysis tool can help me.

Update: I am using Java 7

答:
You could define this by extracting each concern in a separated module.

The view module would have a dependency on the controller module and  the controller module would have a dependency on the model module.

You could use Maven to achieve these constraints.

You could for example define a reactor or a multi module Maven project with 3 modules.

Maven provides transitive dependencies for a declared dependency. So to respect fully your requirements, the view module should exclude the transitive model dependency that is pulled by the controller dependency .

Body:
Let us say I have three public java packages:

my.com.model
my.com.view
my.com.controler

Now I want to restrict which package is allowed to import classes from a dedicated package.

So e.g. the classes from view package are only allowed to import classes from controler package
but not from model package and the controler package is only allowed to import classes from model package but
not from the view package and the model package has no access at all to the model and view packages.

How can I achieve this? I know that Java does not support such a requirement so maybe some static code
analysis tool can help me.

Update: I am using Java 7