问:
Speed up R performance or convert R function to C++ function
I have an R function to compute the probability of the integer k; k = 1, ....., m from the given values of the other parameters. When the size of the k is very large (e.g., m = 10,000), the function is very slow. Do you have any suggestions to improve the performance of the function?

I also want to create an equivalent function in C++ if needed so that I can use RCPP package from R, but I do not know C++. Before learning C++ from the scratch, I also would like to have your suggestions.

```<code>prob <- function(k, et, ey, nrep = 10000, m0, m1)
{
    m = m0 + m1
    t <- rnorm(nrep, et, 1)
    p0 <- pnorm(-t)
    p1 <- pnorm(ey - t)

    mean0 <- (m0 - 1)*p0 + m1*p1 + 1
    mean1 <- m0*p0 + (m1 - 1)*p1 + 1

    var0 <- (m0 - 1)*p0*(1 - p0) + m1*p1*(1 - p1)
    var1 <- m0*p0*(1 - p0) + (m1 - 1)*p1*(1 - p1)

    prob <- ifelse(et == 0, mean(dnorm(k, mean0, sqrt(var0))),
                   mean(dnorm(k, mean1, sqrt(var1))))

    return(prob)
}
</code>```

apply the function

```<code>prob_k <- sapply(1:10000, prob, et=1, ey=1 ,m0 = 5000, m1 = 5000)
</code>```

答:
Since dnorm is a vectorized function, you can just call prob like

```<code>prob_k <- prob(1:10000, et = 1, ey = 1 ,m0 = 5000, m1 = 5000)
</code>```

To get verctorized outputs, you will have to change the code of the function a bit though

```<code>prob <- function(k, et, ey, nrep = 10000, m0, m1)
{
  m = m0 + m1
  t <- rnorm(nrep, et, 1)
  p0 <- pnorm(-t)
  p1 <- pnorm(ey - t)

  mean0 <- (m0 - 1)*p0 + m1*p1 + 1
  mean1 <- m0*p0 + (m1 - 1)*p1 + 1

  var0 <- (m0 - 1)*p0*(1 - p0) + m1*p1*(1 - p1)
  var1 <- m0*p0*(1 - p0) + (m1 - 1)*p1*(1 - p1)

  if( et == 0 )
    dnorm(k, mean0, sqrt(var0))
  else
    dnorm(k, mean1, sqrt(var1))
}
</code>```

This is pretty fast on my machine (5 milliseconds on average)

```<code>microbenchmark(prob_k <- prob(1:10000, et = 1, ey = 1 ,m0 = 5000, m1 = 5000))
# Unit: milliseconds
#                                                           expr     min
#  prob_k <- prob(1:10000, et = 1, ey = 1, m0 = 5000, m1 = 5000) 4.68232
#        lq     mean   median       uq      max neval
#  4.776912 5.168405 4.817979 4.907612 7.023989   100
</code>```

Body:
I have an R function to compute the probability of the integer k; k = 1, ....., m from the given values of the other parameters. When the size of the k is very large (e.g., m = 10,000), the function is very slow. Do you have any suggestions to improve the performance of the function?

I also want to create an equivalent function in C++ if needed so that I can use RCPP package from R, but I do not know C++. Before learning C++ from the scratch, I also would like to have your suggestions.

prob <- function(k, et, ey, nrep = 10000, m0, m1)
{
    m = m0 + m1
    t <- rnorm(nrep, et, 1)
    p0 <- pnorm(-t)
    p1 <- pnorm(ey - t)

    mean0 <- (m0 - 1)*p0 + m1*p1 + 1
    mean1 <- m0*p0 + (m1 - 1)*p1 + 1

    var0 <- (m0 - 1)*p0*(1 - p0) + m1*p1*(1 - p1)
    var1 <- m0*p0*(1 - p0) + (m1 - 1)*p1*(1 - p1)

    prob <- ifelse(et == 0, mean(dnorm(k, mean0, sqrt(var0))),
                   mean(dnorm(k, mean1, sqrt(var1))))

    return(prob)
}

apply the function

prob_k <- sapply(1:10000, prob, et=1, ey=1 ,m0 = 5000, m1 = 5000)

Body:
Since dnorm is a vectorized function, you can just call prob like

prob_k <- prob(1:10000, et = 1, ey = 1 ,m0 = 5000, m1 = 5000)

To get verctorized outputs, you will have to change the code of the function a bit though

prob <- function(k, et, ey, nrep = 10000, m0, m1)
{
  m = m0 + m1
  t <- rnorm(nrep, et, 1)
  p0 <- pnorm(-t)
  p1 <- pnorm(ey - t)

  mean0 <- (m0 - 1)*p0 + m1*p1 + 1
  mean1 <- m0*p0 + (m1 - 1)*p1 + 1

  var0 <- (m0 - 1)*p0*(1 - p0) + m1*p1*(1 - p1)
  var1 <- m0*p0*(1 - p0) + (m1 - 1)*p1*(1 - p1)

  if( et == 0 )
    dnorm(k, mean0, sqrt(var0))
  else
    dnorm(k, mean1, sqrt(var1))
}

This is pretty fast on my machine (5 milliseconds on average)

microbenchmark(prob_k <- prob(1:10000, et = 1, ey = 1 ,m0 = 5000, m1 = 5000))
# Unit: milliseconds
#                                                           expr     min
#  prob_k <- prob(1:10000, et = 1, ey = 1, m0 = 5000, m1 = 5000) 4.68232
#        lq     mean   median       uq      max neval
#  4.776912 5.168405 4.817979 4.907612 7.023989   100


来源: stackexchange

问:
Cyclic inheritance with Android development - fragments, activities and interfaces
I have an app with several fragments and one activity that manages them. In order to avoid coupling between fragments all interactions and changes go through the activity - but here's my problem - I get cyclic inheritance compile time error in the following scenario:

in short:

```<code> class A extends Z implements B.listenerB, C.listenerC // cyclic inheritance involving A
 class B extends Y implements A.listenerA  //cyclic inheritance involving B
 class C extends Y implements A.listenerA  // cyclic inheritance involving A
</code>```

in long:

```<code>    public class Fragment1 extends Fragment implements Activity1.onCustomEventListenerActivity {
           onCustomEventListenerFrag1 listener1;

        public interface onCustomEventListenerFrag1{
         void onCustomEventinFrag1();
        }

        public void someAction(){
           if (successful)
               listener1.onCustomEvent(); //notify the activity of success
        }

        @Override
        public void onCustomEvent(){
            //respond to change from activity
        }
}
</code>```

Here is my example Activity:

```<code>public class Activity1 extends FragmentActivity implements Fragment1.onCustomEventListenerFrag1, Fragment2.onCustomEventListenerFrag2{

    //Listens to events in the Activity
    onCustomEventListenerActivity mListener;
    public interface onCustomEventListenerActivity{
       void onCustomEvent();
    }

    @Override
    public void onCustomEventinFrag1(){
        // notify Frag2
        mListener.onCustomEvent();
     }

     @Override
        public void onCustomEventinFrag2(){
        // some code
     }

     public void someAction(){
        if (successful)
        mListener.onCustomEvent();
     }
}
</code>```

And my other Fragment:

```<code>public class Fragment2 extends Fragment implements Activity1.onCustomEventListenerActivity {

    //Listens to some event in Frag2
    onCustomEventListenerFrag2 listener2;
    public interface onCustomEventListenerFrag2{
        void onCustomEventinFrag2();
    }

    //Said event
    public void someAction(){
        if (successful)
            listener2.onCustomEventinFrag2(); //notify the activity of success
    }

    //Responding to an event in the activity
    @Override
    public void onCustomEvent(){
        //change something in the fragment
    }
}
</code>```

How can I avoid this error while maintaining loose coupling between fragments? Can I wrap all interfaces in one single class for example and make every class implement needed interface (and if yes, how)? I have seen other examples of cyclic coupling but this one doesn't seem to be the case to my understanding.

Edit: I think I saw why I get the error, but still - is implementing an interface from a certain class the same as inheriting said class?

Thanks!

答: For me and i think for you as well. notice if you have a interface class that is embedded in a class, so nested. if you do and two classes are using that you'll get this error.  just take the interface and move it into a separate file and do not embed it in the class. that will quiet the error. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have an app with several fragments and one activity that manages them. In order to avoid coupling between fragments all interactions and changes go through the activity - but here's my problem - I get cyclic inheritance compile time error in the following scenario:

in short:

 class A extends Z implements B.listenerB, C.listenerC // cyclic inheritance involving A
 class B extends Y implements A.listenerA  //cyclic inheritance involving B
 class C extends Y implements A.listenerA  // cyclic inheritance involving A

in long:

    public class Fragment1 extends Fragment implements Activity1.onCustomEventListenerActivity {
           onCustomEventListenerFrag1 listener1;

        public interface onCustomEventListenerFrag1{
         void onCustomEventinFrag1();
        }

        public void someAction(){
           if (successful)
               listener1.onCustomEvent(); //notify the activity of success
        }

        @Override
        public void onCustomEvent(){
            //respond to change from activity
        }
}

Here is my example Activity:

public class Activity1 extends FragmentActivity implements Fragment1.onCustomEventListenerFrag1, Fragment2.onCustomEventListenerFrag2{

    //Listens to events in the Activity
    onCustomEventListenerActivity mListener;
    public interface onCustomEventListenerActivity{
       void onCustomEvent();
    }

    @Override
    public void onCustomEventinFrag1(){
        // notify Frag2
        mListener.onCustomEvent();
     }

     @Override
        public void onCustomEventinFrag2(){
        // some code
     }

     public void someAction(){
        if (successful)
        mListener.onCustomEvent();
     }
}

And my other Fragment:

public class Fragment2 extends Fragment implements Activity1.onCustomEventListenerActivity {

    //Listens to some event in Frag2
    onCustomEventListenerFrag2 listener2;
    public interface onCustomEventListenerFrag2{
        void onCustomEventinFrag2();
    }

    //Said event
    public void someAction(){
        if (successful)
            listener2.onCustomEventinFrag2(); //notify the activity of success
    }

    //Responding to an event in the activity
    @Override
    public void onCustomEvent(){
        //change something in the fragment
    }
}

How can I avoid this error while maintaining loose coupling between fragments? Can I wrap all interfaces in one single class for example and make every class implement needed interface (and if yes, how)? I have seen other examples of cyclic coupling but this one doesn't seem to be the case to my understanding.

Edit: I think I saw why I get the error, but still - is implementing an interface from a certain class the same as inheriting said class?

Thanks!


问:
extjs vtype does not work on textarea
ok , I have a vtype for enslish and sign only that looks like this:

```<code>Ext.apply(Ext.form.VTypes, {
excel: function (v) {
    return /^.*.(xls)$/.test(v);
},
excelText: 'Must be an *.xls file',
englishOnly: function (v) {
    return /^[a-z0-9,\.\~\!\@\#\$\%\^\&\*\(\)\_\+\<\>]*$/.test(v);
},
englishOnlyTest: 'Must be English letters'
</code>```

});

now I have a form that looks like this:

```<code>new Ext.FormPanel({
    id: 'add-label-form',
    url: hp,
    frame: true,
    baseParams: { actionName: 'AddLable' },
    defaultType: 'textfield',
    labelWidth: 70,
    items: [{
        id: 'tbKey',
        fieldLabel: localize.key,
        allowBlank: false,
        name: 'tbKey',
        anchor: '100%'
    }, {
        id: 'tbHebrewTran',
        fieldLabel: localize.hebrew,
        allowBlank: false,
        name: 'tbHebrewTran',
        anchor: '100%'
    }, {
        id: 'tbEnglishTran',
        fieldLabel: localize.english,
        allowBlank: false,
        name: 'tbEnglishTran',
        anchor: '100%'
    }, {
        id: 'tbDescription',
        xtype: 'textarea',
        vtype:'englishOnly',
        fieldLabel: localize.description,
        allowBlank: true,
        name: 'tbDescription',
        anchor: '100%'
    }],
    buttons: [{
        text: localize.submit,
        formBind: true,
        handler: onAddLabelSubmitClick
    }, {
        text: localize.reset,
        handler: function () {
            var f = Ext.getCmp('add-label-form').getForm();
            f.reset();
        }
    }]
})
</code>```

The vtype handler is called and returns false as expected but the form is still valid and no alert is displayed on the screen...
why is that?

答:
Make sure to include monitorValid: true in your FormPanel config.

Here's a comment from the API that explains the config option in more detail:

monitorValid  : Boolean

If true, the form monitors its
  valid state client-side and regularly
  fires the clientvalidation event
  passing that state.

When monitoring valid state, the
  FormPanel enables/disables any of its
  configured buttons which have been
  configured with formBind: true
  depending on whether the form is valid
  or not. Defaults to false.

With this set you should see the Button enabled/disabled and a red outline around whatever field the vtype applied to.

Update:

I noticed that your text variable for englishOnly is defined as englishOnlyTest, and I think it should be defined as englishOnlyText (you spelled "test" instead of "text"). If I recall correctly the framework expects to see text appended to the string that you want to use for the returned text. This may be why you're not seeing any red outline or popup text.

ContentLicense: CC BY-SA 2.5

Title: extjs vtype does not work on textarea

Body:
ok , I have a vtype for enslish and sign only that looks like this:

Ext.apply(Ext.form.VTypes, {
excel: function (v) {
    return /^.*.(xls)$/.test(v);
},
excelText: 'Must be an *.xls file',
englishOnly: function (v) {
    return /^[a-z0-9,\.\~\!\@\#\$\%\^\&\*\(\)\_\+\<\>]*$/.test(v);
},
englishOnlyTest: 'Must be English letters'

});

now I have a form that looks like this:

new Ext.FormPanel({
    id: 'add-label-form',
    url: hp,
    frame: true,
    baseParams: { actionName: 'AddLable' },
    defaultType: 'textfield',
    labelWidth: 70,
    items: [{
        id: 'tbKey',
        fieldLabel: localize.key,
        allowBlank: false,
        name: 'tbKey',
        anchor: '100%'
    }, {
        id: 'tbHebrewTran',
        fieldLabel: localize.hebrew,
        allowBlank: false,
        name: 'tbHebrewTran',
        anchor: '100%'
    }, {
        id: 'tbEnglishTran',
        fieldLabel: localize.english,
        allowBlank: false,
        name: 'tbEnglishTran',
        anchor: '100%'
    }, {
        id: 'tbDescription',
        xtype: 'textarea',
        vtype:'englishOnly',
        fieldLabel: localize.description,
        allowBlank: true,
        name: 'tbDescription',
        anchor: '100%'
    }],
    buttons: [{
        text: localize.submit,
        formBind: true,
        handler: onAddLabelSubmitClick
    }, {
        text: localize.reset,
        handler: function () {
            var f = Ext.getCmp('add-label-form').getForm();
            f.reset();
        }
    }]
})

The vtype handler is called and returns false as expected but the form is still valid and no alert is displayed on the screen...
why is that?


问:
Why I can get subroutine address before it is declared without error?
I have next program:

```<code>use warnings;
use strict;

BEGIN {
    print \&mysub;
}

sub mysub {};

print \&mysub;
</code>```

Its output:

```<code>CODE(0x118e890)CODE(0x118e890)
</code>```

The BEGIN block is processed in compile time. At that point definition of sub mysub is not seen by compiler yet. But program still prints right subroutine address, which it will have when defined.

Why I do not get error here? Is this some sort of autovivification?

答:
Very interesting question. I'm writing this as an answer instead of a comment because it will be rather long, but there are still some bits I'm not entirely sure about.

I believe your intuition is correct and that it is a form of autovivification.

Devel::Peek can spread more light on what's happening.

I changed your code a little bit:

```<code>use warnings;
use strict;
use Devel::Peek;

$|++;

BEGIN {
  Dump( \&mysub );
  print \&mysub;
};

sub mysub {};

Dump( \&mysub );
print \&mysub;
</code>```

I added $|++ so that buffering won't be cause of confusions, and added calls to Devel::Peek::Dump to look into the reference \&mysub. Here the output on my system:

```<code>SV = IV(0x2628628) at 0x2628638
  REFCNT = 1
  FLAGS = (TEMP,ROK)
  RV = 0x26286e0
  SV = PVCV(0x2640750) at 0x26286e0
    REFCNT = 2
    FLAGS = (DYNFILE)
    COMP_STASH = 0x25ffdb0  "main"
    ROOT = 0x0
    GVGV::GV = 0x26287a0    "main" :: "mysub"
    FILE = "/tmp/autov.pl"
    DEPTH = 0
    FLAGS = 0x1000
    OUTSIDE_SEQ = 0
    PADLIST = 0x0
    OUTSIDE = 0x0 (null)
CODE(0x26286e0)SV = IV(0x25fff20) at 0x25fff30
  REFCNT = 1
  FLAGS = (TEMP,ROK)
  RV = 0x26286e0
  SV = PVCV(0x2640750) at 0x26286e0
    REFCNT = 2
    FLAGS = (DYNFILE)
    COMP_STASH = 0x25ffdb0  "main"
    START = 0x262ea50 ===> 1
    ROOT = 0x262ea10
    GVGV::GV = 0x26287a0    "main" :: "mysub"
    FILE = "/tmp/autov.pl"
    DEPTH = 0
    FLAGS = 0x1000
    OUTSIDE_SEQ = 371
    PADLIST = 0x2648620
    PADNAME = 0x2630180(0x2667f70) PAD = 0x2628770(0x262f020)
    OUTSIDE = 0x2600140 (MAIN)
CODE(0x26286e0)
</code>```

Note how Dump's output changes between the two calls.
The first time Dump is called we just have a reference to a empty scalar.
The second time, after the actual definition of the subroutine, you can see the details that pertain to subroutines have been fleshed out: namely PADLIST (now not null), PADNAME and START (I'm not an expert of Perl guts but I think this is the actual "pointer" to the subroutine).

I hope this helps. I'd be interested in knowing what you'll discover if you'll dig deeper in the problem.

Body:
I have next program:

use warnings;
use strict;

BEGIN {
    print \&mysub;
}

sub mysub {};

print \&mysub;

Its output:

CODE(0x118e890)CODE(0x118e890)

The BEGIN block is processed in compile time. At that point definition of sub mysub is not seen by compiler yet. But program still prints right subroutine address, which it will have when defined.

Why I do not get error here? Is this some sort of autovivification?

Body:
Very interesting question. I'm writing this as an answer instead of a comment because it will be rather long, but there are still some bits I'm not entirely sure about.

I believe your intuition is correct and that it is a form of autovivification.

Devel::Peek can spread more light on what's happening.

I changed your code a little bit:

use warnings;
use strict;
use Devel::Peek;

$|++;

BEGIN {
  Dump( \&mysub );
  print \&mysub;
};

sub mysub {};

Dump( \&mysub );
print \&mysub;

I added $|++ so that buffering won't be cause of confusions, and added calls to Devel::Peek::Dump to look into the reference \&mysub. Here the output on my system:

SV = IV(0x2628628) at 0x2628638
  REFCNT = 1
  FLAGS = (TEMP,ROK)
  RV = 0x26286e0
  SV = PVCV(0x2640750) at 0x26286e0
    REFCNT = 2
    FLAGS = (DYNFILE)
    COMP_STASH = 0x25ffdb0  "main"
    ROOT = 0x0
    GVGV::GV = 0x26287a0    "main" :: "mysub"
    FILE = "/tmp/autov.pl"
    DEPTH = 0
    FLAGS = 0x1000
    OUTSIDE_SEQ = 0
    PADLIST = 0x0
    OUTSIDE = 0x0 (null)
CODE(0x26286e0)SV = IV(0x25fff20) at 0x25fff30
  REFCNT = 1
  FLAGS = (TEMP,ROK)
  RV = 0x26286e0
  SV = PVCV(0x2640750) at 0x26286e0
    REFCNT = 2
    FLAGS = (DYNFILE)
    COMP_STASH = 0x25ffdb0  "main"
    START = 0x262ea50 ===> 1
    ROOT = 0x262ea10
    GVGV::GV = 0x26287a0    "main" :: "mysub"
    FILE = "/tmp/autov.pl"
    DEPTH = 0
    FLAGS = 0x1000
    OUTSIDE_SEQ = 371
    PADLIST = 0x2648620
    PADNAME = 0x2630180(0x2667f70) PAD = 0x2628770(0x262f020)
    OUTSIDE = 0x2600140 (MAIN)
CODE(0x26286e0)

Note how Dump's output changes between the two calls.
The first time Dump is called we just have a reference to a empty scalar.
The second time, after the actual definition of the subroutine, you can see the details that pertain to subroutines have been fleshed out: namely PADLIST (now not null), PADNAME and START (I'm not an expert of Perl guts but I think this is the actual "pointer" to the subroutine).

I hope this helps. I'd be interested in knowing what you'll discover if you'll dig deeper in the problem.


问:
Is it possible to get TLSv 1.1 to work with Coldfusion 6.1
We have a legacy system that runs on Coldfusion 6.1 with JVM 1.6.0 build 24. It appears that TLSv 1.1 was added in build 111. Is it possible to get Coldfusion 6.1 to work with that build (or higher) and what would I have to do?</p>

答:
TLS 1.1 is only supported in Java 1.8 on CF10 (Oddly 1.7 and above in CF11)

I dont think CF 6.1 will work properly on higher versions of JDK. You may want to try to upgrade it to 1.8 to see if that helps.

See this Adobe Blog as a starting guide to updating your Java: http://blogs.coldfusion.com/post.cfm/how-to-change-upgrade-jdk-version-of-coldfusion-server

Also see this: http://www.coldfusionmuse.com/index.cfm/2014/12/8/colfusion-jvm-versions-sslv3-tls


问:
Listing columns in table from existing schema with SQL Alchemy
The (I think) simple question - how can I use SQL Alchemy automap extension to list the columns of a table within a schema - importantly - of an existing mysql database??

This is what I have been attempting (trying to follow docs here:
 Automap):

```<code>metadata = MetaData()
metadata.reflect(engine)

Base = automap_base(metadata=metadata)
Base.prepare()
</code>```

From this point, I can 'see' all the tables (e.g. Base.classes.table1, Base.classes.table2 etc), and can 'see' the columns in a particular table as attributes of each table (e.g. Base.classes.table1.column1, Base.classes.column2).

The question is basically is there a simple way to list the columns in the tables? (or indeed the tables in the schema?).. Something analagous to SHOW COLUMNS IN 'table1'... Maybe I am missing somethings obvious / basic here.

A perhaps related comment - I have been both a mysql admin/user and a python user for several years now, and I am only just dipping my toes into the ORM world. Maybe I am just slow, but I am finding the docs for SQL Alchemy to be pretty impenetrable - there is seems to be mountains and mountains of documentation (and whole new vocabularly to use)... or maybe I am just thinking about ORM in completely the wrong way - so any basic  guides etc - that aren't from SQL Alchemy - would be appreciated. Perhaps something along the lines of "SQL Alchemy  for SQL users" - if such a thing exists..

答:
The answer is basically contained in the question link to by Ilja Everilä.
Will mark as duplicate - but here is the direct answer to my question:

Base.classes.table1.__table__.columns  will provide you with columns information (as an SQL Alchemy ImmutableColumnCollection object, which has a handful of methods).

One of those methods will yield a list of column names, specifically:

Base.classes.table1.__table__.columns.keys()

...Basically the main thing I was missing was the "magic" __table__ attribute/object.

Body:
The (I think) simple question - how can I use SQL Alchemy automap extension to list the columns of a table within a schema - importantly - of an existing mysql database??

This is what I have been attempting (trying to follow docs here:
 Automap):

metadata = MetaData()
metadata.reflect(engine)

Base = automap_base(metadata=metadata)
Base.prepare()

From this point, I can 'see' all the tables (e.g. Base.classes.table1, Base.classes.table2 etc), and can 'see' the columns in a particular table as attributes of each table (e.g. Base.classes.table1.column1, Base.classes.column2).

The question is basically is there a simple way to list the columns in the tables? (or indeed the tables in the schema?).. Something analagous to SHOW COLUMNS IN 'table1'... Maybe I am missing somethings obvious / basic here.

A perhaps related comment - I have been both a mysql admin/user and a python user for several years now, and I am only just dipping my toes into the ORM world. Maybe I am just slow, but I am finding the docs for SQL Alchemy to be pretty impenetrable - there is seems to be mountains and mountains of documentation (and whole new vocabularly to use)... or maybe I am just thinking about ORM in completely the wrong way - so any basic  guides etc - that aren't from SQL Alchemy - would be appreciated. Perhaps something along the lines of "SQL Alchemy  for SQL users" - if such a thing exists..


问:
How to get NSData from file by using PHAsset
I have file at path

```<code>file:///var/mobile/Media/DCIM/100APPLE/IMG_0197.mov
</code>```

But when I try this code-

```<code>NSError *error;
NSData *data = [NSData dataWithContentsOfFile:assetUrl.relativePath options:NSDataReadingMappedAlways error:&error];
</code>```

I got nothing but error:

Error Domain=NSCocoaErrorDomain Code=257 "Не удалось завершить
  операцию. (Cocoa, ошибка 257)" UserInfo=0x175a61380
  {NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0197.mov,
  NSUnderlyingError=0x17424e550 "Не удалось завершить операцию.
  Operation not permitted"}

File exists but I can't read it.

But at the same time AVPlayer normally plays video file.

I tried

```<code>PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[assetUrl] options:nil];
</code>```

But I did not get any result.

答:
For me helped the following code. It's important to use relativePath instead of absoluteString.

```<code>    [[PHImageManager defaultManager] requestAVAssetForVideo:videoContent options:options resultHandler:^(AVAsset* avasset, AVAudioMix* audioMix, NSDictionary* info){
                AVURLAsset* myAsset = (AVURLAsset*)avasset;
                NSData * data = [NSData dataWithContentsOfFile:myAsset.URL.relativePath];
                if (data) {
                }
    }];
</code>```

Swift 3 version:-

```<code>PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (asset, mix, nil) in
                    let myAsset = asset as? AVURLAsset
                    do {
                        let videoData = try Data(contentsOf: (myAsset?.url)!)
                        self.selectedVideoData = videoData  //Set video data to nil in case of video
                        print("video data : \(videoData)")

                    } catch  {
                        print("exception catch at block - while uploading video")
                    }
                })
</code>```

Body:
I have file at path

file:///var/mobile/Media/DCIM/100APPLE/IMG_0197.mov

But when I try this code-

NSError *error;
NSData *data = [NSData dataWithContentsOfFile:assetUrl.relativePath options:NSDataReadingMappedAlways error:&error];

I got nothing but error:

Error Domain=NSCocoaErrorDomain Code=257 "Не удалось завершить
  операцию. (Cocoa, ошибка 257)" UserInfo=0x175a61380
  {NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0197.mov,
  NSUnderlyingError=0x17424e550 "Не удалось завершить операцию.
  Operation not permitted"}

File exists but I can't read it.

But at the same time AVPlayer normally plays video file.

I tried

PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[assetUrl] options:nil];

But I did not get any result.

Body:
For me helped the following code. It's important to use relativePath instead of absoluteString.

    [[PHImageManager defaultManager] requestAVAssetForVideo:videoContent options:options resultHandler:^(AVAsset* avasset, AVAudioMix* audioMix, NSDictionary* info){
                AVURLAsset* myAsset = (AVURLAsset*)avasset;
                NSData * data = [NSData dataWithContentsOfFile:myAsset.URL.relativePath];
                if (data) {
                }
    }];

Swift 3 version:-

PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (asset, mix, nil) in
                    let myAsset = asset as? AVURLAsset
                    do {
                        let videoData = try Data(contentsOf: (myAsset?.url)!)
                        self.selectedVideoData = videoData  //Set video data to nil in case of video
                        print("video data : \(videoData)")

                    } catch  {
                        print("exception catch at block - while uploading video")
                    }
                })


问:
Angular 2 environment not working
I have set up an angular 2 application with development fetching data from the local computer hence json-server and the production fetches from the live API.

I believed typing "ng serve --environment=prod" in the terminal would launch the app using the "environment.prod.ts", production file instead of the dev file.

However this is not the case, i see nothing that reflects the difference in settings in the preview.

Please can someone point out where I am going wrong?

答:
Did you use ng serve --prod or ng serve --environment prod or ng serve -e prod? Also, make sure in your .angular-cli.json file that "environments" has prod defined. Do note that the Angular CLI tool doesn't really do anything when generating the two environment ts files. They both have a boolean that is true if you use prod and false otherwise. If you didn't set anything in the environment files, you're not going to see any difference.

Finally, it seems that ng serve --prod may not be a good way to deploy your code https://github.com/angular/angular-cli/issues/5274

Title: Angular 2 environment not working


问:
How can I remove a commit on GitHub?
I "accidentally" pushed a commit to GitHub.

Is it possible to remove this commit?

I want to revert my GitHub repository as it was before this commit.

答:
```<code>git push -f origin HEAD^:master
</code>```

That should "undo" the push.

OwnerDisplayName: hectorsq

Title: How can I remove a commit on GitHub?

Body:
git push -f origin HEAD^:master

That should "undo" the push.

OwnerDisplayName: Dustin


问:
how to integrate graphs and pie charts in Google sites as a form?
How to integrate pie chart and graphs in google sites can anyone please help me out with google apps script</p>

答: Have you checked out Google Visualization API ?</p>


问:
How to prevent a condition from being repeated in several navigation properties in lambda expressions or linq
When I map a DB entity to my DTO in the project, I create in a single model the properties of both the header and its related table of languages.
When repeating this condition in several properties, the query that generates is very large and makes me lose a lot of time in the query. How can I raise this to have to do the comparison only once?

```<code>return s => new DtoTimelineEvent()
        {
            Id = s.tline_even_id_i,
            TimelineId = s.tline_id_i,
            Tipo = (TimeLineEventTypes)s.even_tip_id_i,
            Fecha = s.fecha_dt,

            Titulo = s.t_tline_even_rel_idi.Any(a => a.idi_id_t == (byte)cultura) ? s.t_tline_even_rel_idi.FirstOrDefault(a => a.idi_id_t == (byte)cultura).Titulo : s.t_tline_even_rel_idi.FirstOrDefault().Titulo,
            Descripcion = s.t_tline_even_rel_idi.Any(a => a.idi_id_t == (byte)cultura) ? s.t_tline_even_rel_idi.FirstOrDefault(a => a.idi_id_t == (byte)cultura).Descripcion : s.t_tline_even_rel_idi.FirstOrDefault().Descripcion,

            SocialId = s.t_tline_even_rel_idi.Any(a => a.idi_id_t == (byte)cultura) ?
               s.t_tline_even_rel_idi.FirstOrDefault(a => a.idi_id_t == (byte)cultura).obj_id :
               s.t_tline_even_rel_idi.FirstOrDefault().obj_id,
        }
</code>```

"Titulo", "Descripcion" and "SocialId" have the same condition and are repeated in many more fields, how can I improve this query?

答:
Do it in two steps: first, fetch the object on which Titulo, Description, and SocialId are defined, and then project them out:

```<code>return s => {
    var common = s.t_tline_even_rel_idi.Any(a => a.idi_id_t == (byte)cultura)
        ? s.t_tline_even_rel_idi.FirstOrDefault(a => a.idi_id_t == (byte)cultura)
        : s.t_tline_even_rel_idi.FirstOrDefault();
    return new DtoTimelineEvent() {
        Id = s.tline_even_id_i,
        TimelineId = s.tline_id_i,
        Tipo = (TimeLineEventTypes)s.even_tip_id_i,
        Fecha = s.fecha_dt,
        Titolo = common.Titolo,
        Description = common.Description,
        SocialId = common.obj_id
    };
};
</code>```

This fetches common object only once, and then its fields are referenced in the constructor of DTO.

Body:
When I map a DB entity to my DTO in the project, I create in a single model the properties of both the header and its related table of languages.
When repeating this condition in several properties, the query that generates is very large and makes me lose a lot of time in the query. How can I raise this to have to do the comparison only once?

return s => new DtoTimelineEvent()
        {
            Id = s.tline_even_id_i,
            TimelineId = s.tline_id_i,
            Tipo = (TimeLineEventTypes)s.even_tip_id_i,
            Fecha = s.fecha_dt,

            Titulo = s.t_tline_even_rel_idi.Any(a => a.idi_id_t == (byte)cultura) ? s.t_tline_even_rel_idi.FirstOrDefault(a => a.idi_id_t == (byte)cultura).Titulo : s.t_tline_even_rel_idi.FirstOrDefault().Titulo,
            Descripcion = s.t_tline_even_rel_idi.Any(a => a.idi_id_t == (byte)cultura) ? s.t_tline_even_rel_idi.FirstOrDefault(a => a.idi_id_t == (byte)cultura).Descripcion : s.t_tline_even_rel_idi.FirstOrDefault().Descripcion,

            SocialId = s.t_tline_even_rel_idi.Any(a => a.idi_id_t == (byte)cultura) ?
               s.t_tline_even_rel_idi.FirstOrDefault(a => a.idi_id_t == (byte)cultura).obj_id :
               s.t_tline_even_rel_idi.FirstOrDefault().obj_id,
        }

"Titulo", "Descripcion" and "SocialId" have the same condition and are repeated in many more fields, how can I improve this query?

Body:
Do it in two steps: first, fetch the object on which Titulo, Description, and SocialId are defined, and then project them out:

return s => {
    var common = s.t_tline_even_rel_idi.Any(a => a.idi_id_t == (byte)cultura)
        ? s.t_tline_even_rel_idi.FirstOrDefault(a => a.idi_id_t == (byte)cultura)
        : s.t_tline_even_rel_idi.FirstOrDefault();
    return new DtoTimelineEvent() {
        Id = s.tline_even_id_i,
        TimelineId = s.tline_id_i,
        Tipo = (TimeLineEventTypes)s.even_tip_id_i,
        Fecha = s.fecha_dt,
        Titolo = common.Titolo,
        Description = common.Description,
        SocialId = common.obj_id
    };
};

This fetches common object only once, and then its fields are referenced in the constructor of DTO.


问:
Count the number of viewed pages that contain an exact string
I would like to count the number of viewed pages that contain some customer tagging, my code is currently returning the same value for all 3 counts and these values are far too high, can anyone suggest what the issue is here?</p>

```<code>SELECT
  Date,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff=" THEN 1 ELSE 0 END) AS Affinity,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff2=" THEN 1 ELSE 0 END) AS Addon_Affinity,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff3=" THEN 1 ELSE 0 END) AS Style_Affinity

FROM `dataset.ga_sessions_*` AS t
  CROSS JOIN UNNEST(hits) AS hits
WHERE (_TABLE_SUFFIX BETWEEN '20170703' AND '20170703')
group by date
</code>```

答:
Other possibility would be to solve this query like:

```<code>WITH data AS(
  select "20170701" as date, ARRAY<STRUCT<page STRUCT<pagePath STRING> >> [STRUCT(STRUCT('?aff=' as pagePath) as page), STRUCT(STRUCT('?aff=' as pagePath) as page), STRUCT(STRUCT('/test' as pagePath) as page), STRUCT(STRUCT('?aff2=' as pagePath) as page), STRUCT(STRUCT('?aff=' as pagePath) as page)] hits union all
  select "20170701" as date, ARRAY<STRUCT<page STRUCT<pagePath STRING> >> [STRUCT(STRUCT('?aff2=' as pagePath) as page), STRUCT(STRUCT('?aff2=' as pagePath) as page), STRUCT(STRUCT('?aff3=' as pagePath) as page), STRUCT(STRUCT('?aff3=' as pagePath) as page), STRUCT(STRUCT('?aff=' as pagePath) as page)] hits
)

SELECT
  date,
  sum((select countif(hits.page.pagepath like "?aff=") from unnest(hits) hits)) Affinity,
  sum((select countif(hits.page.pagepath like "?aff2=") from unnest(hits) hits)) Addon_Affinity,
  sum((select countif(hits.page.pagepath like "?aff3=") from unnest(hits) hits)) Style_Affinity
FROM data
GROUP BY
date
</code>```

Where data is a simulation of your ga_sessions data.

ContentLicense: CC BY-SA 4.0

Body:
I would like to count the number of viewed pages that contain some customer tagging, my code is currently returning the same value for all 3 counts and these values are far too high, can anyone suggest what the issue is here?

SELECT
  Date,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff=" THEN 1 ELSE 0 END) AS Affinity,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff2=" THEN 1 ELSE 0 END) AS Addon_Affinity,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff3=" THEN 1 ELSE 0 END) AS Style_Affinity

FROM `dataset.ga_sessions_*` AS t
  CROSS JOIN UNNEST(hits) AS hits
WHERE (_TABLE_SUFFIX BETWEEN '20170703' AND '20170703')
group by date

Body:
Other possibility would be to solve this query like:

WITH data AS(
  select "20170701" as date, ARRAY<STRUCT<page STRUCT<pagePath STRING> >> [STRUCT(STRUCT('?aff=' as pagePath) as page), STRUCT(STRUCT('?aff=' as pagePath) as page), STRUCT(STRUCT('/test' as pagePath) as page), STRUCT(STRUCT('?aff2=' as pagePath) as page), STRUCT(STRUCT('?aff=' as pagePath) as page)] hits union all
  select "20170701" as date, ARRAY<STRUCT<page STRUCT<pagePath STRING> >> [STRUCT(STRUCT('?aff2=' as pagePath) as page), STRUCT(STRUCT('?aff2=' as pagePath) as page), STRUCT(STRUCT('?aff3=' as pagePath) as page), STRUCT(STRUCT('?aff3=' as pagePath) as page), STRUCT(STRUCT('?aff=' as pagePath) as page)] hits
)

SELECT
  date,
  sum((select countif(hits.page.pagepath like "?aff=") from unnest(hits) hits)) Affinity,
  sum((select countif(hits.page.pagepath like "?aff2=") from unnest(hits) hits)) Addon_Affinity,
  sum((select countif(hits.page.pagepath like "?aff3=") from unnest(hits) hits)) Style_Affinity
FROM data
GROUP BY
date

Where data is a simulation of your ga_sessions data.


问:
Convert time.Time to string
I'm trying to add some values from my database to a []string in Go. Some of these are timestamps.

I get the error:

cannot use U.Created_date (type time.Time) as type string in array element

Can I convert time.Time to string?

```<code>type UsersSession struct {
    Userid int
    Timestamp time.Time
    Created_date time.Time
}

type Users struct {
    Name string
    Email string
    Country string
    Created_date time.Time
    Id int
    Hash string
    IP string
}
</code>```

-

```<code>var usersArray = [][]string{}

rows, err := db.Query("SELECT u.id, u.hash, u.name, u.email, u.country, u.IP, u.created_date, us.timestamp, us.created_date FROM usersSession AS us LEFT JOIN users AS u ON u.id = us.userid WHERE us.timestamp + interval 30 minute >= now()")

U := Users{}
US := UsersSession{}

for rows.Next() {
    err = rows.Scan(&U.Id, &U.Hash, &U.Name, &U.Email, &U.Country, &U.IP, &U.Created_date, &US.Timestamp, &US.Created_date)
    checkErr(err)

    userid_string := strconv.Itoa(U.Id)
    user := []string{userid_string, U.Hash, U.Name, U.Email, U.Country, U.IP, U.Created_date, US.Timestamp, US.Created_date}
    // -------------
    // ^ this is where the error occurs
    // cannot use U.Created_date (type time.Time) as type string in array element (for US.Created_date and US.Timestamp aswell)
    // -------------

    usersArray = append(usersArray, user)
    log.Print("usersArray: ", usersArray)
}
</code>```

EDIT

I added the following. It works now, thanks.

```<code>userCreatedDate := U.Created_date.Format("2006-01-02 15:04:05")
userSessionCreatedDate := US.Created_date.Format("2006-01-02 15:04:05")
userSessionTimestamp := US.Timestamp.Format("2006-01-02 15:04:05")
</code>```

答:
Please find the simple solution to convete Date & Time Format in Go Lang. Please find the example below.

Package Link: https://github.com/vigneshuvi/GoDateFormat.

Please find the plackholders:https://medium.com/@Martynas/formatting-date-and-time-in-golang-5816112bf098

```<code>package main

// Import Package
import (
    "fmt"
    "time"
    "github.com/vigneshuvi/GoDateFormat"
)

func main() {
    fmt.Println("Go Date Format(Today - 'yyyy-MM-dd HH:mm:ss Z'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MM-dd HH:mm:ss Z")))
    fmt.Println("Go Date Format(Today - 'yyyy-MMM-dd'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MMM-dd")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS tt'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS tt")))
}

func GetToday(format string) (todayString string){
    today := time.Now()
    todayString = today.Format(format);
    return
}
</code>```

Title: Convert time.Time to string

Body:
I'm trying to add some values from my database to a []string in Go. Some of these are timestamps.

I get the error:

cannot use U.Created_date (type time.Time) as type string in array element

Can I convert time.Time to string?

type UsersSession struct {
    Userid int
    Timestamp time.Time
    Created_date time.Time
}

type Users struct {
    Name string
    Email string
    Country string
    Created_date time.Time
    Id int
    Hash string
    IP string
}

-

var usersArray = [][]string{}

rows, err := db.Query("SELECT u.id, u.hash, u.name, u.email, u.country, u.IP, u.created_date, us.timestamp, us.created_date FROM usersSession AS us LEFT JOIN users AS u ON u.id = us.userid WHERE us.timestamp + interval 30 minute >= now()")

U := Users{}
US := UsersSession{}

for rows.Next() {
    err = rows.Scan(&U.Id, &U.Hash, &U.Name, &U.Email, &U.Country, &U.IP, &U.Created_date, &US.Timestamp, &US.Created_date)
    checkErr(err)

    userid_string := strconv.Itoa(U.Id)
    user := []string{userid_string, U.Hash, U.Name, U.Email, U.Country, U.IP, U.Created_date, US.Timestamp, US.Created_date}
    // -------------
    // ^ this is where the error occurs
    // cannot use U.Created_date (type time.Time) as type string in array element (for US.Created_date and US.Timestamp aswell)
    // -------------

    usersArray = append(usersArray, user)
    log.Print("usersArray: ", usersArray)
}

EDIT

I added the following. It works now, thanks.

userCreatedDate := U.Created_date.Format("2006-01-02 15:04:05")
userSessionCreatedDate := US.Created_date.Format("2006-01-02 15:04:05")
userSessionTimestamp := US.Timestamp.Format("2006-01-02 15:04:05")

Body:
Please find the simple solution to convete Date & Time Format in Go Lang. Please find the example below.

Package Link: https://github.com/vigneshuvi/GoDateFormat.

Please find the plackholders:https://medium.com/@Martynas/formatting-date-and-time-in-golang-5816112bf098

package main

// Import Package
import (
    "fmt"
    "time"
    "github.com/vigneshuvi/GoDateFormat"
)

func main() {
    fmt.Println("Go Date Format(Today - 'yyyy-MM-dd HH:mm:ss Z'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MM-dd HH:mm:ss Z")))
    fmt.Println("Go Date Format(Today - 'yyyy-MMM-dd'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MMM-dd")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS tt'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS tt")))
}

func GetToday(format string) (todayString string){
    today := time.Now()
    todayString = today.Format(format);
    return
}


问:
Problems Opening Firefox
I'm trying to write a Python script to open a URL, but I keep getting errors when I try to use it:

```<code>import webbrowser

firefox = webbrowser.get('mozilla')
</code>```

This is the error:

```<code>Traceback (most recent call last):
  File "C:\Users\Gelu\Documents\CSCI\Image URL Generator\src\Generator.py", line 8, in <module>
    firefox = webbrowser.get('mozilla')
  File "C:\Program Files\Python31\lib\webbrowser.py", line 53, in get
    raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser
</code>```

Any ideas why this isn't working?

答:
For me the issue was, webbrowser.py did not recognize any other browser in my windows machine. So, i had to register the browser and then launch a new tab.

```<code>import webbrowser
urL='https://www.google.com'
firefox_path="C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(firefox_path),1)
webbrowser.get('firefox').open_new_tab(urL)
</code>```

Hope this helps some one.

Also some python notes for reference on what register does ,

webbrowser.register(name, constructor[, instance])¶

Register the browser type name. Once a browser type is registered, the get() function can return a controller for that browser type. If instance is not provided, or is None, constructor will be called without parameters to create an instance when needed. If instance is provided, constructor will never be called, and may be None.This entry point is only useful if you plan to either set the BROWSER variable or call get() with a nonempty argument matching the name of a handler you declare.

Title: Problems Opening Firefox

Body:
I'm trying to write a Python script to open a URL, but I keep getting errors when I try to use it:

import webbrowser

firefox = webbrowser.get('mozilla')

This is the error:

Traceback (most recent call last):
  File "C:\Users\Gelu\Documents\CSCI\Image URL Generator\src\Generator.py", line 8, in <module>
    firefox = webbrowser.get('mozilla')
  File "C:\Program Files\Python31\lib\webbrowser.py", line 53, in get
    raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser

Any ideas why this isn't working?

Body:
For me the issue was, webbrowser.py did not recognize any other browser in my windows machine. So, i had to register the browser and then launch a new tab.

import webbrowser
urL='https://www.google.com'
firefox_path="C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(firefox_path),1)
webbrowser.get('firefox').open_new_tab(urL)

Hope this helps some one.

Also some python notes for reference on what register does ,

webbrowser.register(name, constructor[, instance])¶

Register the browser type name. Once a browser type is registered, the get() function can return a controller for that browser type. If instance is not provided, or is None, constructor will be called without parameters to create an instance when needed. If instance is provided, constructor will never be called, and may be None.This entry point is only useful if you plan to either set the BROWSER variable or call get() with a nonempty argument matching the name of a handler you declare.


问:
saving operators in arrays, error
To give an idea of what I want elaborate with this code is the following:

Enter two numbers: 10 7

Choose Operator: e.g. (+, - , * and /)

What's 10 * 7?

Correct!

```<code>int[] arr = new int[5];

System.out.println("enter two numbers: ");
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();

System.out.println("Choose Operator: ");
arr[3] = sc.nextInt();

int operator = arr[1]+arr[3]+arr[2];

System.out.print("what's "+operator);
int svar = sc.nextInt();

if (svar == operator)
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is "+operator);
</code>```

Now I'm having a problem with running some aspects within this code. It works fine to compile but each time the program asks for to "choose operator" the compiler responses with the following error:

Exception in thread "main"

java.util.InputMismatchException   at

java.util.Scanner.throwFor(Unknown

Source)    at

java.util.Scanner.next(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)

at test1.main(test1.java:13)

I wonder how I'm going to deal with this one. But the goal would be to "save" the desired operator, and then put it together with arr[1] and arr[2] (shown in int operator) to "sort of" create this whole mathematical operation. But the error occurs when I choose one particular operator.

I would appreciate some help with this one. Thank you!

答:
Here </p>

```<code>System.out.println("Choose Operator: ");
    arr[3] = sc.nextInt();
</code>```

<p>you are trying to store a '+' operator as an int, maybe you should read a line and then determine what to do with the read in input. </p>

Title: saving operators in arrays, error

Body:
To give an idea of what I want elaborate with this code is the following:

Enter two numbers: 10 7

Choose Operator: e.g. (+, - , * and /)

What's 10 * 7?

Correct!

int[] arr = new int[5];

System.out.println("enter two numbers: ");
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();

System.out.println("Choose Operator: ");
arr[3] = sc.nextInt();

int operator = arr[1]+arr[3]+arr[2];

System.out.print("what's "+operator);
int svar = sc.nextInt();

if (svar == operator)
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is "+operator);

Now I'm having a problem with running some aspects within this code. It works fine to compile but each time the program asks for to "choose operator" the compiler responses with the following error:

Exception in thread "main"

java.util.InputMismatchException   at

java.util.Scanner.throwFor(Unknown

Source)    at

java.util.Scanner.next(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)

at test1.main(test1.java:13)

I wonder how I'm going to deal with this one. But the goal would be to "save" the desired operator, and then put it together with arr[1] and arr[2] (shown in int operator) to "sort of" create this whole mathematical operation. But the error occurs when I choose one particular operator.

I would appreciate some help with this one. Thank you!

Body:
Here

System.out.println("Choose Operator: ");
    arr[3] = sc.nextInt();

you are trying to store a '+' operator as an int, maybe you should read a line and then determine what to do with the read in input.


问:
Oracle Apex Tabular forms apex_application.g_f array not populating
I am in the process of developing a Tabular form based on a simple query from a table. I have added the add row functionality in the form.

Now, here is what I want to do. Let's say my query is based on emp table, and when the user enters the empid I should fetch the empname and display it in the textfield next to empid. I have tried using apex_application.g_f arrays but this is always returning count as 0. I have tried arrays g_f01 to g_f10 just to see if the array is populated somwhere but the count apex_application.g_f01.count to apex_application.g_f10.count is always coming as 0.

However I tried using the below javascript code and its showing the values.

```<code>for (var i = 0; i < document.wwv_flow.f04.length; i++)
{
    var vTemp=$(document.wwv_flow.f04[i]).val();
    alert(vTemp);
}
</code>```

Just to add a point, I have the row selector as well. I use a dynamic action to get the count.

Can someone help me to identify why the apex_application.g_f array is not populated?

答: The apex_application.g_f arrays are only populated when the page is submitted, i.e. they can be accessed from processes that run on page submit.  But they do not persist when the page is reloaded.  Javascript is the right way to access these from the page itself.

Body:
I am in the process of developing a Tabular form based on a simple query from a table. I have added the add row functionality in the form.

Now, here is what I want to do. Let's say my query is based on emp table, and when the user enters the empid I should fetch the empname and display it in the textfield next to empid. I have tried using apex_application.g_f arrays but this is always returning count as 0. I have tried arrays g_f01 to g_f10 just to see if the array is populated somwhere but the count apex_application.g_f01.count to apex_application.g_f10.count is always coming as 0.

However I tried using the below javascript code and its showing the values.

for (var i = 0; i < document.wwv_flow.f04.length; i++)
{
    var vTemp=$(document.wwv_flow.f04[i]).val();
    alert(vTemp);
}

Just to add a point, I have the row selector as well. I use a dynamic action to get the count.

Can someone help me to identify why the apex_application.g_f array is not populated?


问:
Is there an option to run second time the same program in Qt?
I'm creating simple online game in Qt Creator. I've created server project which analyse received data and take decisions. Also I created player project which sends requests to server for permission to move, shoot etc. Player project should be universal for Player 1 and Player 2.

Is there an option to run player project twice in Qt Creator?
I need it to test how server and player project behaves when second player connects.

答: I'm using Qt Creator 4.3.1: You can do that in Tools > Options... > Build & Run. Under the General tab, set the "Stop applications before building:" to "None"


问:
Crashlytics. Project dev is inactive
When I'm trying to upload new flavor build, I get an error:

WARN - Crashlytics had a problem uploading the distribution. Project dev is inactive

How can I fix it and add new flavor for tests?

答:
I fixed the issue running the new flavour (in case you have a new one) or the main one (app itself) in my device. Remember you need to have:

```<code>Fabric.with(new Fabric.Builder(application)
    .kits(new Crashlytics())
    .debuggable(BuildConfig.DEBUG)
    .build()
);
</code>```

in your Application in order to make Fabric triggering the creation of a new app :-)

Title: Crashlytics. Project dev is inactive

Body:
I fixed the issue running the new flavour (in case you have a new one) or the main one (app itself) in my device. Remember you need to have:

Fabric.with(new Fabric.Builder(application)
    .kits(new Crashlytics())
    .debuggable(BuildConfig.DEBUG)
    .build()
);

in your Application in order to make Fabric triggering the creation of a new app :-)


问:
Disable front end editing in Joomla 3
How do you disable front-end editing in joomla 3.6.5? I need to be able to give people a sneak peek sometimes when a site is offline because it's in development, but don't want them to accidentally edit my articles in front end.
I have turned everything to 'hide' option in my admin login. I went to front end and still see 'edit' option in modules.

I really hope that by now Joomla has a way to accomplish this without hacking, but if it's the only way then so be it. Can anyone help?

Thanks in advance.

答:
Other people can only edit articles if they have the appropriate autorisations (Author, Editor, Publisher, Super User).
When you're logged in as a Super User you will see an option to edit the article. This does not mean, that a 'Registered' user sees this option.
If they do see the edit-option, they probably have the wrong autorisation. Then you might consider changing this.</p>

Title: Disable front end editing in Joomla 3


问:
Passing a variable to a function (which alters said variable) repeatedly
I'm having a play with Rust and, probably biting off far more than I can chew, am trying to write a module that will encapsulate my database traffic for the rest of the application. The code I'm struggling with is the following:

```<code>pub fn create_statement(cypher: &str, params: &HashMap<&str, &str>) -> rusted_cypher::Statement {
    let mut statement = rusted_cypher::Statement::new(cypher);
    for (field, value) in params.iter() {
        statement.with_param(field.to_owned(), value.to_owned());
    }
    return statement;
}
</code>```

This gives the following error: error[E0382]: use of moved value: statement. My searching has, I think, lead me to what this means (the Statement struct is not copyable, thus gets moved and is then ... effectively no longer accessible, I guess?), but I'm not sure how to get around it. Can anyone point me in the direction of a solution?

答:
While this doesn't answer your underlying question about passing a mutable value in the same way as your current code.

rusted-cypher::Statement has a set_parameters method which takes a &BTreeMap<String, T> as its only argument.

You can see this function in the rusted-cypher's source code.

A conceivable implementation:

```<code>pub fn create_statement(cypher: &str, params: &BTreeMap<&str, &str>) -> rusted_cypher::Statement {
   let mut statement = rusted_cypher::Statement::new(cypher);
   statement.set_parameters(params);
   statement
}
</code>```

Body:
I'm having a play with Rust and, probably biting off far more than I can chew, am trying to write a module that will encapsulate my database traffic for the rest of the application. The code I'm struggling with is the following:

pub fn create_statement(cypher: &str, params: &HashMap<&str, &str>) -> rusted_cypher::Statement {
    let mut statement = rusted_cypher::Statement::new(cypher);
    for (field, value) in params.iter() {
        statement.with_param(field.to_owned(), value.to_owned());
    }
    return statement;
}

This gives the following error: error[E0382]: use of moved value: statement. My searching has, I think, lead me to what this means (the Statement struct is not copyable, thus gets moved and is then ... effectively no longer accessible, I guess?), but I'm not sure how to get around it. Can anyone point me in the direction of a solution?

Body:
While this doesn't answer your underlying question about passing a mutable value in the same way as your current code.

rusted-cypher::Statement has a set_parameters method which takes a &BTreeMap<String, T> as its only argument.

You can see this function in the rusted-cypher's source code.

A conceivable implementation:

pub fn create_statement(cypher: &str, params: &BTreeMap<&str, &str>) -> rusted_cypher::Statement {
   let mut statement = rusted_cypher::Statement::new(cypher);
   statement.set_parameters(params);
   statement
}


问:
unable to validate email and number
I need help because I have added the following javascript(mentioned below in code) to my form and I am passing ID to js, but unable to validate it.

Javascript Code

```<code>function validateForm() {
    var x = document.getElementById('emailid').value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    var txt = document.getElementById('mobNo');
    var filter = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;
    var test_bool = filter.test(txt.value);
    if (test_bool == false) {
        alert('Please enter valid Mobile Number ');
        txt.focus();
        return false;
    }
}
</code>```

HTML

```<code><div class="form-group">
    <input type="email" class="form-control" value="" placeholder="Email ID" id="emailid" name="Email" required="required" maxlength="70" />
    <label class="input-field-icon icon-email" for="login-email"></label>
</div>
<div class="form-group">
    <input type="text" class="form-control" value="" placeholder="Mobile Number" id="mobNo" name="number" required="required" maxlength="14" />
    <label class="input-field-icon icon-email" for="login-email"></label>
</div>
</code>```

答:
if you will use a form tag to validate this data you may use onsubmit attribute.

Here is documentation

else if you want to use a event handler for form you may pass event data and prevent it if form not valid.

Here is some usefull information

Title: unable to validate email and number

Body:
I need help because I have added the following javascript(mentioned below in code) to my form and I am passing ID to js, but unable to validate it.

Javascript Code

function validateForm() {
    var x = document.getElementById('emailid').value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    var txt = document.getElementById('mobNo');
    var filter = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;
    var test_bool = filter.test(txt.value);
    if (test_bool == false) {
        alert('Please enter valid Mobile Number ');
        txt.focus();
        return false;
    }
}

HTML

    <input type="email" class="form-control" value="" placeholder="Email ID" id="emailid" name="Email" required="required" maxlength="70" />

    <input type="text" class="form-control" value="" placeholder="Mobile Number" id="mobNo" name="number" required="required" maxlength="14" />


问:
keystonejs cors error with middleware
I keep getting a CORS error when making an http req to keystonejs apis that work fine in the browser.  I added this middleware to middleware.js and it is getting called when making the request:

routes/middleware.js

```<code>exports.corsAPI = function (req,res,next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');

  keystone.initAPI(req, res, next);
};
</code>```

and modified the routes/index.js

```<code>exports = module.exports = function(app) {

    app.get('/api/post/list', middleware.corsAPI, routes.api.posts.list);
    app.all('/api/post/create', middleware.corsAPI, routes.api.posts.create);
    app.get('/api/post/:id', middleware.corsAPI, routes.api.posts.get);
    app.all('/api/post/:id/update', middleware.corsAPI, routes.api.posts.update);
    app.get('/api/post/:id/remove', middleware.corsAPI, routes.api.posts.remove);

}
</code>```

答:
In keystone.js:

```<code>keystone.set('cors allow origin', true);
keystone.set('cors allow methods', true);
keystone.set('cors allow headers', true);
</code>```

In routes\index.js:
either:

```<code>app.get('/api/stuff', [keystone.middleware.api, keystone.middleware.cors], routes.api.workshop.getStuff);
</code>```

or:

```<code>app.get('/api/stuff', keystone.middleware.cors, routes.api.workshop.getStuff);
</code>```

and all the other routes accordingly.
That's all that is necessary to enable CORS headers.

Title: keystonejs cors error with middleware

Body:
I keep getting a CORS error when making an http req to keystonejs apis that work fine in the browser.  I added this middleware to middleware.js and it is getting called when making the request:

routes/middleware.js

exports.corsAPI = function (req,res,next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');

  keystone.initAPI(req, res, next);
};

and modified the routes/index.js

exports = module.exports = function(app) {

    app.get('/api/post/list', middleware.corsAPI, routes.api.posts.list);
    app.all('/api/post/create', middleware.corsAPI, routes.api.posts.create);
    app.get('/api/post/:id', middleware.corsAPI, routes.api.posts.get);
    app.all('/api/post/:id/update', middleware.corsAPI, routes.api.posts.update);
    app.get('/api/post/:id/remove', middleware.corsAPI, routes.api.posts.remove);

}

Body:
In keystone.js:

keystone.set('cors allow origin', true);
keystone.set('cors allow methods', true);
keystone.set('cors allow headers', true);

In routes\index.js:
either:

app.get('/api/stuff', [keystone.middleware.api, keystone.middleware.cors], routes.api.workshop.getStuff);

or:

app.get('/api/stuff', keystone.middleware.cors, routes.api.workshop.getStuff);

and all the other routes accordingly.
That's all that is necessary to enable CORS headers.


问:
python: elasticsearch-dsl: update body not fully transfered
'I am accessing elasticsearch via the python module elasticsearch-dsl.

I have a body that I am passing to the update() function in order to transfer some information to the index:

```<code>>>> hits = client.search(index='xyz', body=body_search)
>>> print hits['hits']['hits'][0]['_source']['authors']
>>> [{u'id': u'None', u'name': u'Xyz'}, {u'id': u'None', u'name': u'Zyx'}, {u'id': None, u'name': u'Yzx'}]

>>> body_update = { "doc": { "authors": None } }
>>> body_update['doc']['authors'] = new_authors
>>> print body_update
>>> {'doc': {'authors': [{u'id': u'XYZ_0', u'name': u'Xyz'}, {u'id': u'ZYX_0', u'name': u'Zyx'}, {u'id': 'YZX_0', u'name': u'Yzx'}]}}

>>> client.update(index='xyz', doc_type='zyx', id=123, body=body_update)
>>> print client.search(index='xyz', body=body_search)['hits']['hits'][0]['_source']['authors']
>>> [{u'id': u'XYZ_0', u'name': u'Xyz'}, {u'id': u'ZYX_0', u'name': u'Zyx'}, {u'id': None, u'name': u'Yzx'}]
</code>```

The body contains the respective information, but not all of it is transfered. I checked that as expected, only one document is returned by the searches. No error messages. Same behavior on repetition (exact same authors).

答: Ok, I just had to add refresh=True to the update() query.

Body:
'I am accessing elasticsearch via the python module elasticsearch-dsl.

I have a body that I am passing to the update() function in order to transfer some information to the index:

>>> hits = client.search(index='xyz', body=body_search)
>>> print hits['hits']['hits'][0]['_source']['authors']
>>> [{u'id': u'None', u'name': u'Xyz'}, {u'id': u'None', u'name': u'Zyx'}, {u'id': None, u'name': u'Yzx'}]

>>> body_update = { "doc": { "authors": None } }
>>> body_update['doc']['authors'] = new_authors
>>> print body_update
>>> {'doc': {'authors': [{u'id': u'XYZ_0', u'name': u'Xyz'}, {u'id': u'ZYX_0', u'name': u'Zyx'}, {u'id': 'YZX_0', u'name': u'Yzx'}]}}

>>> client.update(index='xyz', doc_type='zyx', id=123, body=body_update)
>>> print client.search(index='xyz', body=body_search)['hits']['hits'][0]['_source']['authors']
>>> [{u'id': u'XYZ_0', u'name': u'Xyz'}, {u'id': u'ZYX_0', u'name': u'Zyx'}, {u'id': None, u'name': u'Yzx'}]

The body contains the respective information, but not all of it is transfered. I checked that as expected, only one document is returned by the searches. No error messages. Same behavior on repetition (exact same authors).


问:
Send MIDI events to a stand-alone sampler/synth
I'd like to develop a very simple program to map PC keyboard to a piano keyboard: each time the user press a key a MIDI event is generated and a stand-alone sampler/synth (such as SFZ+ or other) receives these events and plays a sound.

I am able to generate MIDI events (using midiOutShortMsg), but they are sent directly to the FM synth (and so played by it), I'd like to send them to an external software. The code must be in C/C++.

Could you help me?

Tnx.

答: sounds like you are not opening the correct device. midiOutOpen takes a device ID as second parameter; did you check if the one you pass is the correct one (using  midiOutGetNumDevs and midiOutGetDevCaps)?</p>


问:
Select Input on Label Click
I want to search data
but i have multiple label like firstname,lastname and Username
and only one input
i want to place different placeholder based on the label clicked
how this possible with jquery and javascript

Thanks In Advance

答:
You can set the Property of an input using jquery

```<code>$('input').attr("placeholder", "your text");
</code>```

See the demo here

Title: Select Input on Label Click

Body:
You can set the Property of an input using jquery

$('input').attr("placeholder", "your text");

See the demo here


问:
Can you specify Resource Files in the Command Line call for Robot Framework
Can you specify resource files in the command line for Robot Framework similar to variable files? http://robotframework.googlecode.com/svn/tags/robotframework-2.5.5/doc/userguide/RobotFrameworkUserGuide.html#variable-files

A lot of our tests use the same resource file and we're trying to see if we can speed up execution by only including the resource file once.

答:
I'm not really sure whether you would be fine with a workaround, but there is Import Resource keyword

http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Import%20Resource

So I'd say, that you can use that at least to test.

But if your expectation is that if there is resource in multiple robot files and so it is loaded multiple times I'd just guess this is not correct assumption, so you won't save a second using this.

But I'm just a beginner with Robot Framework, so there is a chance I'm wrong...


问:
Editing Json files via node.js from the html input tag(Front end (angularJs+Html))
I have a bunch of json array files which I read and display in form of a table. Only the header of the table which are the keys of the json object need to editable. So the user could choose his own header and that need to be changed in the json file. My server side code is with node.js and front end with angularJs+html. For the following json file.

[
{"name":"item 1", "id": 1},
{"name":"item 2", "id": 2}
]```

Below is the picture of how my table looks like.

P.S: I have seen many questions regarding this but most of them suggests writing the whole file again with fs.write.
I am asking for a way that I can only change the keys of the json objects through header input of the table.

答: Use ng-model with header and get the data in your angular controller.Then using $http post your updated data. And update value of your keys.

Body:
I have a bunch of json array files which I read and display in form of a table. Only the header of the table which are the keys of the json object need to editable. So the user could choose his own header and that need to be changed in the json file. My server side code is with node.js and front end with angularJs+html. For the following json file.

[
{"name":"item 1", "id": 1},
{"name":"item 2", "id": 2}
]

Below is the picture of how my table looks like.

P.S: I have seen many questions regarding this but most of them suggests writing the whole file again with fs.write.
I am asking for a way that I can only change the keys of the json objects through header input of the table.


问:
How to render has_many in template?
I have two classes : Letter and LetterFiles (attached files to the letter):

```<code>class Letter extends DataObject {
    private static $db = array(
        'Sender' => 'Text',
        'SendTo' => 'Text',
        ...
    );

    private static $has_many = array(
        'Letters' => 'LetterFiles'
    );
    ...
}

class LetterFiles extends File {
    private static $has_one = array(
        'Files' => 'Letter'
    );
    ...
}
</code>```

I want to show all letters and all attached files on LetterPage:

```<code>class LetterPage extends Page {
}

class LetterPage_Controller extends Page_Controller {
    public function index() {
        $letters = Letter::get()->sort('DateUpload');
        return array(
            'AllLetters' => $letters
        );
    }
}
</code>```

I try to use template LetterPage.ss:

```<code>   <% loop $AllLetters %>
        <tr>
            ...
            <td>$Sender</td>
            <td>$SendTo</td>
            <td>$Theme</td>
            <td>
                  <% loop $Files %>
                      $Name
                  <% end_loop %>
            </td>
        </tr>
   <% end_loop %>
</code>```

But <% loop $Files %> doesn't work. How to show attached files in this template?

答:
Think you're just using the wrong relation name, should be Letters and not Files:</p>

```<code><% loop AllLetters %>
    $Sender
    $SendTo
    <% loop Letters %>
        $ID
    <% end_loop %>
<% end_loop %>
</code>```

Title: How to render has_many in template?

Body:
I have two classes : Letter and LetterFiles (attached files to the letter):

class Letter extends DataObject {
    private static $db = array(
        'Sender' => 'Text',
        'SendTo' => 'Text',
        ...
    );

    private static $has_many = array(
        'Letters' => 'LetterFiles'
    );
    ...
}

class LetterFiles extends File {
    private static $has_one = array(
        'Files' => 'Letter'
    );
    ...
}

I want to show all letters and all attached files on LetterPage:

class LetterPage extends Page {
}

class LetterPage_Controller extends Page_Controller {
    public function index() {
        $letters = Letter::get()->sort('DateUpload');
        return array(
            'AllLetters' => $letters
        );
    }
}

I try to use template LetterPage.ss:

   <% loop $AllLetters %>

            ...
            $Sender
            $SendTo
            $Theme

                  <% loop $Files %>
                      $Name
                  <% end_loop %>

   <% end_loop %>

But <% loop $Files %> doesn't work. How to show attached files in this template?

Body:
Think you're just using the wrong relation name, should be Letters and not Files:

<% loop AllLetters %>
    $Sender
    $SendTo
    <% loop Letters %>
        $ID
    <% end_loop %>
<% end_loop %>


问:
php: wanted to replace '\\\/' from string
I wanted to replace en/us with es/es:</p>

```<code><?php

$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');

$json = json_encode($str);

$str = str_replace('en\/us', 'es\/es', $json);

echo $str;
</code>```

答:
You need to 'double escape' the backslash, like so:

```<code><?php

$str = array('url'=>'www.domain.com/data/en/us/data.gif');

$json = json_encode($str);

$str = str_replace('en\\/us', 'es\\/es', $json);

echo $str;
</code>```

See http://php.net/manual/en/language.types.string.php (section 'Single quoted').

Would be easier to escape the string BEFORE feeding it to json_encode, but I'm assuming this is a test case and the data you want to replace in is already JSON.

Body:
I wanted to replace en/us with es/es:

<?php

$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');

$json = json_encode($str);

$str = str_replace('en\/us', 'es\/es', $json);

echo $str;

Body:
You need to 'double escape' the backslash, like so:

<?php

$str = array('url'=>'www.domain.com/data/en/us/data.gif');

$json = json_encode($str);

$str = str_replace('en\\/us', 'es\\/es', $json);

echo $str;

See http://php.net/manual/en/language.types.string.php (section 'Single quoted').

Would be easier to escape the string BEFORE feeding it to json_encode, but I'm assuming this is a test case and the data you want to replace in is already JSON.


问:
Present View Controller not working with ios 9
Present view controller is not working with ios 9,
when I press the button it not redirected to present view controller.

Why this happens ?

I had tried the below code

```<code> RegistrationViewController * viewController =[[UIStoryboard storyboardWithName:@"Registration" bundle:nil] instantiateViewControllerWithIdentifier:@"RegistrationViewController"];
 [self presentViewController:viewController animated:YES completion:nil];
</code>```

I had also tried the below code

```<code> UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Registration"
                                                         bundle:nil];
 RegistrationViewController *add =
 [storyboard instantiateViewControllerWithIdentifier:@"RegistrationViewController"];
 [self presentViewController:add animated:YES completion:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:add
                               animated:YES
                             completion:nil];
        });
  }];
</code>```

Edit

My complete code here. I am using Xcode 7 and running it with ios 9

```<code>#import "LoginViewController.h"
#import "RegistrationViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)actionRegistrationClicked:(id)sender
{
    RegistrationViewController * viewController =[[UIStoryboard storyboardWithName:@"Registration" bundle:nil] instantiateViewControllerWithIdentifier:@"RegistrationViewController"];
     [self presentViewController:viewController animated:YES completion:nil];

}
@end
</code>```

Registration view controller

```<code>#import "RegistrationViewController.h"

@interface RegistrationViewController ()

@end

@implementation RegistrationViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

答:
try viewDidAppear in  </p>

```<code>  -(void)viewDidAppear:(BOOL)animated{
         [self presentViewController:viewController animated:YES completion:nil];
    }
</code>```

Body:
Present view controller is not working with ios 9,
when I press the button it not redirected to present view controller.

Why this happens ?

I had tried the below code

 RegistrationViewController * viewController =[[UIStoryboard storyboardWithName:@"Registration" bundle:nil] instantiateViewControllerWithIdentifier:@"RegistrationViewController"];
 [self presentViewController:viewController animated:YES completion:nil];

I had also tried the below code

 UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Registration"
                                                         bundle:nil];
 RegistrationViewController *add =
 [storyboard instantiateViewControllerWithIdentifier:@"RegistrationViewController"];
 [self presentViewController:add animated:YES completion:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:add
                               animated:YES
                             completion:nil];
        });
  }];

Edit

My complete code here. I am using Xcode 7 and running it with ios 9

#import "LoginViewController.h"
#import "RegistrationViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)actionRegistrationClicked:(id)sender
{
    RegistrationViewController * viewController =[[UIStoryboard storyboardWithName:@"Registration" bundle:nil] instantiateViewControllerWithIdentifier:@"RegistrationViewController"];
     [self presentViewController:viewController animated:YES completion:nil];

}
@end

Registration view controller

#import "RegistrationViewController.h"

@interface RegistrationViewController ()

@end

@implementation RegistrationViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Body:
try viewDidAppear in

  -(void)viewDidAppear:(BOOL)animated{
         [self presentViewController:viewController animated:YES completion:nil];
    }


问:
filtering xpath with same functionality on different pages
Because I have the same functionality on several different pages and dont want to repeat myself. I want to make a xpath that retrieves the element with a wildcard. On each page I have a input ID, they look like this:

```<code>tbAAFound_fileUpload
tbBBFound_fileUpload
tbCCFound_fileUpload
tbDDFound_fileUpload
tbEEFound_fileUpload
</code>```

I want to make the xpath filter so that it searches if it can find the element on more than one page.

When I try the following xpath:

```<code>[FindsBy(How = How.XPath, Using = "//input[starts-with(@id, 'tb:') and contains(@id, '_fileUpload')]")]
private IWebElement UrlFileElement { get; set; }
</code>```

Selenium cannot find the element. Hope that you guys can help me out.

答:
Try this ..</p>

```<code>[FindsBy(How = How.XPath, Using = "//*[contains(@id,’_fileUpload’)]")]
private IWebElement UrlFileElement { get; set; }
</code>```

Body:
Because I have the same functionality on several different pages and dont want to repeat myself. I want to make a xpath that retrieves the element with a wildcard. On each page I have a input ID, they look like this:

tbAAFound_fileUpload
tbBBFound_fileUpload
tbCCFound_fileUpload
tbDDFound_fileUpload
tbEEFound_fileUpload

I want to make the xpath filter so that it searches if it can find the element on more than one page.

When I try the following xpath:

[FindsBy(How = How.XPath, Using = "//input[starts-with(@id, 'tb:') and contains(@id, '_fileUpload')]")]
private IWebElement UrlFileElement { get; set; }

Selenium cannot find the element. Hope that you guys can help me out.

Body:
Try this ..

[FindsBy(How = How.XPath, Using = "//*[contains(@id,’_fileUpload’)]")]
private IWebElement UrlFileElement { get; set; }


答:
JSON is a useful format for moving data between systems. Converting data to JSON and then trying to manipulate it without parsing it first is almost always a terrible (overly complicated and error prone) idea.

Do the replacement before you convert it to JSON.

```<code><?php

function replace_country($value) {
    echo $value;
    echo "\n";
    return str_replace('en\/us', 'es\/es', $value);
}

$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$str = array_map("replace_country", $str);
$json = json_encode($str);
echo $json;
</code>```

Title: php: wanted to replace '\\\/' from string

Body:
JSON is a useful format for moving data between systems. Converting data to JSON and then trying to manipulate it without parsing it first is almost always a terrible (overly complicated and error prone) idea.

Do the replacement before you convert it to JSON.

<?php

function replace_country($value) {
    echo $value;
    echo "\n";
    return str_replace('en\/us', 'es\/es', $value);
}

$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$str = array_map("replace_country", $str);
$json = json_encode($str);
echo $json;


问:
How to give action for two radio buttons to make active one at a time?
Here I had placed two radio buttons on view controller class but unable to give logic to make a radio button active at a time can anyone help me ? </p>

```<code>@IBAction func radioButtonAction(_ sender: KGRadioButton) {
    sender.isSelected = !sender.isSelected

    if sender.isSelected {
        workRadioButton.isSelected = false
    } else{

    }

}
@IBAction func WorkRadiobuttonAction(_ sender: KGRadioButton) {

    sender.isSelected = !sender.isSelected

    if sender.isSelected {
        homeRadioButton.isSelected = false
    } else{

    }
}
</code>```

答:
I am just using UIButton as radioButton.try like below

Create one array to store radio buttons

```<code>var radioButtonArray = [UIButton]()
</code>```

Declare your radio buttons as UIButton or anyOther

```<code>@IBOutlet weak var radioButton1: UIButton!
@IBOutlet weak var radioButton2: UIButton!
</code>```

Append all buttons into array

```<code> radioButtonArray.append(contentsOf: [radio1,radio2])
</code>```

Set same target for all buttons

```<code>self.radioButton1.addTarget(self, action: #selector(self.folderRadioButtonClicked(_:)), for: UIControlEvents.touchUpInside)
self.radioButton2.addTarget(self, action: #selector(self.folderRadioButtonClicked(_:)), for: UIControlEvents.touchUpInside)

func folderRadioButtonClicked(_ sender:UIButton) {
    for i in 0..<self.radioButtonArray.count {
        if self.radioButtonArray[i] == sender{
            // here you can perform what you want
            self.radioButtonArray[i].setImage(UIImage(named: "checked.png"), for: UIControlState())
        }else {
            self.radioButtonArray[i].setImage(UIImage(named: "unchecked.png"), for: UIControlState())
        }
    }
}
</code>```

Body:
Here I had placed two radio buttons on view controller class but unable to give logic to make a radio button active at a time can anyone help me ?

@IBAction func radioButtonAction(_ sender: KGRadioButton) {
    sender.isSelected = !sender.isSelected

    if sender.isSelected {
        workRadioButton.isSelected = false
    } else{

    }

}
@IBAction func WorkRadiobuttonAction(_ sender: KGRadioButton) {

    sender.isSelected = !sender.isSelected

    if sender.isSelected {
        homeRadioButton.isSelected = false
    } else{

    }
}

Body:
I am just using UIButton as radioButton.try like below

Create one array to store radio buttons

var radioButtonArray = [UIButton]()

Declare your radio buttons as UIButton or anyOther

@IBOutlet weak var radioButton1: UIButton!
@IBOutlet weak var radioButton2: UIButton!

Append all buttons into array

 radioButtonArray.append(contentsOf: [radio1,radio2])

Set same target for all buttons

self.radioButton1.addTarget(self, action: #selector(self.folderRadioButtonClicked(_:)), for: UIControlEvents.touchUpInside)
self.radioButton2.addTarget(self, action: #selector(self.folderRadioButtonClicked(_:)), for: UIControlEvents.touchUpInside)

func folderRadioButtonClicked(_ sender:UIButton) {
    for i in 0..<self.radioButtonArray.count {
        if self.radioButtonArray[i] == sender{
            // here you can perform what you want
            self.radioButtonArray[i].setImage(UIImage(named: "checked.png"), for: UIControlState())
        }else {
            self.radioButtonArray[i].setImage(UIImage(named: "unchecked.png"), for: UIControlState())
        }
    }
}


问:
rendering multiple elements after onClick event in React
I'm having problems trying to render two react elements inside a react component after a onClick event. Wondering if that's even possible? I'm sure I'm messing up the ternary operator, but I cannot think on another way to do what I'm trying to do ?

TL;DR: "When I click a button I see elementA and elementB"

Here is a snippet of the code:

```<code>import React, { Component } from 'react';

class MyComponent extends Component {
    constructor(props) {
    super(props)
    this.state = { showElement: true };
    this.onHandleClick = this.onHandleClick.bind(this);
  }

  onHandleClick() {
    console.log(`current state: ${this.state.showElement} and prevState: ${this.prevState}`);
    this.setState(prevState => ({ showElement: !this.state.showElement }) );
  };

  elementA() {
    <div>
      <h1>
      some data
      </h1>
    </div>
  }

  elementB() {
    <div>
      <h1>
      some data
      </h1>
    </div>
  }

  render() {
    return (
      <section>
          <button onClick={ this.onHandleClick } showElement={this.state.showElement === true}>
          </button>
          { this.state.showElement
            ?
            null
            :
            this.elementA() && this.elementB()
          }
      </section>
    )
  }
}

export default MyComponent;
</code>```

答:
Try this instead, (I will add comments into the code trying to explain what's going on):</p>

```<code>function SomeComponentName() { // use props if you want to pass some data to this component. Meaning that if you can keep it stateless do so.
  return (
    <div>
      <h1>
      some data
      </h1>
    </div>
  );
}

class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.state = { showElement: false }; // you say that initially you don't want to show it, right? So let's set it to false :)
    this.onHandleClick = this.onHandleClick.bind(this);
  }

  onHandleClick() {
    this.setState(prevState => ({ showElement: !prevState.showElement }) );
    // As I pointed out in the comment: when using the "reducer" version of `setState` you should use the parameter that's provided to you with the previous state, try never using the word `this` inside a "reducer" `setState` function
  };

  render() {
    return (
      <section>
          <button onClick={ this.onHandleClick } showElement={this.state.showElement === false}>
          </button>
          { this.state.showElement
            ? [<SomeComponentName key="firstOne" />, <SomeComponentName key="secondOne" />]
            : null
          }
      </section>
    )
  }
}

export default MyComponent;
</code>```

Body:
I'm having problems trying to render two react elements inside a react component after a onClick event. Wondering if that's even possible? I'm sure I'm messing up the ternary operator, but I cannot think on another way to do what I'm trying to do ?

TL;DR: "When I click a button I see elementA and elementB"

Here is a snippet of the code:

import React, { Component } from 'react';

class MyComponent extends Component {
    constructor(props) {
    super(props)
    this.state = { showElement: true };
    this.onHandleClick = this.onHandleClick.bind(this);
  }

  onHandleClick() {
    console.log(`current state: ${this.state.showElement} and prevState: ${this.prevState}`);
    this.setState(prevState => ({ showElement: !this.state.showElement }) );
  };

  elementA() {

      some data

  }

  elementB() {

      some data

  }

  render() {
    return (

          <button onClick={ this.onHandleClick } showElement={this.state.showElement === true}>
          </button>
          { this.state.showElement
            ?
            null
            :
            this.elementA() && this.elementB()
          }

    )
  }
}

export default MyComponent;

Body:
Try this instead, (I will add comments into the code trying to explain what's going on):

function SomeComponentName() { // use props if you want to pass some data to this component. Meaning that if you can keep it stateless do so.
  return (
    <div>
      <h1>
      some data
      </h1>
    </div>
  );
}

class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.state = { showElement: false }; // you say that initially you don't want to show it, right? So let's set it to false :)
    this.onHandleClick = this.onHandleClick.bind(this);
  }

  onHandleClick() {
    this.setState(prevState => ({ showElement: !prevState.showElement }) );
    // As I pointed out in the comment: when using the "reducer" version of `setState` you should use the parameter that's provided to you with the previous state, try never using the word `this` inside a "reducer" `setState` function
  };

  render() {
    return (
      <section>
          <button onClick={ this.onHandleClick } showElement={this.state.showElement === false}>
          </button>
          { this.state.showElement
            ? [<SomeComponentName key="firstOne" />, <SomeComponentName key="secondOne" />]
            : null
          }
      </section>
    )
  }
}

export default MyComponent;


问:
how to add an attribute programmatically to product in magento1.9?
I'm beginner in Magento, and I used Magento1.9 CE,
I want to add an attribute, programmatically, in catalog/product.
I mean, that I want to see it in orange box that I highlighted on

This Image

I change version in magento/app/code/core/Mage/Catalog/etc/config.xml file

```<code>`<modules>
    <Mage_Catalog>
        <version>1.6.0.0.19.1.15</version>
    </Mage_Catalog>
 </modules>`
</code>```

and I add this file /magento/app/code/core/Mage/Catalog/sql/catalog_setup/mysql4-data-upgrade-1.6.0.0.19.1.15.php

```<code>$installer = $this;
$installer->startSetup();
$installer->addAttribute('catalog_product', 'promotion', array(
    'group'             => 'promotion',
    'type'              => 'text',
    'backend'           =>
    'catalog/product_attribute_backend_promotion',
    'frontend'          => '',
    'label'             => 'promotion',
    'input'             => 'text',
    'class'             => '',
    'source'            => '',
    'global'            => Mage_Eav_Model_Entity_Setup::SCOPE_GLOBAL,
    'visible'           => true,
    'required'          => false,
    'user_defined'      => false,
    'default'           => '',
    'searchable'        => false,
    'filterable'        => false,
    'comparable'        => false,
    'visible_on_front'  => false,
    'unique'            => false,
    'apply_to'          => 'simple,virtual',
    'is_configurable'   => false
));
</code>```

when I refreshed add product page, In database core_resource table, catalog_setup version changed to 1.6.0.0.19.1.15 but nothing happend to eav_attribute

what should I do to add 'promotion' in eav_attribute table?

答:
You should not change anything from core modules.
First you need to create a local module in magento then only you can able to add product attribute programatically.That is the proper way to add attribute.

This links may help you for create product attributes

http://inchoo.net/magento/programatically-create-attribute-in-magento-useful-for-the-on-the-fly-import-system/

https://magento.stackexchange.com/questions/162595/programmatically-add-custom-product-attribute-to-attribute-set

If you are not aware about create new module in magento means refer this url

http://inchoo.net/magento/programming-magento/magento-hello-world-module-extension/

If you need further assistance means ask me.

Body:
I'm beginner in Magento, and I used Magento1.9 CE,
I want to add an attribute, programmatically, in catalog/product.
I mean, that I want to see it in orange box that I highlighted on

This Image

I change version in magento/app/code/core/Mage/Catalog/etc/config.xml file

`<modules>
    <Mage_Catalog>
        <version>1.6.0.0.19.1.15</version>
    </Mage_Catalog>
 </modules>`

and I add this file /magento/app/code/core/Mage/Catalog/sql/catalog_setup/mysql4-data-upgrade-1.6.0.0.19.1.15.php

$installer = $this;
$installer->startSetup();
$installer->addAttribute('catalog_product', 'promotion', array(
    'group'             => 'promotion',
    'type'              => 'text',
    'backend'           =>
    'catalog/product_attribute_backend_promotion',
    'frontend'          => '',
    'label'             => 'promotion',
    'input'             => 'text',
    'class'             => '',
    'source'            => '',
    'global'            => Mage_Eav_Model_Entity_Setup::SCOPE_GLOBAL,
    'visible'           => true,
    'required'          => false,
    'user_defined'      => false,
    'default'           => '',
    'searchable'        => false,
    'filterable'        => false,
    'comparable'        => false,
    'visible_on_front'  => false,
    'unique'            => false,
    'apply_to'          => 'simple,virtual',
    'is_configurable'   => false
));

when I refreshed add product page, In database core_resource table, catalog_setup version changed to 1.6.0.0.19.1.15 but nothing happend to eav_attribute

what should I do to add 'promotion' in eav_attribute table?


问:
My python file is too heavy because of cv2 (like 50mo)
I got a python program that at some point needs to take a shot with the webcam
So I used cv2 to take and store that shot but the file became too heavy even though im only using
cv2.VideoCapture() and imWrite()

How can I use only these two functions or is there any other way to take a shot from the webcam without having an extra 45mo?

答:
using the following import statements instead of import cv2

from cv2 import VideoCapture
from cv2 import imWrite
```

and then use the functions as VideoCapture() and imWrite()

Body:
using the following import statements instead of import cv2

from cv2 import VideoCapture
from cv2 import imWrite

and then use the functions as VideoCapture() and imWrite()


问:
How can I find the minimum cut on a graph using a maximum flow algorithm?
I need to find the minimum cut on a graph. I've been reading about flow networks, but all I can find are maximum flow algorithms such as Ford-Fulkerson, push-relabel, etc. Given the max flow-min cut theorem, is it possible to use one of those algorithms to find the minimum cut on a graph using a maximum flow algorithm? How?

The best information I have found so far is that if I find "saturated" edges i.e. edges where flow equals capacity, those edges correspond to the minimum cut. Is that true? It doesn't sound 100% right to me. It is true that all edges on the minimum cut will be saturated, but I believe there might also be saturated edges which are out of the minimum cut "path".

答: From the source vertex, do a depth-first search along edges in the residual network (i.e., non-saturated edges and back edges of edges that have flow), and mark all vertices that can be reached this way. The cut consists of all edges that go from a marked to an unmarked vertex. Clearly, those edges are saturated and thus were not traversed. As you noted, there might be other saturated edges that are not part of the minimum cut.</p>


问:
Importing data from Excel to Visual studio dataGridView. Get this error Object reference not set to an instance of an object
I am importing excel data to dataGridView from this Link. But I get error "Object reference not set to an instance of an object".</p>

```<code>        String name = "Sheet1";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        file +
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        System.Data.DataTable data = new System.Data.DataTable();
        sda.Fill(data);
        dgvIM.DataSource = data;
</code>```

答: Check the value of dgvIM when debugging. It's probably null;</p>

Body:
I am importing excel data to dataGridView from this Link. But I get error "Object reference not set to an instance of an object".

        String name = "Sheet1";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        file +
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        System.Data.DataTable data = new System.Data.DataTable();
        sda.Fill(data);
        dgvIM.DataSource = data;