问:
Buttons on form not working
So I'd like to start by saying this is my first time dealing with JS and I am working on a project for my class.

I have to create a form with three buttons, one that will store the form data, one that will display it and one that will clear the form.  I have been researching to all ends to try and figure out what I am doing wrong.  This is an online class so not much info is given other than here's the book and here's your assignment.

Here's what I have so far, any ideas as to why my store and display buttons are not working and also is there a way I can check to see if the store button is correctly storing the data in arrays and it's just the display button not working?!

I'm ripping my hair out, sorry for being terrible.

<DOCTYPE HTML!>

Internet Technologies Membership

<form name ="ratingForm">

Full Name:
<input type="text" id="FullName" name="FullName">
Date:
<input type="date" id="Date" name="Date">
Opinion:
<select name="opinion" id="opinion">
 <option value="excellent">Excellent</option>
 <option value="verygood">Very Good</option>
 <option value="good">Good</option>
 <option value="fair">Fair</option>
 <option value="poor">Poor</option>
 <option value="verybad">Very Bad</option>
</select>

<textarea name="list" id="list" rows="10" cols="100">
</textarea>

<input type="button" value="RATE" onClick="validateData();">
<input type="button" value="DISPLAY" onClick="displayData();">
<input type="reset" value="CLEAR" onClick="clearData();">

</form>

```

答:
I think you can modify displayData() to this:

```<code>function displayData() {
            var col;
            var pos;
            var listElement = document.getElementById("list");

            listElement.value = "FULL NAME               DATE            RATING\n";
            for (pos = 0; pos < numOfRatings; pos++) {
                listElement.value += fullNames[pos] + " ".repeat(24 - fullNames[pos].length);
                listElement.value += dates[pos] + " ".repeat(16 - dates[pos].length);
                listElement.value += opinions[pos] + "\n";
            }
        }
</code>```

The repeat() function is added in ES2015.

Find element one time.

Title: Buttons on form not working

Body:
I think you can modify displayData() to this:

function displayData() {
            var col;
            var pos;
            var listElement = document.getElementById("list");

            listElement.value = "FULL NAME               DATE            RATING\n";
            for (pos = 0; pos < numOfRatings; pos++) {
                listElement.value += fullNames[pos] + " ".repeat(24 - fullNames[pos].length);
                listElement.value += dates[pos] + " ".repeat(16 - dates[pos].length);
                listElement.value += opinions[pos] + "\n";
            }
        }

The repeat() function is added in ES2015.

Find element one time.


来源: stackexchange

问:
How should I write three dots?
Simple question: I want to set a TextView and in that I want to have three dots (Ellipsis). Like

Read more... <-- Now I'm sure I shouldn't just write ... into the String. How should I write these three dots?

答:
Now I'm sure I shouldn't just write ... into the String.

Why? Are you having some sort of issue with how text is handled by the application or operating system? What benefit is served by using a special Unicode symbol instead of a character built into every keyboard out there? You save a byte of data?

I can't imagine how I could be the first one to put this into an answer, but just use three dots.

ContentLicense: CC BY-SA 3.0

Title: How should I write three dots?


问:
I get undefined values in my field value when inserting multiple documents after converting csv to json string and parsing. Why?
Basically, I am trying to do an import function for csv files where the csv file will get converted to json before then being inserted into the mongodb. This is my code.

```<code>//require the csvtojson converter class
var Converter = require("csvtojson").Converter;
// create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

// call the fromFile function which takes in the path to your
// csv file as well as a callback function
converter.fromFile("./NTA-SAM-Inventory-List-Security-Management-
New_2017.csv",function(err,result){
// if an error has occured then handle it
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
var jsonResult  = result;
console.log(jsonResult);
var jsobject= JSON.stringify(jsonResult);
var jsonobject= JSON.parse(jsobject);
var f = jsonobject.length;
console.log(f);
MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log(err);
        }
        for(i = 0; i < f; i++){
    var insertDocument = function() {
    db.collection('documents').insertOne({
//'_id': Object.keys(obj).length,
        'indexNo' : jsonobject.indexNo,
        'samID': jsonobject.samID,
        'Type': jsonobject.Type,
        'InventoryStatus': jsonobject.InventoryStatus,
        'dateIn':jsonobject.dateIn,
        'Remarks':jsonobject.Remarks,
        'dateOut':jsonobject.dateOut,
        //'Remarks':jsonobject.remarks,
        'ntaSamRequestRef': jsonobject.ntaSamReqRef
        //'Created Date': "<b>" + day + "/" + month + "/" + year + "</b>"
    }, function(err, results) {
        if(err) throw err;
        console.log(results);

    });
    };
        insertDocument(db, function() {
            if(err)
                throw err;
            else{
                console.log('insert');
            }
            db.close();
        });
        }
 });
        console.log("Inserted " + f + " document into the documents
        collection.");
 });
</code>```

So far, I have tried doing this of converting a random file with 1400 records into a json string before parsing and then inserting it. But somehow I keep getting undefined from my fields whenever I insert, the result show my respective field with undefined values.

Which part of my jsonobject.indexNo is wrong in the sense that is jsonobject.field1value and jsonobject.field2value etc. How should I get the values from my json string then after parsing?

I am using node.js to run it and mongodb as database. I can convert nicely just this part about inserting the documents inside. Thanks in advance!

答:
db.collection('documents').insertOne is an async method , you can't run it in a loop like that. Workaround is you can use async to handle it. Suggest to use async.each

Eg:

```<code> // Consider jsonResult is an array
 var jsonResult  = result;

 async.each(jsonResult,
   // Here, jsonobject is a child object of jsonResult array
   function(jsonobject, callback){
     db.collection('documents').insertOne({
      //'_id': Object.keys(obj).length,
      'indexNo' : jsonobject.indexNo,
      'samID': jsonobject.samID,
      'Type': jsonobject.Type,
      'InventoryStatus': jsonobject.InventoryStatus,
      'dateIn':jsonobject.dateIn,
      'Remarks':jsonobject.Remarks,
      'dateOut':jsonobject.dateOut,
      //'Remarks':jsonobject.remarks,
      'ntaSamRequestRef': jsonobject.ntaSamReqRef
      //'Created Date': "<b>" + day + "/" + month + "/" + year + "</b>"
     });

     // Async call is done, trigger callback
     callback();
 },
 // 3rd param is the function to call when everything's done
 function(err){
   // All tasks are done now
   doSomethingOnceAllAreDone();
 }
);
</code>```

Body:
Basically, I am trying to do an import function for csv files where the csv file will get converted to json before then being inserted into the mongodb. This is my code.

//require the csvtojson converter class
var Converter = require("csvtojson").Converter;
// create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

// call the fromFile function which takes in the path to your
// csv file as well as a callback function
converter.fromFile("./NTA-SAM-Inventory-List-Security-Management-
New_2017.csv",function(err,result){
// if an error has occured then handle it
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
var jsonResult  = result;
console.log(jsonResult);
var jsobject= JSON.stringify(jsonResult);
var jsonobject= JSON.parse(jsobject);
var f = jsonobject.length;
console.log(f);
MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log(err);
        }
        for(i = 0; i < f; i++){
    var insertDocument = function() {
    db.collection('documents').insertOne({
//'_id': Object.keys(obj).length,
        'indexNo' : jsonobject.indexNo,
        'samID': jsonobject.samID,
        'Type': jsonobject.Type,
        'InventoryStatus': jsonobject.InventoryStatus,
        'dateIn':jsonobject.dateIn,
        'Remarks':jsonobject.Remarks,
        'dateOut':jsonobject.dateOut,
        //'Remarks':jsonobject.remarks,
        'ntaSamRequestRef': jsonobject.ntaSamReqRef
        //'Created Date': "" + day + "/" + month + "/" + year + ""
    }, function(err, results) {
        if(err) throw err;
        console.log(results);

    });
    };
        insertDocument(db, function() {
            if(err)
                throw err;
            else{
                console.log('insert');
            }
            db.close();
        });
        }
 });
        console.log("Inserted " + f + " document into the documents
        collection.");
 });

So far, I have tried doing this of converting a random file with 1400 records into a json string before parsing and then inserting it. But somehow I keep getting undefined from my fields whenever I insert, the result show my respective field with undefined values.

Which part of my jsonobject.indexNo is wrong in the sense that is jsonobject.field1value and jsonobject.field2value etc. How should I get the values from my json string then after parsing?

I am using node.js to run it and mongodb as database. I can convert nicely just this part about inserting the documents inside. Thanks in advance!

Body:
db.collection('documents').insertOne is an async method , you can't run it in a loop like that. Workaround is you can use async to handle it. Suggest to use async.each

Eg:

 // Consider jsonResult is an array
 var jsonResult  = result;

 async.each(jsonResult,
   // Here, jsonobject is a child object of jsonResult array
   function(jsonobject, callback){
     db.collection('documents').insertOne({
      //'_id': Object.keys(obj).length,
      'indexNo' : jsonobject.indexNo,
      'samID': jsonobject.samID,
      'Type': jsonobject.Type,
      'InventoryStatus': jsonobject.InventoryStatus,
      'dateIn':jsonobject.dateIn,
      'Remarks':jsonobject.Remarks,
      'dateOut':jsonobject.dateOut,
      //'Remarks':jsonobject.remarks,
      'ntaSamRequestRef': jsonobject.ntaSamReqRef
      //'Created Date': "<b>" + day + "/" + month + "/" + year + "</b>"
     });

     // Async call is done, trigger callback
     callback();
 },
 // 3rd param is the function to call when everything's done
 function(err){
   // All tasks are done now
   doSomethingOnceAllAreDone();
 }
);


问:
How to use user defined database proxy in @DataJpaTest
We need to track database metrics so we are using datasource-proxy to track this to integrate the same in spring boot project we have created custom datasource
as below

```<code>@Component
@Slf4j
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceBeanConfig
{

    public DataSource actualDataSource()
    {
        EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
        return databaseBuilder.setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    @Primary
    public DataSource dataSource() {
        // use pretty formatted query with multiline enabled
        PrettyQueryEntryCreator creator = new PrettyQueryEntryCreator();
        creator.setMultiline(true);

        log.info("Inside Proxy Creation");

        SystemOutQueryLoggingListener listener = new SystemOutQueryLoggingListener();
        listener.setQueryLogEntryCreator(creator);

        return ProxyDataSourceBuilder
                .create(actualDataSource())
                .countQuery()
                .name("MyDS")
                .listener(listener)
                .build();
    }
}
</code>```

When we run main application datasource-proxy is picked up but when we use @DataJpaTest it is not picking up. How to enable datasource-proxy in JUNIT test cases?

Edit::

Using Spring BeanPostProcessor to configure Proxy DataSource

```<code>@Slf4j
@Configuration
public class DataSourceBeanConfig implements BeanPostProcessor
{
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException
    {

        if (bean instanceof DataSource)
        {
            System.out.println("AfterInitialization : " + beanName);

            // use pretty formatted query with multiline enabled
            PrettyQueryEntryCreator creator = new PrettyQueryEntryCreator();
            creator.setMultiline(true);

            log.info("Inside Proxy Creation");

            SystemOutQueryLoggingListener listener = new SystemOutQueryLoggingListener();
            listener.setQueryLogEntryCreator(creator);

            return ProxyDataSourceBuilder.create((DataSource) bean).countQuery()
                    .name("MyDS").listener(listener).build();

        }
        return bean; // you can return any other object as well
    }
}
</code>```

答:
Here is the solution we need to create TestConfiguration to use in @DataJpaTest</p>

```<code>@RunWith(SpringRunner.class)
@DataJpaTest
public class DataTestJPA
{

    @TestConfiguration
    static class ProxyDataSourceConfig implements BeanPostProcessor
    {
        public Object postProcessAfterInitialization(Object bean, String beanName)
                throws BeansException
        {

            if (bean instanceof DataSource)
            {
               return ProxyDataSourceBuilder
                            .create((DataSource) bean)
                            .countQuery()
                            .name("MyDS")
                            .build();
                // @formatter:on

            }
            return bean; // you can return any other object as well
        }
    }
}
</code>```

Body:
We need to track database metrics so we are using datasource-proxy to track this to integrate the same in spring boot project we have created custom datasource
as below

@Component
@Slf4j
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceBeanConfig
{

    public DataSource actualDataSource()
    {
        EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
        return databaseBuilder.setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    @Primary
    public DataSource dataSource() {
        // use pretty formatted query with multiline enabled
        PrettyQueryEntryCreator creator = new PrettyQueryEntryCreator();
        creator.setMultiline(true);

        log.info("Inside Proxy Creation");

        SystemOutQueryLoggingListener listener = new SystemOutQueryLoggingListener();
        listener.setQueryLogEntryCreator(creator);

        return ProxyDataSourceBuilder
                .create(actualDataSource())
                .countQuery()
                .name("MyDS")
                .listener(listener)
                .build();
    }
}

When we run main application datasource-proxy is picked up but when we use @DataJpaTest it is not picking up. How to enable datasource-proxy in JUNIT test cases?

Edit::

Using Spring BeanPostProcessor to configure Proxy DataSource

@Slf4j
@Configuration
public class DataSourceBeanConfig implements BeanPostProcessor
{
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException
    {

        if (bean instanceof DataSource)
        {
            System.out.println("AfterInitialization : " + beanName);

            // use pretty formatted query with multiline enabled
            PrettyQueryEntryCreator creator = new PrettyQueryEntryCreator();
            creator.setMultiline(true);

            log.info("Inside Proxy Creation");

            SystemOutQueryLoggingListener listener = new SystemOutQueryLoggingListener();
            listener.setQueryLogEntryCreator(creator);

            return ProxyDataSourceBuilder.create((DataSource) bean).countQuery()
                    .name("MyDS").listener(listener).build();

        }
        return bean; // you can return any other object as well
    }
}

Body:
Here is the solution we need to create TestConfiguration to use in @DataJpaTest

@RunWith(SpringRunner.class)
@DataJpaTest
public class DataTestJPA
{

    @TestConfiguration
    static class ProxyDataSourceConfig implements BeanPostProcessor
    {
        public Object postProcessAfterInitialization(Object bean, String beanName)
                throws BeansException
        {

            if (bean instanceof DataSource)
            {
               return ProxyDataSourceBuilder
                            .create((DataSource) bean)
                            .countQuery()
                            .name("MyDS")
                            .build();
                // @formatter:on

            }
            return bean; // you can return any other object as well
        }
    }
}


问:
ClassNotFoundException oracle.i18n.util.LocaleMapper on tomcat TLD scanning. ojdbc7 maven dep (xmlparserv2-12.1.0.2.jar transitive) causes this error
I am receiving an error when running my spring-boot application with embedded-tomcat (haven't tried with server tomcat yet).

```<code>java.lang.IllegalStateException: Tomcat 7 reflection failed
    at org.springframework.boot.context.embedded.tomcat.SkipPatternJarScanner.scan(SkipPatternJarScanner.java:77)
    at org.apache.catalina.startup.TldConfig.execute(TldConfig.java:271)
    at org.apache.catalina.startup.TldConfig.lifecycleEvent(TldConfig.java:590)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5522)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException: null
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.context.embedded.tomcat.SkipPatternJarScanner.scan(SkipPatternJarScanner.java:73)
    ... 12 common frames omitted
Caused by: java.lang.NoClassDefFoundError: oracle/i18n/util/LocaleMapper
    at oracle.xml.parser.v2.XMLReader.setEncoding(XMLReader.java:980)
    at oracle.xml.parser.v2.XMLReader.checkXMLDecl(XMLReader.java:3284)
    at oracle.xml.parser.v2.XMLReader.pushXMLReader(XMLReader.java:570)
    at oracle.xml.parser.v2.XMLReader.pushXMLReader(XMLReader.java:274)
    at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:232)
    at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1576)
    at org.apache.catalina.startup.TldConfig.tldScanStream(TldConfig.java:565)
    at org.apache.catalina.startup.TldConfig.tldScanJar(TldConfig.java:513)
    at org.apache.catalina.startup.TldConfig.access$200(TldConfig.java:61)
    at org.apache.catalina.startup.TldConfig$TldJarScannerCallback.scan(TldConfig.java:300)
    at org.apache.tomcat.util.scan.StandardJarScanner.process(StandardJarScanner.java:259)
    at org.apache.tomcat.util.scan.StandardJarScanner.scan(StandardJarScanner.java:221)
    ... 17 common frames omitted
Caused by: java.lang.ClassNotFoundException: oracle.i18n.util.LocaleMapper
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 29 common frames omitted
</code>```

On further inspection, It appears as though the previous version of the orai18n.jar depended on by the ojdbc7 maven dep contained this class in vesion 11.2.0.3 but the newer (12.1.0.2) file does not contain it.

答:
After much hassle, I've found the root cause (Edit: Actually the better answer provided has a more appropriate cause/solution, see Serri's answer):

according to this bug comment in spring-boot The Oracle SaxParserFactory impl and the (later run into after solving the first) DocumentBuilderFactory implementations are picked up instead of the default xerces impls. Changing the implementation using the META-INF/services/<class-name> files solved the issue:

in my.jar:

and each file:

```<code>// javax.xml.parsers.DocumentBuilderFactory
com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl

// javax.xml.parsers.SAXParserFactory
com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
</code>```

This causes each service finder to resolve the default xerces implementation in the standard java library.

Body:
I am receiving an error when running my spring-boot application with embedded-tomcat (haven't tried with server tomcat yet).

java.lang.IllegalStateException: Tomcat 7 reflection failed
    at org.springframework.boot.context.embedded.tomcat.SkipPatternJarScanner.scan(SkipPatternJarScanner.java:77)
    at org.apache.catalina.startup.TldConfig.execute(TldConfig.java:271)
    at org.apache.catalina.startup.TldConfig.lifecycleEvent(TldConfig.java:590)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5522)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException: null
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.context.embedded.tomcat.SkipPatternJarScanner.scan(SkipPatternJarScanner.java:73)
    ... 12 common frames omitted
Caused by: java.lang.NoClassDefFoundError: oracle/i18n/util/LocaleMapper
    at oracle.xml.parser.v2.XMLReader.setEncoding(XMLReader.java:980)
    at oracle.xml.parser.v2.XMLReader.checkXMLDecl(XMLReader.java:3284)
    at oracle.xml.parser.v2.XMLReader.pushXMLReader(XMLReader.java:570)
    at oracle.xml.parser.v2.XMLReader.pushXMLReader(XMLReader.java:274)
    at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:232)
    at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1576)
    at org.apache.catalina.startup.TldConfig.tldScanStream(TldConfig.java:565)
    at org.apache.catalina.startup.TldConfig.tldScanJar(TldConfig.java:513)
    at org.apache.catalina.startup.TldConfig.access$200(TldConfig.java:61)
    at org.apache.catalina.startup.TldConfig$TldJarScannerCallback.scan(TldConfig.java:300)
    at org.apache.tomcat.util.scan.StandardJarScanner.process(StandardJarScanner.java:259)
    at org.apache.tomcat.util.scan.StandardJarScanner.scan(StandardJarScanner.java:221)
    ... 17 common frames omitted
Caused by: java.lang.ClassNotFoundException: oracle.i18n.util.LocaleMapper
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 29 common frames omitted

On further inspection, It appears as though the previous version of the orai18n.jar depended on by the ojdbc7 maven dep contained this class in vesion 11.2.0.3 but the newer (12.1.0.2) file does not contain it.

Body:
After much hassle, I've found the root cause (Edit: Actually the better answer provided has a more appropriate cause/solution, see Serri's answer):

according to this bug comment in spring-boot The Oracle SaxParserFactory impl and the (later run into after solving the first) DocumentBuilderFactory implementations are picked up instead of the default xerces impls. Changing the implementation using the META-INF/services/<class-name> files solved the issue:

in my.jar:

and each file:

// javax.xml.parsers.DocumentBuilderFactory
com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl

// javax.xml.parsers.SAXParserFactory
com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl

This causes each service finder to resolve the default xerces implementation in the standard java library.

ContentLicense: CC BY-SA 4.0


问:
Why won't form.submit() trigger the "submit" event?
I am submitting my form by using JavaScript .submit() function.

```<code>form.submit();
</code>```

But when I using addEventListener to capture my submit event, it wouldn't work.

```<code>form.addEventListener("submit", function(event){
    //codes
});
</code>```

I found out addEvenetListener function will only listen for onsubmit event instead of submit. Is there have any alternative solution to call my function when form.submit() is executed?

ps: For some reasons I need to stay with form.submit() to submit my form instead of using submit button.

答:
I think this solution would be more useful than the one you are trying. There could be some syntax error.

HTML:

```<code><button onclick="formSubmit()"> Submit form</button>
</code>```

JavaScript:

```<code>function formSubmit()
{
   var form = document.getElementById('formName');
   form[0].submit();
}
</code>```

Body:
I am submitting my form by using JavaScript .submit() function.

form.submit();

But when I using addEventListener to capture my submit event, it wouldn't work.

form.addEventListener("submit", function(event){
    //codes
});

I found out addEvenetListener function will only listen for onsubmit event instead of submit. Is there have any alternative solution to call my function when form.submit() is executed?

ps: For some reasons I need to stay with form.submit() to submit my form instead of using submit button.

Body:
I think this solution would be more useful than the one you are trying. There could be some syntax error.

HTML:

<button onclick="formSubmit()"> Submit form</button>

JavaScript:

function formSubmit()
{
   var form = document.getElementById('formName');
   form[0].submit();
}


问:
How to hide text links when viewed in mobile with bootstrap 4
I'd like to hide the text part of the link when viewed in mobile (xs and sm) sizes. How can I accomplish this? Does bootstrap 4 offer anything?

HTML

```<code><li>
  <a href="#"><i class="fa fa-icon"></i> Text Link</a>
</li>
</code>```

In mobile, I should only see the (icon). In desktop or tablet mode, I'll see (icon) Text Link

答:
Use this class hidden-sm-down to hide on small devices

```<code><li>
  <a href="#"><i class="fa fa-icon"></i> <span class="hidden-sm-down">Text Link</span></a>
</li>
</code>```

You can find more about regarding this from here. https://v4-alpha.getbootstrap.com/layout/responsive-utilities/#available-classes

Body:
I'd like to hide the text part of the link when viewed in mobile (xs and sm) sizes. How can I accomplish this? Does bootstrap 4 offer anything?

HTML

   Text Link

In mobile, I should only see the (icon). In desktop or tablet mode, I'll see (icon) Text Link

Body:
Use this class hidden-sm-down to hide on small devices

<li>
  <a href="#"><i class="fa fa-icon"></i> <span class="hidden-sm-down">Text Link</span></a>
</li>

You can find more about regarding this from here. https://v4-alpha.getbootstrap.com/layout/responsive-utilities/#available-classes


问:
Can't get login script to work after adding salt to hash; worked fine before
I've reset my database and on registration, we added random salt to hashes, and the registration script worked fine, we could create accounts and accounts with the same password and they had different hashes, but our login script is broken, not logging in users, saying their password is incorrect.

No idea why- we have spent the last 2 hours trying to fix it. We have used PHP error checkers(https://phpcodechecker.com/), nothing was wrong.

We are running an old version PHP(5.6) and MySQL and can't currently change.

```<code>    <?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';

    // it will never let you open index(login) page if session is set
    if ( isset($_SESSION['user'])!="" ) {
     header("Location: index.php");
     exit;
    }

    $error = false;

    if( isset($_POST['btn-login']) ) {

     // prevent sql injections/ clear user invalid inputs
     $email = trim($_POST['email']);
     $email = strip_tags($email);
     $email = htmlspecialchars($email);

     $name = trim($_POST['name']);
     $name = strip_tags($name);
     $name = htmlspecialchars($name);

     $pass = trim($_POST['pass']);
     $pass = strip_tags($pass);
     $pass = htmlspecialchars($pass);
     // prevent sql injections / clear user invalid inputs

     if(empty($name)){
      $error = true;
      $nameError = "Please enter your username.";
     }

     if(empty($pass)){
      $error = true;
      $passError = "Please enter your password.";
     }
       $res=mysql_query("SELECT userId, userEmail, userPass, userSalt, userSalt2 FROM users WHERE userName='$name'");
      $row=mysql_fetch_array($res);

      $row['userSalt']=$salt1;
      $row['userSalt2']=$salt2;
     // if there's no error, continue to login
     if (!$error) {

        $passwordHash = hash('sha256', $salt1 . $password . $salt2); // password hashing using SHA256

      //$res=mysql_query("SELECT userId, userEmail, userPass, userSalt,        userSalt2 FROM users WHERE userName='$name'");
      //$row=mysql_fetch_array($res);
      $count = mysql_num_rows($res); // if email/pass correct it returns must be 1        row

      if( $count == 1 && $row['userPass']==$passwordHash ) {
       $_SESSION['user'] = $row['userId'];
header("Location: dashboard.php");
      } else {
       $errMSG = "Incorrect Credentials, Try again...";
      }

     }

    }
   ?>
   <!DOCTYPE html>
   <html>
   <head>
   <script src="//code.jquery.com/jquery-1.10.2.js"></script>
   <script>
   $(function(){
        $("#overallhead").load("overall_header.php");
        $("#overallfoot").load("overall_footer.html");
    });
   </script>
   <style>
   body {
    color: Thistle;
    }
    </style>
   <div id="overallhead"></div>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Creature Paradise</title>
   <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"  />
   <link rel="stylesheet" href="style.css" type="text/css" />
   </head>
   <body>

   <div class="container">

    <div id="login-form">
       <form method="post" action="<?php echo        htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

 <div class="col-md-12">

     <div class="form-group">
         <h2 class="">Login</h2>
        </div>

     <div class="form-group">
         <hr />
         </div>

        <?php
      if ( isset($errMSG) ) {

       ?>
       <div class="form-group">
         <div class="alert alert-danger">
       <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
            </div>
         </div>
            <?php
      }
      ?>

        <div class="form-group">
         <div class="input-group">
            <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
         <input type="name" name="name" class="form-control" placeholder="Your Username" value="<?php echo $name; ?>" maxlength="40" />
            </div>
            <span class="text-danger"><?php echo $nameError; ?></span>
        </div>

        <div class="form-group">
         <div class="input-group">
            <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
         <input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" />
            </div>
            <span class="text-danger"><?php echo $passError; ?></span>
        </div>

        <div class="form-group">
         <hr />
        </div>

        <div class="form-group">
         <button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>
        </div>

        <div class="form-group">
         <hr />
        </div>

        <div class="form-group">
                <a href="register.php">Don't have an account? Sign up here!              </a>
               </div>

           </div>

       </form>
       </div>

   </div>
   <div id="overallfoot"></div>
   </body>
   </html>
   <?php ob_end_flush(); ?>
</code>```

答: Have you do hashing on registration page, too? Because $row['userPass'] will never equal $passwordHash if you have not registration a new account with new hash applied

Body:
I've reset my database and on registration, we added random salt to hashes, and the registration script worked fine, we could create accounts and accounts with the same password and they had different hashes, but our login script is broken, not logging in users, saying their password is incorrect.

No idea why- we have spent the last 2 hours trying to fix it. We have used PHP error checkers(https://phpcodechecker.com/), nothing was wrong.

We are running an old version PHP(5.6) and MySQL and can't currently change.

    <?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';

    // it will never let you open index(login) page if session is set
    if ( isset($_SESSION['user'])!="" ) {
     header("Location: index.php");
     exit;
    }

    $error = false;

    if( isset($_POST['btn-login']) ) {

     // prevent sql injections/ clear user invalid inputs
     $email = trim($_POST['email']);
     $email = strip_tags($email);
     $email = htmlspecialchars($email);

     $name = trim($_POST['name']);
     $name = strip_tags($name);
     $name = htmlspecialchars($name);

     $pass = trim($_POST['pass']);
     $pass = strip_tags($pass);
     $pass = htmlspecialchars($pass);
     // prevent sql injections / clear user invalid inputs

     if(empty($name)){
      $error = true;
      $nameError = "Please enter your username.";
     }

     if(empty($pass)){
      $error = true;
      $passError = "Please enter your password.";
     }
       $res=mysql_query("SELECT userId, userEmail, userPass, userSalt, userSalt2 FROM users WHERE userName='$name'");
      $row=mysql_fetch_array($res);

      $row['userSalt']=$salt1;
      $row['userSalt2']=$salt2;
     // if there's no error, continue to login
     if (!$error) {

        $passwordHash = hash('sha256', $salt1 . $password . $salt2); // password hashing using SHA256

      //$res=mysql_query("SELECT userId, userEmail, userPass, userSalt,        userSalt2 FROM users WHERE userName='$name'");
      //$row=mysql_fetch_array($res);
      $count = mysql_num_rows($res); // if email/pass correct it returns must be 1        row

      if( $count == 1 && $row['userPass']==$passwordHash ) {
       $_SESSION['user'] = $row['userId'];
header("Location: dashboard.php");
      } else {
       $errMSG = "Incorrect Credentials, Try again...";
      }

     }

    }
   ?>
   <!DOCTYPE html>

   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Creature Paradise</title>
   <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"  />
   <link rel="stylesheet" href="style.css" type="text/css" />

       <form method="post" action="<?php echo        htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

Login

        <?php
      if ( isset($errMSG) ) {

       ?>

        <?php echo $errMSG; ?>

            <?php
      }
      ?>

         <input type="name" name="name" class="form-control" placeholder="Your Username" value="<?php echo $name; ?>" maxlength="40" />

            <?php echo $nameError; ?>

         <input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" />

            <?php echo $passError; ?>

         <button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>

                Don't have an account? Sign up here!

       </form>

   <?php ob_end_flush(); ?>


问:
Get the only latest data from last week and sum some column
Get only latest data from last week and sum some column

I made an example with dat, the actual result and the expected.

http://rextester.com/HMB12638

```<code> --Taking first as example..

--      user    contact         barcode date                in  out dif
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 80
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 90
-- 3    USER2   Guillermo Tole  987654  13.06.2017 05:27:00 400 380 20
-- 4    USER2   Guillermo Tole  281460  12.06.2017 05:26:00 230 190 40
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 6    USER3   Juan Rulfo      123456  12.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240
-- 8    USER3   Pepito Marquez  346234  14.06.2017 05:37:00 450 300 150

 -- This would be the expectation
-- (MOST RECENT in . out) SUM of all the barcodes showed
--      user    contact         barcode date                in  out sum
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 170 (80 + 90)
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 170 (80 + 90)
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240
</code>```

答:
I think this matches your expected result:

```<code>select "user", "contact", "barcode", "date", "in", "out","dif"
     , sum("in"-"out") over(partition by "user", "contact") as "sum"
from (
    select "user", "contact", "barcode", "date", "in", "out","dif"
    , lag(dif,1) over(partition by "user", "contact" order by "date" ASC) prevdif
    , row_number() over(partition by "user", "contact" order by "date" DESC) rn
    from "table1"
    where date_trunc('day', "date") <= '2017-06-25' ::date - (  interval '1 week')::interval
    and "date" >  '2017-06-25'::date - (  interval '2 weeks')::interval
    ) d
where rn in (1,2) and prevdif is not null
order by 1,2,4 DESC
</code>```

Result:

```<code>+----+-------+----------------+---------+---------------------+-----+-----+-----+-----+
|    | user  |    contact     | barcode |        date         | in  | out | dif | sum |
+----+-------+----------------+---------+---------------------+-----+-----+-----+-----+
|  1 | USER2 | Guillermo Tole |  987654 | 16.06.2017 05:27:00 | 500 | 420 |  80 | 170 |
|  2 | USER2 | Guillermo Tole |  281460 | 15.06.2017 05:36:00 | 310 | 220 |  90 | 170 |
|  3 | USER3 | Juan Rulfo     |  123456 | 15.06.2017 05:37:00 | 450 | 300 | 150 | 150 |
|  4 | USER3 | Pepito Marquez |  346234 | 15.06.2017 05:37:00 | 600 | 360 | 240 | 240 |
+----+-------+----------------+---------+---------------------+-----+-----+-----+-----+
</code>```

See: http://rextester.com/ISHS42170

For conditions such as "most recent" I find that using ROW_NUMBER() OVER() is the most convenient as it allows the whole row of each "most recent" event be returned which isn't quite so simple if using MAX() and GROUP BY. "Distinct" results are returned by filtering the rows having value 1 returned by the function.

+EDIT

Instead of using where rn in (1,2) I believe a better way would have been better to use barcode in the OVER(PARTITION BY...) conditions, like this:

```<code>select "user", "contact", "barcode", "date", "in", "out","dif"
     , sum("in"-"out") over(partition by "user", "contact") as "sum"
from (
    select "user", "contact", "barcode", "date", "in", "out","dif"
    , lag(dif,1) over(partition by "user", "contact", "barcode" order by "date" ASC) prevdif
    , row_number() over(partition by "user", "contact", "barcode" order by "date" DESC) rn
    from "table1"
    where date_trunc('day', "date") <= '2017-06-25' ::date - (  interval '1 week')::interval
    and "date" >  '2017-06-25'::date - (  interval '2 weeks')::interval
    ) d
where rn = 1 and prevdif is not null
order by 1,2,4 DESC
</code>```

http://rextester.com/SCV98254

Body:
Get only latest data from last week and sum some column

I made an example with dat, the actual result and the expected.

http://rextester.com/HMB12638

 --Taking first as example..

--      user    contact         barcode date                in  out dif
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 80
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 90
-- 3    USER2   Guillermo Tole  987654  13.06.2017 05:27:00 400 380 20
-- 4    USER2   Guillermo Tole  281460  12.06.2017 05:26:00 230 190 40
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 6    USER3   Juan Rulfo      123456  12.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240
-- 8    USER3   Pepito Marquez  346234  14.06.2017 05:37:00 450 300 150

 -- This would be the expectation
-- (MOST RECENT in . out) SUM of all the barcodes showed
--      user    contact         barcode date                in  out sum
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 170 (80 + 90)
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 170 (80 + 90)
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240

Body:
I think this matches your expected result:

select "user", "contact", "barcode", "date", "in", "out","dif"
     , sum("in"-"out") over(partition by "user", "contact") as "sum"
from (
    select "user", "contact", "barcode", "date", "in", "out","dif"
    , lag(dif,1) over(partition by "user", "contact" order by "date" ASC) prevdif
    , row_number() over(partition by "user", "contact" order by "date" DESC) rn
    from "table1"
    where date_trunc('day', "date") <= '2017-06-25' ::date - (  interval '1 week')::interval
    and "date" >  '2017-06-25'::date - (  interval '2 weeks')::interval
    ) d
where rn in (1,2) and prevdif is not null
order by 1,2,4 DESC

Result:

+----+-------+----------------+---------+---------------------+-----+-----+-----+-----+
|    | user  |    contact     | barcode |        date         | in  | out | dif | sum |
+----+-------+----------------+---------+---------------------+-----+-----+-----+-----+
|  1 | USER2 | Guillermo Tole |  987654 | 16.06.2017 05:27:00 | 500 | 420 |  80 | 170 |
|  2 | USER2 | Guillermo Tole |  281460 | 15.06.2017 05:36:00 | 310 | 220 |  90 | 170 |
|  3 | USER3 | Juan Rulfo     |  123456 | 15.06.2017 05:37:00 | 450 | 300 | 150 | 150 |
|  4 | USER3 | Pepito Marquez |  346234 | 15.06.2017 05:37:00 | 600 | 360 | 240 | 240 |
+----+-------+----------------+---------+---------------------+-----+-----+-----+-----+

See: http://rextester.com/ISHS42170

For conditions such as "most recent" I find that using ROW_NUMBER() OVER() is the most convenient as it allows the whole row of each "most recent" event be returned which isn't quite so simple if using MAX() and GROUP BY. "Distinct" results are returned by filtering the rows having value 1 returned by the function.

+EDIT

Instead of using where rn in (1,2) I believe a better way would have been better to use barcode in the OVER(PARTITION BY...) conditions, like this:

select "user", "contact", "barcode", "date", "in", "out","dif"
     , sum("in"-"out") over(partition by "user", "contact") as "sum"
from (
    select "user", "contact", "barcode", "date", "in", "out","dif"
    , lag(dif,1) over(partition by "user", "contact", "barcode" order by "date" ASC) prevdif
    , row_number() over(partition by "user", "contact", "barcode" order by "date" DESC) rn
    from "table1"
    where date_trunc('day', "date") <= '2017-06-25' ::date - (  interval '1 week')::interval
    and "date" >  '2017-06-25'::date - (  interval '2 weeks')::interval
    ) d
where rn = 1 and prevdif is not null
order by 1,2,4 DESC

http://rextester.com/SCV98254


答:
We are talking about large dataset, so we might need the performance, as also we have the input data as a NumPy array. Listed in this post are two NumPy approaches.

Approach #1

Here's one approach using np.unique to get the row indices separating groups and then using a loop comprehension to get the dictionary output -

```<code>unq, idx = np.unique(x[:,0], return_index=1)
idx1 = np.r_[idx,x.shape[0]]
dict_out = {unq[i]:x[idx1[i]:idx1[i+1],1:] for i in range(len(unq))}
</code>```

This assumes the first column to be sorted as stated in the question title - ...repeated value in one column. If that's not the case, we need to use x[:,0].argsort() to sort the rows of x and then proceed.

Sample input, output -

```<code>In [41]: x
Out[41]:
array([[100,  14,  12,  15],
       [100,  21,  16,  11],
       [100,  19,  10,  13],
       [160,  24,  15,  12],
       [160,  43,  12,  65],
       [160,  17,  53,  23],
       [300,  15,  17,  11],
       [300,  66,  23,  12],
       [300,  44,  70,  19]])

In [42]: dict_out
Out[42]:
{100: array([[14, 12, 15],
        [21, 16, 11],
        [19, 10, 13]]), 160: array([[24, 15, 12],
        [43, 12, 65],
        [17, 53, 23]]), 300: array([[15, 17, 11],
        [66, 23, 12],
        [44, 70, 19]])}
</code>```

Approach #2

Here's another getting rid of np.unique for further performance boost -

```<code>idx1 = np.concatenate(([0],np.flatnonzero(x[1:,0] != x[:-1,0])+1, [x.shape[0]]))
dict_out = {x[i,0]:x[i:j,1:] for i,j in zip(idx1[:-1], idx1[1:])}
</code>```

Runtime test

Approaches -

```<code># @COLDSPEED's soln
from collections import defaultdict
def defaultdict_app(x):
    data = defaultdict(list)
    for l in x:
        data[l[0]].append(l[1:])

# @David Z's soln-1
import pandas as pd
def pandas_groupby_app(x):
    df = pd.DataFrame(x)
    return {key: group.iloc[:,1:] for key, group in df.groupby(0)}

# @David Z's soln-2
import itertools as it
def groupby_app(x):
    return {key: list(map(list, group)) for key, group in \
                        it.groupby(x, lambda row: row[0])}

# Proposed in this post
def numpy_app1(x):
    unq, idx = np.unique(x[:,0], return_index=1)
    idx1 = np.r_[idx,x.shape[0]]
    return {unq[i]:x[idx1[i]:idx1[i+1],1:] for i in range(len(unq))}

# Proposed in this post
def numpy_app2(x):
    idx1 = np.concatenate(([0],np.flatnonzero(x[1:,0] != x[:-1,0])+1, [x.shape[0]]))
    return {x[i,0]:x[i:j,1:] for i,j in zip(idx1[:-1], idx1[1:])}
</code>```

Timings -

```<code>In [84]: x = np.random.randint(0,100,(10000,4))

In [85]: x[:,0].sort()

In [86]: %timeit defaultdict_app(x)
    ...: %timeit pandas_groupby_app(x)
    ...: %timeit groupby_app(x)
    ...: %timeit numpy_app1(x)
    ...: %timeit numpy_app2(x)
    ...:
100 loops, best of 3: 4.43 ms per loop
100 loops, best of 3: 15 ms per loop
100 loops, best of 3: 12.1 ms per loop
1000 loops, best of 3: 310 µs per loop
10000 loops, best of 3: 75.6 µs per loop
</code>```

Title: Python: How to bin a set of data by a repeated value in one column

Body:
Say, I have a numpy array like this:

import numpy as np

x= np.array(
    [[100, 14, 12, 15],
    [100, 21, 16, 11],
    [100, 19, 10, 13],
    [160, 24, 15, 12],
    [160, 43, 12, 65],
    [160, 17, 53, 23],
    [300, 15, 17, 11],
    [300, 66, 23, 12],
    [300, 44, 70, 19]])

The original array is much bigger, so my question is if there's a way to bin or group rows based on the value on column 1?
for example:

{'100': [[14, 12, 15], [21, 16, 11], [19, 10, 13]],
,'160': [[24, 15, 12], [43, 12, 65], [17, 53, 23]],
,'300': [[15, 17, 11], [66, 23, 12], [44, 70, 19]]}

Body:
We are talking about large dataset, so we might need the performance, as also we have the input data as a NumPy array. Listed in this post are two NumPy approaches.

Approach #1

Here's one approach using np.unique to get the row indices separating groups and then using a loop comprehension to get the dictionary output -

unq, idx = np.unique(x[:,0], return_index=1)
idx1 = np.r_[idx,x.shape[0]]
dict_out = {unq[i]:x[idx1[i]:idx1[i+1],1:] for i in range(len(unq))}

This assumes the first column to be sorted as stated in the question title - ...repeated value in one column. If that's not the case, we need to use x[:,0].argsort() to sort the rows of x and then proceed.

Sample input, output -

In [41]: x
Out[41]:
array([[100,  14,  12,  15],
       [100,  21,  16,  11],
       [100,  19,  10,  13],
       [160,  24,  15,  12],
       [160,  43,  12,  65],
       [160,  17,  53,  23],
       [300,  15,  17,  11],
       [300,  66,  23,  12],
       [300,  44,  70,  19]])

In [42]: dict_out
Out[42]:
{100: array([[14, 12, 15],
        [21, 16, 11],
        [19, 10, 13]]), 160: array([[24, 15, 12],
        [43, 12, 65],
        [17, 53, 23]]), 300: array([[15, 17, 11],
        [66, 23, 12],
        [44, 70, 19]])}

Approach #2

Here's another getting rid of np.unique for further performance boost -

idx1 = np.concatenate(([0],np.flatnonzero(x[1:,0] != x[:-1,0])+1, [x.shape[0]]))
dict_out = {x[i,0]:x[i:j,1:] for i,j in zip(idx1[:-1], idx1[1:])}

Runtime test

Approaches -

# @COLDSPEED's soln
from collections import defaultdict
def defaultdict_app(x):
    data = defaultdict(list)
    for l in x:
        data[l[0]].append(l[1:])

# @David Z's soln-1
import pandas as pd
def pandas_groupby_app(x):
    df = pd.DataFrame(x)
    return {key: group.iloc[:,1:] for key, group in df.groupby(0)}

# @David Z's soln-2
import itertools as it
def groupby_app(x):
    return {key: list(map(list, group)) for key, group in \
                        it.groupby(x, lambda row: row[0])}

# Proposed in this post
def numpy_app1(x):
    unq, idx = np.unique(x[:,0], return_index=1)
    idx1 = np.r_[idx,x.shape[0]]
    return {unq[i]:x[idx1[i]:idx1[i+1],1:] for i in range(len(unq))}

# Proposed in this post
def numpy_app2(x):
    idx1 = np.concatenate(([0],np.flatnonzero(x[1:,0] != x[:-1,0])+1, [x.shape[0]]))
    return {x[i,0]:x[i:j,1:] for i,j in zip(idx1[:-1], idx1[1:])}

Timings -

In [84]: x = np.random.randint(0,100,(10000,4))

In [85]: x[:,0].sort()

In [86]: %timeit defaultdict_app(x)
    ...: %timeit pandas_groupby_app(x)
    ...: %timeit groupby_app(x)
    ...: %timeit numpy_app1(x)
    ...: %timeit numpy_app2(x)
    ...:
100 loops, best of 3: 4.43 ms per loop
100 loops, best of 3: 15 ms per loop
100 loops, best of 3: 12.1 ms per loop
1000 loops, best of 3: 310 µs per loop
10000 loops, best of 3: 75.6 µs per loop


问:
Error with Azure AD SingleSignOn
I have a subscription to azure and an already developed application, I'm trying to use Azure AD as authentification mechanism.

I created the application in Azure, added Azure AD as authentification mechanism and when I try to log in I get this error.

AADSTS65005: The app needs access to a service
  ("http://rts.powerapps.com") that your organization
  "123-32323-323232-3233" has not subscribed to or enabled. Contact your
  IT Admin to review the configuration of your service subscriptions.

This is my Startup Class.

```<code>public partial class Startup
{

    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

    string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
    }
}
</code>```

Any ideas?

EDIT 1:

After removing some app from my required permissions that appeared deleted now I get this error.

Error Img

EDIT 2:

Fixed after removing and adding the permissions again.

答:
It seems that you were developing with Common Data Service, based on the service("http://rts.powerapps.com"). Please ensure that that your organization doesn't have the subscribed the service ("http://rts.powerapps.com").

Please note the prerequisites of Common Data Service:

If you've already signed up for PowerApps, you can go to PowerApps and sign in. If you haven't yet signed up, you can follow these instructions to sign up.

Make sure that you have admin access to an environment that contains a Common Data Service database. Go to the PowerApps portal, click the gear icon in the upper right of the page, and then click Admin center. If you don't have admin access to any environments that contain a database, follow these instructions to create a database.

And below is helpful document to help get started:

Get started with the Common Data Service SDK

Title: Error with Azure AD SingleSignOn

Body:
I have a subscription to azure and an already developed application, I'm trying to use Azure AD as authentification mechanism.

I created the application in Azure, added Azure AD as authentification mechanism and when I try to log in I get this error.

AADSTS65005: The app needs access to a service
  ("http://rts.powerapps.com") that your organization
  "123-32323-323232-3233" has not subscribed to or enabled. Contact your
  IT Admin to review the configuration of your service subscriptions.

This is my Startup Class.

public partial class Startup
{

    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

    string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
    }
}

Any ideas?

EDIT 1:

After removing some app from my required permissions that appeared deleted now I get this error.

Error Img

EDIT 2:

Fixed after removing and adding the permissions again.


问:
Text not wrapping inside a flex container
I managed to use the Flexible Box Layout Module for a lot of things, however when it comes to paragraphs I'm experiencing this issue:

When I use a small amount of text everything works as expected:

When I use a large amount of text the layout breaks:

Here is the code I am using:

body {
  width: 90%;
  margin: 3em auto;
  background-color: #aaa;
}
section {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  border: 1px solid black;
}
.title {
  flex: 1 0 100%;
  text-align: center;
  background-color: #eee;
}
.image {
  flex: 0 0 auto;
  background-color: #ccc;
}
.image img {
  display: block;
  max-height: 100%;
  max-width: 100%;
}
.text {
  flex: 6 0 auto;
  background-color: #96AED1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <div class="title">
    <h1>Title here</h1>
  </div>

  <div class="image">
    <img src="http://www.macovei-sculptor.ro/img.jpg">
  </div>

  <div class="text">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer felis velit, ullamcorper eu ornare sed, vulputate quis diam. Duis ultrices rutrum sapien, in condimentum nibh sagittis sit amet. Morbi sit amet rhoncus dui, at pharetra nisi. Nunc et
      lacus porttitor, pretium nisl at, sollicitudin velit. Donec felis nisl, consequat vitae egestas vestibulum, egestas non tortor. Cras mattis non sem nec aliquam. Sed dignissim sit amet sapien vitae feugiat. Pellentesque vel luctus ante, quis ornare
      purus. Nulla in arcu sapien. Aenean tempor arcu ac lacinia pellentesque. Quisque vulputate maximus augue, non aliquet ligula gravida in. Donec a leo justo. Integer velit eros, blandit sit amet elit eget, efficitur mollis nulla. Suspendisse tempor
      ligula facilisis scelerisque ullamcorper. Ut vehicula ligula ipsum, cursus condimentum sapien pretium ac.</p>
  </div>
</section></code>```

Why is the
 tag not wrapping properly when using a large amount of text?

答:
The proper solution is either to put

```<code>white-space: initial;
</code>```

or

```<code>min-width: 0;
</code>```

Check out the link here

*I am aware the link is about truncating texts. However, the same solution applies to wrap the texts around.

Body:
I managed to use the Flexible Box Layout Module for a lot of things, however when it comes to paragraphs I'm experiencing this issue:

When I use a small amount of text everything works as expected:

When I use a large amount of text the layout breaks:

Here is the code I am using:

body {
  width: 90%;
  margin: 3em auto;
  background-color: #aaa;
}
section {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  border: 1px solid black;
}
.title {
  flex: 1 0 100%;
  text-align: center;
  background-color: #eee;
}
.image {
  flex: 0 0 auto;
  background-color: #ccc;
}
.image img {
  display: block;
  max-height: 100%;
  max-width: 100%;
}
.text {
  flex: 6 0 auto;
  background-color: #96AED1;
}

Title here

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer felis velit, ullamcorper eu ornare sed, vulputate quis diam. Duis ultrices rutrum sapien, in condimentum nibh sagittis sit amet. Morbi sit amet rhoncus dui, at pharetra nisi. Nunc et
      lacus porttitor, pretium nisl at, sollicitudin velit. Donec felis nisl, consequat vitae egestas vestibulum, egestas non tortor. Cras mattis non sem nec aliquam. Sed dignissim sit amet sapien vitae feugiat. Pellentesque vel luctus ante, quis ornare
      purus. Nulla in arcu sapien. Aenean tempor arcu ac lacinia pellentesque. Quisque vulputate maximus augue, non aliquet ligula gravida in. Donec a leo justo. Integer velit eros, blandit sit amet elit eget, efficitur mollis nulla. Suspendisse tempor
      ligula facilisis scelerisque ullamcorper. Ut vehicula ligula ipsum, cursus condimentum sapien pretium ac.

Why is the
 tag not wrapping properly when using a large amount of text?

Body:
The proper solution is either to put

white-space: initial;

or

min-width: 0;

Check out the link here

*I am aware the link is about truncating texts. However, the same solution applies to wrap the texts around.


问:
Read property file placed inside in package under src/test/resource in maven
My maven structure looks as below:

Have placed property file inside package under src/test/resources
And I trying to read from java class( Browser Test) under src/test/java

I am using below code to ready file, but the getting NullPointerException.

```<code>public Static Properties CONFIG
CONFIG = new Properties();
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);

[31mMessage: [0m[31mjava.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)
</code>```

答:
Put the resource files in the root of the src/test/resources tree (src/test/resources/application.properties). Then use a static initialization block. Like,

```<code>public static Properties CONFIG = new Properties();
static {
    try {
        CONFIG.load(BrowserTest.class.getResourceAsStream(
                "application.properties"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Body:
My maven structure looks as below:

Have placed property file inside package under src/test/resources
And I trying to read from java class( Browser Test) under src/test/java

I am using below code to ready file, but the getting NullPointerException.

public Static Properties CONFIG
CONFIG = new Properties();
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);

[31mMessage: [0m[31mjava.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)

Body:
Put the resource files in the root of the src/test/resources tree (src/test/resources/application.properties). Then use a static initialization block. Like,

public static Properties CONFIG = new Properties();
static {
    try {
        CONFIG.load(BrowserTest.class.getResourceAsStream(
                "application.properties"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}


问:
Setting up Android Development Environment on Windows 7
I want to start learning Android developement. I have a windows 7 Home Premium Operating System. My problem is I am not able to setup the environment of developing android. Here is what I have done till now.

I have installed Java (both 32 bit and 64 bit versions)

I have installed Android SDK (installer_r08-windows.exe)

I have not yet downloaded any tools or platforms or ADT.

I have downloaded 32 bit eclipse. (eclipse-SDK-3.5.1-win32.zip)

I am stuck at this eclipse setup. A strange thing I observed is that, it does not install. When I click on eclipse.exe, it starts running from there only. I am still not sure if my eclipse installation is proper?

So, I assumed that my eclipse is working fine. Then when I try installing new programs in eclipse, eg google plugin, it gives error.

I want to know, where am I going wrong? What mistakes am I doing?
Can anyone guide me with the complete step by step procedure to setup my android development environment on windows 7?

Thanks in advance.

Jay

答:
to 5: Eclipse don't have a normal installer, its just a zip file you can extract and run from anywhere.

to 6: What errors do you get? (I will update my answer when you deliver more details)

A step by step how to is here: http://developer.android.com/sdk/installing.html

ContentLicense: CC BY-SA 2.5


问:
.htaccess serve index from subdirectory
I have an API in PHP that I want to serve with apache using .htaccess files. The server is configured to host a specific directory as https://www.example.com/~user/.

```<code>/web/
├── index.html
└── api/
    ├── .htaccess
    ├── public/
    │   └── index.php
    └── src/
</code>```

What I would like to achieve is that https://www.example.com/~user/api/ serves the index.php file that is in the public/ subdirectory while redirecting its base: https://www.example.com/~user/api/v1/ would then be matched as v1/ inside index.php.

Originally my setup featured a .htaccess file inside the public/ directory but this would create an url like https://www.example.com/~user/api/public/v1/ which is undesirable.

RewriteEngine On

RewriteBase /~user/api/public/

# If the file with the specified name in the browser doesn't exist,
# or the directory in the browser doesn't exist then proceed to the rewrite rule below
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
```

答:
You can use something like this in your api directory:

```<code>RewriteEngine On
RewriteBase /~user/api/
RewriteRule !^public/index\.php$ public/index.php [L]
</code>```

In your PHP, you can get the URL that was visited from $_SERVER['REQUEST_URI'] which will contain the original URL.

If you don't want to rewrite existing files and directories, use:

```<code>RewriteEngine On
RewriteBase /~user/api/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !^public/index\.php$ public/index.php [L]
</code>```

Title: .htaccess serve index from subdirectory

Body:
I have an API in PHP that I want to serve with apache using .htaccess files. The server is configured to host a specific directory as https://www.example.com/~user/.

/web/
├── index.html
└── api/
    ├── .htaccess
    ├── public/
    │   └── index.php
    └── src/

What I would like to achieve is that https://www.example.com/~user/api/ serves the index.php file that is in the public/ subdirectory while redirecting its base: https://www.example.com/~user/api/v1/ would then be matched as v1/ inside index.php.

Originally my setup featured a .htaccess file inside the public/ directory but this would create an url like https://www.example.com/~user/api/public/v1/ which is undesirable.

RewriteEngine On

RewriteBase /~user/api/public/

# If the file with the specified name in the browser doesn't exist,
# or the directory in the browser doesn't exist then proceed to the rewrite rule below
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Body:
You can use something like this in your api directory:

RewriteEngine On
RewriteBase /~user/api/
RewriteRule !^public/index\.php$ public/index.php [L]

In your PHP, you can get the URL that was visited from $_SERVER['REQUEST_URI'] which will contain the original URL.

If you don't want to rewrite existing files and directories, use:

RewriteEngine On
RewriteBase /~user/api/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !^public/index\.php$ public/index.php [L]


问:
Full Json match with RestAssured
I'm using REST-Assured to test some API. My API clearly respond with a JSON and according to the doc if this is the response:

```<code>{
    "id": "390",
    "data": {
        "leagueId": 35,
        "homeTeam": "Norway",
        "visitingTeam": "England",
    },
    "odds": [{
        "price": "1.30",
        "name": "1"
    },
    {
        "price": "5.25",
        "name": "X"
    }]
}
</code>```

I could test like this:

```<code>@Test
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
   get("/events?id=390")
      .then()
         .statusCode(200)
         .assertThat()
            .body("data.leagueId", equalTo(35));
}
</code>```

Surely this is readable but I would a full comparison of the JSON (i.e.: this is the JSON response; this is a canned JSON - a resource file would be perfect - are those JSON equals?). Does REST-Assured offer something like that or I need to make it manually.

答:
Karate is exactly what you are looking for - you can perform a full equality match of a JSON payload in one step.

And for the cases where you have dynamic values (generated keys, timestamps) Karate provides a very elegant way for you to ignore (or just validate the format of) these keys.

One the primary motivations for creating Karate was to come up with a better alternative to REST-assured. You can refer to this document which can help you evaluate Karate and make a case for it in your organization: Karate vs REST-assured.

Title: Full Json match with RestAssured

Body:
I'm using REST-Assured to test some API. My API clearly respond with a JSON and according to the doc if this is the response:

{
    "id": "390",
    "data": {
        "leagueId": 35,
        "homeTeam": "Norway",
        "visitingTeam": "England",
    },
    "odds": [{
        "price": "1.30",
        "name": "1"
    },
    {
        "price": "5.25",
        "name": "X"
    }]
}

I could test like this:

@Test
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
   get("/events?id=390")
      .then()
         .statusCode(200)
         .assertThat()
            .body("data.leagueId", equalTo(35));
}

Surely this is readable but I would a full comparison of the JSON (i.e.: this is the JSON response; this is a canned JSON - a resource file would be perfect - are those JSON equals?). Does REST-Assured offer something like that or I need to make it manually.


问:
PHP count all elements in an array
I'm unable to get the sizeof/count of the pages_article array in the $total_count variable. I tried $total_count = count($this->pages_articles); and it's not able to count all the elements in the pages_articles array. I tried sizeof as well and it's the same problem. There's 8 elements in the array and when I do echo/print, it displays 0.</p>

```<code>  <?php
  class Pagination {
  public $current_page;
  public $per_page;
  public $total_count;
  public $pages_articles;

  public function __construct($page=1, $per_page=20, $total_count=0) {
 $this->current_page = (int)$page;
 $this->per_page = (int)$per_page;
 $this->total_count = (int)$total_count;
 $this->pages_articles=array(
  '<div class="article-loop"><img src="http://i.imgur.com/CmU3tnl.jpg"></div>',
  '<div class="article-loop"><img src="http://i.imgur.com/TDdxS9H.png"></div>',
  '<div class="article-loop"><img src="http://i.imgur.com/39rpmwB.jpg"></div>',
  '<div class="article-loop"><img src="http://i.imgur.com/1lBZQ1B.png"></div>',
  '<div class="article-loop"><img src="https://i.imgur.com/Y5Ld4Qfh.jpg"></div>',
  '<div class="article-loop"><img src="http://i.imgur.com/8HumESY.jpg"></div>',
  '<div class="article-loop"><img src="http://i.imgur.com/CqCZBvk.png"></div>',
  '<div class="article-loop"><img src="http://i.imgur.com/wQVPRVp.png"></div>');
  }

  public function offset() {
return ($this->current_page - 1) * $this->per_page;
   }
  public function total_pages() {
//$this->total_count=sizeof($this->pages_articles);
return ceil($this->total_count/$this->per_page);
   }
  public function previous_page() {
return $this->current_page - 1;
   }
  public function next_page() {
return $this->current_page + 1;
   }
  public function has_previous_page() {
return $this->previous_page() >= 1 ? true : false;
   }
  public function has_next_page() {
return $this->next_page() <= $this->total_pages() ? true : false;
   }
  }
  $page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
  $per_page = 3;
  $total_count=8;
  $pagination = new Pagination($page, $per_page, $total_count);
  ?>

  <html>
  <body>
  <div>
<?php
    $i = $pagination->offset()  ;
    $limit = $pagination->per_page;
    while($i<$pagination->total_count && $limit>0) {
        echo $pagination->pages_articles[$i]."<br>";
        $i++;
        $limit--;
    }
      ?>
  </div>
  <ul>
      <?php
    if($pagination->has_previous_page()) {
        echo '<li style="display:inline"><a  href="index.php?page='.$pagination->previous_page().'">«</a></li>';
    } else {
        echo '<li style="display:inline" class="disabled"><a href="#">«</a></li>';
    }
    for($i=1; $i<=$pagination->total_pages(); $i++) {
        echo '<a href="index.php?page='.$i.'"><li style="display:inline; margin-left:5px; margin-right:5px">'.$i.'</li></a>';
    }
    if($pagination->has_next_page()) {
        echo '<li style="display:inline"><a href="index.php?page='.$pagination->next_page().'">»</a></li>';
    } else {
        echo '<li style="display:inline" class="disabled"><a href="#">»</a></li>';
    }
   ?>
  </ul>
  </body>
  </html>
</code>```

答: Try count($array, COUNT_RECURSIVE)

Title: PHP count all elements in an array

Body:
I'm unable to get the sizeof/count of the pages_article array in the $total_count variable. I tried $total_count = count($this->pages_articles); and it's not able to count all the elements in the pages_articles array. I tried sizeof as well and it's the same problem. There's 8 elements in the array and when I do echo/print, it displays 0.

  <?php
  class Pagination {
  public $current_page;
  public $per_page;
  public $total_count;
  public $pages_articles;

  public function __construct($page=1, $per_page=20, $total_count=0) {
 $this->current_page = (int)$page;
 $this->per_page = (int)$per_page;
 $this->total_count = (int)$total_count;
 $this->pages_articles=array(
  '

',
  '

',
  '

',
  '

',
  '

',
  '

',
  '

',
  '

');
  }

  public function offset() {
return ($this->current_page - 1) * $this->per_page;
   }
  public function total_pages() {
//$this->total_count=sizeof($this->pages_articles);
return ceil($this->total_count/$this->per_page);
   }
  public function previous_page() {
return $this->current_page - 1;
   }
  public function next_page() {
return $this->current_page + 1;
   }
  public function has_previous_page() {
return $this->previous_page() >= 1 ? true : false;
   }
  public function has_next_page() {
return $this->next_page() <= $this->total_pages() ? true : false;
   }
  }
  $page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
  $per_page = 3;
  $total_count=8;
  $pagination = new Pagination($page, $per_page, $total_count);
  ?>

<?php
    $i = $pagination->offset()  ;
    $limit = $pagination->per_page;
    while($i<$pagination->total_count && $limit>0) {
        echo $pagination->pages_articles[$i]."
";
        $i++;
        $limit--;
    }
      ?>

      <?php
    if($pagination->has_previous_page()) {
        echo '
previous_page().'">«
';
    } else {
        echo '
«
';
    }
    for($i=1; $i<=$pagination->total_pages(); $i++) {
        echo '
'.$i.'
';
    }
    if($pagination->has_next_page()) {
        echo '
next_page().'">»
';
    } else {
        echo '
»
';
    }
   ?>

Body: Try count($array, COUNT_RECURSIVE)


问:
How to keep service alive when remove app from stack
I want to show notification every minute using Alarm Manager, I have implemented below code, it's working fine but the problem is when I remove app from stack the service is not running.

I want keep alive, I have tried START_STICKY in onStartCommand and also used onTaskRemoved but it's same.

I also tried to implement using WakefulIntentService but the problem is same. My code is below.

In MainActivity

```<code>    Intent myIntent = new Intent(NotificationDemo.this, MyReceiver.class);

                myIntent.putExtra("title", "2 minutes");

                Random random = new Random();
                int m = random.nextInt(9999 - 1000) + 1000;

                Log.d("m::: In Notification", m + "");
                myIntent.putExtra("id", m);

                pendingIntent = PendingIntent.getBroadcast(NotificationDemo.this, m, myIntent, 0);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
//                alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),alarmManager.Inte pendingIntent);
                alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime(),
                        1 * 60 * 1000,
                        pendingIntent);
</code>```

MyService

```<code>       public class MyAlarmService extends Service {

            private NotificationManager mManager;

            @Override
            public IBinder onBind(Intent arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void onCreate() {
                // TODO Auto-generated method stub
                super.onCreate();
            }

            @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
        String title = intent.getStringExtra("title");
        int id = intent.getIntExtra("id", 0);
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);

        Notification notification = new Notification(R.mipmap.ic_launcher, title, System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Log.d("id::", id + "");

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(MyAlarmService.this);

        notification = builder.setContentTitle(title)
                .setContentText("Hellooo...")
                .setTicker("Good Evening...")
                .setSmallIcon(android.R.drawable.ic_btn_speak_now)
                .setVibrate(new long[]{1000, 1000, 1000, 100})
                .setLights(5, 5, 5)
                .setContentIntent(pendingNotificationIntent).build();

        mManager.notify(id, notification);
        startForeground(1337, notification);
        return START_STICKY;
    }

            @Override
            public void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
               // sendBroadcast(new Intent("IWillStartAuto"));
            }

            @Override
            public void onTaskRemoved(Intent rootIntent) {
                super.onTaskRemoved(rootIntent);
        //        sendBroadcast(new Intent("IWillStartAuto"));
        //        Intent intent = new Intent(getApplicationContext(),MyReceiver.class);
        //        sendBroadcast(intent);
            }
        }
</code>```

and this is my receiver

```<code>public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         String title = intent.getStringExtra("title");
    int id = intent.getIntExtra("id", 0);
    Intent service1 = new Intent(context, MyAlarmService.class);
    service1.putExtra("title", title);
    service1.putExtra("id", id);
    context.startService(service1);

    }
}
</code>```

In Manifest

```<code><receiver android:name=".MyReceiver">
        <!--<intent-filter>
            <action android:name="IWillStartAuto"/>
        </intent-filter>-->
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service
        android:name=".MyAlarmService"
        android:enabled="true"
        android:stopWithTask="false" />
</code>```

答:
I tested this code on my phone with android 6.0 and on emulator with android 7.0 in both is working fine, even removing the application from the stack.
The notification still working even removing the receiver code.

Body:
I want to show notification every minute using Alarm Manager, I have implemented below code, it's working fine but the problem is when I remove app from stack the service is not running.

I want keep alive, I have tried START_STICKY in onStartCommand and also used onTaskRemoved but it's same.

I also tried to implement using WakefulIntentService but the problem is same. My code is below.

In MainActivity

    Intent myIntent = new Intent(NotificationDemo.this, MyReceiver.class);

                myIntent.putExtra("title", "2 minutes");

                Random random = new Random();
                int m = random.nextInt(9999 - 1000) + 1000;

                Log.d("m::: In Notification", m + "");
                myIntent.putExtra("id", m);

                pendingIntent = PendingIntent.getBroadcast(NotificationDemo.this, m, myIntent, 0);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
//                alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),alarmManager.Inte pendingIntent);
                alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime(),
                        1 * 60 * 1000,
                        pendingIntent);

MyService

       public class MyAlarmService extends Service {

            private NotificationManager mManager;

            @Override
            public IBinder onBind(Intent arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void onCreate() {
                // TODO Auto-generated method stub
                super.onCreate();
            }

            @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
        String title = intent.getStringExtra("title");
        int id = intent.getIntExtra("id", 0);
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);

        Notification notification = new Notification(R.mipmap.ic_launcher, title, System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Log.d("id::", id + "");

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(MyAlarmService.this);

        notification = builder.setContentTitle(title)
                .setContentText("Hellooo...")
                .setTicker("Good Evening...")
                .setSmallIcon(android.R.drawable.ic_btn_speak_now)
                .setVibrate(new long[]{1000, 1000, 1000, 100})
                .setLights(5, 5, 5)
                .setContentIntent(pendingNotificationIntent).build();

        mManager.notify(id, notification);
        startForeground(1337, notification);
        return START_STICKY;
    }

            @Override
            public void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
               // sendBroadcast(new Intent("IWillStartAuto"));
            }

            @Override
            public void onTaskRemoved(Intent rootIntent) {
                super.onTaskRemoved(rootIntent);
        //        sendBroadcast(new Intent("IWillStartAuto"));
        //        Intent intent = new Intent(getApplicationContext(),MyReceiver.class);
        //        sendBroadcast(intent);
            }
        }

and this is my receiver

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         String title = intent.getStringExtra("title");
    int id = intent.getIntExtra("id", 0);
    Intent service1 = new Intent(context, MyAlarmService.class);
    service1.putExtra("title", title);
    service1.putExtra("id", id);
    context.startService(service1);

    }
}

In Manifest

<receiver android:name=".MyReceiver">

        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service
        android:name=".MyAlarmService"
        android:enabled="true"
        android:stopWithTask="false" />


问:
Creating, writing and editing same text file in java
Let's say I have the following code:

```<code>import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class EditFile {

    public static void main(String[] args) {

        try{
            String verify, putData;
            File file = new File("file.txt");
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("Some text here for a reason");
            bw.flush();
            bw.close();
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            while( br.readLine() != null ){
                verify = br.readLine();
                if(verify != null){
                    putData = verify.replaceAll("here", "there");
                    bw.write(putData);
                }
            }
            br.close();

        }catch(IOException e){
        e.printStackTrace();
        }
    }

}
</code>```

All I wanted to do was to write something in a text file, in my case "Some text here for a reason". Then to read data from my file, and finally to change my text from my file from "Some text here for a reason" in "Some text there for a reason". I ran the code but all it happens is to write in my file "Some text here for a reason".

I tried to figure out what could be wrong in my code, but unfortunately it was in vain. Any advice or rewrite is highly appreciated from me.

答:
```<code>import java.io.*;

public class TextFile
{
    public static void main(String[] args)
    {
        try
        {
            String verify, putData;
            File file = new File("G:\\Dairy.txt");
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("I am Shah Khalid");
            bw.flush();

            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            while( (verify=br.readLine()) != null )
            {
                if(verify != null)
                {
                    putData = verify.replaceAll("here", "there");
                    //bw.write(putData);
                }
            }
            br.close();
            bw.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        System.out.println("Shah");
    }
}
</code>```

There is no need to type bw.write(putData);, because it will just print the statement twice.

Whatever you want in a file, just give the correct path of the file and use the above code accordingly.

Body:
Let's say I have the following code:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class EditFile {

    public static void main(String[] args) {

        try{
            String verify, putData;
            File file = new File("file.txt");
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("Some text here for a reason");
            bw.flush();
            bw.close();
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            while( br.readLine() != null ){
                verify = br.readLine();
                if(verify != null){
                    putData = verify.replaceAll("here", "there");
                    bw.write(putData);
                }
            }
            br.close();

        }catch(IOException e){
        e.printStackTrace();
        }
    }

}

All I wanted to do was to write something in a text file, in my case "Some text here for a reason". Then to read data from my file, and finally to change my text from my file from "Some text here for a reason" in "Some text there for a reason". I ran the code but all it happens is to write in my file "Some text here for a reason".

I tried to figure out what could be wrong in my code, but unfortunately it was in vain. Any advice or rewrite is highly appreciated from me.

Body:
import java.io.*;

public class TextFile
{
    public static void main(String[] args)
    {
        try
        {
            String verify, putData;
            File file = new File("G:\\Dairy.txt");
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("I am Shah Khalid");
            bw.flush();

            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            while( (verify=br.readLine()) != null )
            {
                if(verify != null)
                {
                    putData = verify.replaceAll("here", "there");
                    //bw.write(putData);
                }
            }
            br.close();
            bw.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        System.out.println("Shah");
    }
}

There is no need to type bw.write(putData);, because it will just print the statement twice.

Whatever you want in a file, just give the correct path of the file and use the above code accordingly.


问:
How to play Youtube videos using Expo
I am trying to use the react-native-youtube component in my expo project. However, I couldn't get it to work. All I have so far is a black screen with red borders. I tried following the video instructions on online however, expo doesn't have an iOS or Android folder, which means I can't open it in XCode and fiddle with it. How can I play youtube videos using expo? As you might have noticed from my question I'm new to react-native using expo. </p>

答:
At the moment, YouTube is not supported by Expo. You can either eject the project and install the react-native-youtube library or load your videos from a WebView like this:</p>
```<code><WebView
    style={{flex:1}}
    javaScriptEnabled={true}
    source={{uri: 'https://www.youtube.com/embed/ZZ5LpwO-An4?rel=0&autoplay=0&showinfo=0&controls=0'}}
/>
</code>```

Title: How to play Youtube videos using Expo

Body:
At the moment, YouTube is not supported by Expo. You can either eject the project and install the react-native-youtube library or load your videos from a WebView like this:

<WebView
    style={{flex:1}}
    javaScriptEnabled={true}
    source={{uri: 'https://www.youtube.com/embed/ZZ5LpwO-An4?rel=0&autoplay=0&showinfo=0&controls=0'}}
/>


问:
AWS API Gateway Method Authorization
I have domain with aws example.com, currently I have record set so that when user goes to example.com, it serves static website from S3 (done with angular) and backend api (Lambda and API gate way). And I don't have sign in process, as the purpose of site is public facing.

I can use apikey on method to authorize the http call, but I still have to save it in js code somewhere, which I don;t want to do. And I am not sure how IAM role can help me in this scenario.

Is there any way I can let api allow calls from specific domain ?

答:
You can use IAM Role defined for Unauthenticated user in AWS Cognito Federated Identities. The AWS document will guide through the process assigning IAM Role to the Unauthenticated user.

Then you can enable "AWS_IAM" Authorizer option in the API Gateway for any specific API's resources.

This question has similar approach in implementing the IAM Role - based to access API, in which the implementation is using External Federated Identities (Google) instead of unauthenticated user identities.

Title: AWS API Gateway Method Authorization


问:
Java Thread: Run method cannot throw checked exception
In Java thread, the 'run' method cannot throw a 'checked exception'. I came across this in the Core Java (vol 1)  book. Can someone please explain the reasoning behind it? </p>

答:
Can someone please explain the reasoning behind it?

Yes, because any exception you throw in run method will be carefully ignored by JVM. Thus, throwing it there is probably a mistake (unless you have specific exception handler for the thread, see the docs about that). No reason to incite potentially erroneous behaviour.

Or, with an example.

```<code> class MyThread extends Thread {
     public void run() {
         throw new RuntimeException();
     }
 }

...

new MyThread().start();
// here thread dies silently with no visible effects at all
</code>```

edit

Why can't the parent thread 'catch' the exception from the spawned 'child' thread?

@chaotic3quilibrium has already noted in his comment why not: because parent thread has likely moved on already.

```<code>new MyThread().start(); // launch thread and forget

// 1000 lines of code further...
i = i + 1; // would you like exception from child thread to be propagated here?
</code>```

Body:
Can someone please explain the reasoning behind it?

Yes, because any exception you throw in run method will be carefully ignored by JVM. Thus, throwing it there is probably a mistake (unless you have specific exception handler for the thread, see the docs about that). No reason to incite potentially erroneous behaviour.

Or, with an example.

 class MyThread extends Thread {
     public void run() {
         throw new RuntimeException();
     }
 }

...

new MyThread().start();
// here thread dies silently with no visible effects at all

edit

Why can't the parent thread 'catch' the exception from the spawned 'child' thread?

@chaotic3quilibrium has already noted in his comment why not: because parent thread has likely moved on already.

new MyThread().start(); // launch thread and forget

// 1000 lines of code further...
i = i + 1; // would you like exception from child thread to be propagated here?