问:
Can't parse from Json to Object Array in Unity (Firebase)
Good afternoon, I spent the whole morning breaking my head trying to pass a JSON to an array using the JsonHelper class, without success. Let's see if someone throws a cable to see where the failure is. Clarify that I'm making a game in Unity (in case Unity is the one that limits the code or something).

The fact is that I'm trying to make a ranking with the players and scores I have in a database in Firebase.

As you can see below with the class WWW sent the route and the text that returns the www is that json below.

```<code>public void Ranking ()
{
    string url = "https://example.firebaseio.com/.json";
    WWW www = new WWW (url);
    StartCoroutine (WaitForRequest (www));
}

IEnumerator WaitForRequest (WWW www)
{
    yield return www;

    // check for errors
    if (www.error == null)
    {
        User[] users;
        users = JsonHelper.FromJson <User> (www.text);

        Debug.Log ("WWW Ok !:" + www.text);
    }
    else
    {
        Debug.Log ("WWW Error:" + www.error);
    }
}
</code>```

And this is the returned string

```<code>{"Eduardito": {"playerName": "Eduardito", "playerScore": "4"}, "Joel": {"playerName": "Joel", "playerScore": "4"}, "Karla": { "playerName": "Karla", "playerScore": "5"}, "Miguelin": {"playerName": "Miguelin", "playerScore": "4"}}
</code>```

So far so good, the mess arrives at the time of using the JsonHelper class to pass it to an array. All the time it returns null. I do not know if it's because in the User's class something is wrong or not. Anyone who can think of something? Thanksss! Sorry for my bad english

Edit: The user class simply has the constructor and the two variables for the name and the score, nothing more.

I'm putting the JsonHelper class in

```<code>public static class JsonHelper
{
    public static User[] FromJson<User>(string json)
    {
        Wrapper<User> wrapper = JsonUtility.FromJson<Wrapper<User>>(json);

        Debug.Log(wrapper.Items);

        return wrapper.Items;
    }

    public static string ToJson<User> (User[] array)
    {
        Wrapper<User> wrapper = new Wrapper<User> ();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson <User>(User[] array, bool prettyPrint)
    {
        Wrapper <User> wrapper = new Wrapper<User>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    internal static string ArrayToJsonString<T>(User[] res, bool v)
    {
        throw new NotImplementedException();
    }

    [Serializable]
    private class Wrapper<User>
    {
        public User[] Items;
    }
}
</code>```

答:
Ok, lets start from the beginning. The JSON returning from your WWW request is not an array, its an object. So you should try to change the format of the return of your request to something like:

```<code>[{"playerName": "Eduardito", "playerScore": "4"}, {"playerName": "Joel", "playerScore": "4"}]
</code>```

Now this is an array!

Then, you should be sure that your User class is marked as serializable too, don't forget that!

At last but not least, remember that the JsonUtility class only works with objects, so it will not be able to deserialize the array because an array is not exactly an object. So, since your Wrapper class contains an parameter called Items, the JSONUtility will look for a parameter called Items on the given JSON.
You can fix this by changing your JSONHelper.FromJson function to something like:

```<code>Wrapper <User> wrapper = JsonUtility.FromJson <Wrapper <User >> ("{\"Items\":" + json + "}");
</code>```

That way the JsonUtility deserializer will find an parameter called Items and will correctly deserialize it to your wrapper class.

Here is a simple version of your code so you can better understand what Im talking. You can copy and past it in your unity and it should works properly.

```<code>public class JSONTest : MonoBehaviour
{
    private string jsonStr = "[{\"playerName\": \"Eduardito\", \"playerScore\": \"4\"}, {\"playerName\": \"Joel\", \"playerScore\": \"4\"}]";

    [Serializable]
    public class JSONArray<T>
    {
        public T[] Items;
    }

    [Serializable]
    public class User
    {
        public string playerName;
        public string playerScore;
    }

    void Start()
    {
        JSONArray<User> users = JsonUtility.FromJson<JSONArray<User>>("{\"Items\":" + jsonStr + "}");
        if (users.Items != null && users.Items.Length > 0)
        {
            foreach (User user in users.Items)
            {
                Debug.Log("Deserialized user " + user.playerName);
            }
        }
        else
        {
            Debug.Log("I should never reach this code.");
        }
    }
}
</code>```

Body:
Good afternoon, I spent the whole morning breaking my head trying to pass a JSON to an array using the JsonHelper class, without success. Let's see if someone throws a cable to see where the failure is. Clarify that I'm making a game in Unity (in case Unity is the one that limits the code or something).

The fact is that I'm trying to make a ranking with the players and scores I have in a database in Firebase.

As you can see below with the class WWW sent the route and the text that returns the www is that json below.

public void Ranking ()
{
    string url = "https://example.firebaseio.com/.json";
    WWW www = new WWW (url);
    StartCoroutine (WaitForRequest (www));
}

IEnumerator WaitForRequest (WWW www)
{
    yield return www;

    // check for errors
    if (www.error == null)
    {
        User[] users;
        users = JsonHelper.FromJson <User> (www.text);

        Debug.Log ("WWW Ok !:" + www.text);
    }
    else
    {
        Debug.Log ("WWW Error:" + www.error);
    }
}

And this is the returned string

{"Eduardito": {"playerName": "Eduardito", "playerScore": "4"}, "Joel": {"playerName": "Joel", "playerScore": "4"}, "Karla": { "playerName": "Karla", "playerScore": "5"}, "Miguelin": {"playerName": "Miguelin", "playerScore": "4"}}

So far so good, the mess arrives at the time of using the JsonHelper class to pass it to an array. All the time it returns null. I do not know if it's because in the User's class something is wrong or not. Anyone who can think of something? Thanksss! Sorry for my bad english

Edit: The user class simply has the constructor and the two variables for the name and the score, nothing more.

I'm putting the JsonHelper class in

public static class JsonHelper
{
    public static User[] FromJson<User>(string json)
    {
        Wrapper<User> wrapper = JsonUtility.FromJson<Wrapper<User>>(json);

        Debug.Log(wrapper.Items);

        return wrapper.Items;
    }

    public static string ToJson<User> (User[] array)
    {
        Wrapper<User> wrapper = new Wrapper<User> ();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson <User>(User[] array, bool prettyPrint)
    {
        Wrapper <User> wrapper = new Wrapper<User>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    internal static string ArrayToJsonString<T>(User[] res, bool v)
    {
        throw new NotImplementedException();
    }

    [Serializable]
    private class Wrapper<User>
    {
        public User[] Items;
    }
}

Body:
Ok, lets start from the beginning. The JSON returning from your WWW request is not an array, its an object. So you should try to change the format of the return of your request to something like:

[{"playerName": "Eduardito", "playerScore": "4"}, {"playerName": "Joel", "playerScore": "4"}]

Now this is an array!

Then, you should be sure that your User class is marked as serializable too, don't forget that!

At last but not least, remember that the JsonUtility class only works with objects, so it will not be able to deserialize the array because an array is not exactly an object. So, since your Wrapper class contains an parameter called Items, the JSONUtility will look for a parameter called Items on the given JSON.
You can fix this by changing your JSONHelper.FromJson function to something like:

Wrapper <User> wrapper = JsonUtility.FromJson <Wrapper <User >> ("{\"Items\":" + json + "}");

That way the JsonUtility deserializer will find an parameter called Items and will correctly deserialize it to your wrapper class.

Here is a simple version of your code so you can better understand what Im talking. You can copy and past it in your unity and it should works properly.

public class JSONTest : MonoBehaviour
{
    private string jsonStr = "[{\"playerName\": \"Eduardito\", \"playerScore\": \"4\"}, {\"playerName\": \"Joel\", \"playerScore\": \"4\"}]";

    [Serializable]
    public class JSONArray<T>
    {
        public T[] Items;
    }

    [Serializable]
    public class User
    {
        public string playerName;
        public string playerScore;
    }

    void Start()
    {
        JSONArray<User> users = JsonUtility.FromJson<JSONArray<User>>("{\"Items\":" + jsonStr + "}");
        if (users.Items != null && users.Items.Length > 0)
        {
            foreach (User user in users.Items)
            {
                Debug.Log("Deserialized user " + user.playerName);
            }
        }
        else
        {
            Debug.Log("I should never reach this code.");
        }
    }
}


来源: stackexchange

问:
Referencing class variable in class method Javascript
I'm defining a class in Javascript meant to serve as an audioplayer compatible with iOS. I'm just getting started with the basics, and running into an issue when trying to access a class method.

After creating an instance of the class (var audio = new WebAudio('soundfile.mp3', document.querySelector(#sound_div)), and attempting to access the method audio.playSound(), I'm getting:

ReferenceError: Can't find variable: elem on line 29

```<code>class WebAudio {

    constructor(soundFile, elem) {
        this.soundFile = soundFile;
        this.elem = elem;
    }

    context() {
        var AudioContext = window.AudioContext || window.webkitAudioContext;
        var context = new AudioContext();
        return context;
    }

    webAudioTouchUnlock(context) {
       return new Promise(function (resolve, reject) {
       //if AudioContext is suspended, and window has been interacted with
           if (context.state === 'suspended' && 'ontouchstart' in window) {
           console.log(context.state);
           var unlock = function() {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(function() {
                   console.log("context resumed");
                   this.elem.removeEventListener('touchstart', unlock);
                   this.elem.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                   reject(reason);
               });
           };
           this.elem.addEventListener('touchstart', unlock, false); //error
           this.elem.addEventListener('touchend', unlock, false);
           } else {
               console.log('context not suspended? Context is ' + context.state);
               resolve(false);
           }
       });
    }

    playSound() {
        this.webAudioTouchUnlock(this.context()).then(function (unlocked) {
            if(unlocked) {
                console.log('playing audio file');
                var audio = new Audio('sound/' + soundFile);
                if (!audio.playing) {
                    audio.play();
                } else {
                    audio.pause();
                }
            }
        }, function(reason) {
            console.error(reason);
        });
        document.body.addEventListener('load', playSound(soundFile));
    }
}
</code>```

答:
You lose the binding to this when you pass the function to an event listener:

```<code>var unlock = function() {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(function() {
                   console.log("context resumed");
                   // this won't point to the instance when called by listener
                   this.elem.removeEventListener('touchstart', unlock);
                   this.elem.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                   reject(reason);
               });
           };
           this.elem.addEventListener('touchstart', unlock, false); //error
</code>```

Arrow functions or manually calling bind(this) can fix it. The arrow function will bind this in the function lexically, which means this will be the this value from where it was defined rather than how it is called:

```<code>var unlock = () => {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(() => {
                   console.log("context resumed");
                   this.elem.removeEventListener('touchstart', unlock);
                   this.elem.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                   reject(reason);
               });
           };
           this.elem.addEventListener('touchstart', unlock, false); //error
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm defining a class in Javascript meant to serve as an audioplayer compatible with iOS. I'm just getting started with the basics, and running into an issue when trying to access a class method.

After creating an instance of the class (var audio = new WebAudio('soundfile.mp3', document.querySelector(#sound_div)), and attempting to access the method audio.playSound(), I'm getting:

ReferenceError: Can't find variable: elem on line 29

class WebAudio {

    constructor(soundFile, elem) {
        this.soundFile = soundFile;
        this.elem = elem;
    }

    context() {
        var AudioContext = window.AudioContext || window.webkitAudioContext;
        var context = new AudioContext();
        return context;
    }

    webAudioTouchUnlock(context) {
       return new Promise(function (resolve, reject) {
       //if AudioContext is suspended, and window has been interacted with
           if (context.state === 'suspended' && 'ontouchstart' in window) {
           console.log(context.state);
           var unlock = function() {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(function() {
                   console.log("context resumed");
                   this.elem.removeEventListener('touchstart', unlock);
                   this.elem.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                   reject(reason);
               });
           };
           this.elem.addEventListener('touchstart', unlock, false); //error
           this.elem.addEventListener('touchend', unlock, false);
           } else {
               console.log('context not suspended? Context is ' + context.state);
               resolve(false);
           }
       });
    }

    playSound() {
        this.webAudioTouchUnlock(this.context()).then(function (unlocked) {
            if(unlocked) {
                console.log('playing audio file');
                var audio = new Audio('sound/' + soundFile);
                if (!audio.playing) {
                    audio.play();
                } else {
                    audio.pause();
                }
            }
        }, function(reason) {
            console.error(reason);
        });
        document.body.addEventListener('load', playSound(soundFile));
    }
}

Body:
You lose the binding to this when you pass the function to an event listener:

var unlock = function() {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(function() {
                   console.log("context resumed");
                   // this won't point to the instance when called by listener
                   this.elem.removeEventListener('touchstart', unlock);
                   this.elem.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                   reject(reason);
               });
           };
           this.elem.addEventListener('touchstart', unlock, false); //error

Arrow functions or manually calling bind(this) can fix it. The arrow function will bind this in the function lexically, which means this will be the this value from where it was defined rather than how it is called:

var unlock = () => {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(() => {
                   console.log("context resumed");
                   this.elem.removeEventListener('touchstart', unlock);
                   this.elem.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                   reject(reason);
               });
           };
           this.elem.addEventListener('touchstart', unlock, false); //error


问:
Python SQLite database not growing
I'm trying to fill in a SQLite database using the Python library sqlite3. In this example, the idea is simply to read data from a file and populate the database, however, although it seems the table is being created, the database is not growing and values are not written to it.

The code I have is below:

```<code>import sqlite3

def update_db(c, key, val):
    sql = ''' UPDATE atable SET f1 = ? WHERE id = ?; '''
    c.execute(sql, (val, key))

def create_table(c):
    sql = ''' CREATE TABLE atable (id text PRIMARY KEY, f1 integer DEFAULT 0); '''
    c.execute(sql)

with sqlite3.connect('test.db') as conn:
    c = conn.cursor()
    create_table(c)

    with open('file1.txt') as f1:
        for line in f1:
            l = line.strip().split()
            update_db(c, l[0], int(l[1]))

    conn.commit()
</code>```

This code runs without errors, but when trying to query this database, either with Python:

```<code>with sqlite3.connect('test.db') as conn:
    c = conn.cursor()
    c.execute('SELECT * FROM atable;')
    for row in c:
        print(row)
</code>```

or in the SQLite command interface:

```<code>$ sqlite3 test.db
SQLite version 3.8.10.2 2015-05-20 18:17:19
Enter ".help" for usage hints.
sqlite> SELECT * FROM atable;
sqlite> .tables
atable
sqlite>
</code>```

the output is always empty (but it looks the table was correctly create). What am I doing wrong here?

The 'file1.txt' for testing is this:

```<code>foo 2
bar 0
baz 1
</code>```

答:
The SQL syntax for adding rows to your table is:

INSERT INTO atable (id, f1) VALUES (?, ?);
```

UPDATE will do nothing if there are not already rows in the table.

If you want to insert or replace an existing row, sqlite also supports an INSERT OR REPLACE command.

Title: Python SQLite database not growing

Body:
I'm trying to fill in a SQLite database using the Python library sqlite3. In this example, the idea is simply to read data from a file and populate the database, however, although it seems the table is being created, the database is not growing and values are not written to it.

The code I have is below:

import sqlite3

def update_db(c, key, val):
    sql = ''' UPDATE atable SET f1 = ? WHERE id = ?; '''
    c.execute(sql, (val, key))

def create_table(c):
    sql = ''' CREATE TABLE atable (id text PRIMARY KEY, f1 integer DEFAULT 0); '''
    c.execute(sql)

with sqlite3.connect('test.db') as conn:
    c = conn.cursor()
    create_table(c)

    with open('file1.txt') as f1:
        for line in f1:
            l = line.strip().split()
            update_db(c, l[0], int(l[1]))

    conn.commit()

This code runs without errors, but when trying to query this database, either with Python:

with sqlite3.connect('test.db') as conn:
    c = conn.cursor()
    c.execute('SELECT * FROM atable;')
    for row in c:
        print(row)

or in the SQLite command interface:

$ sqlite3 test.db
SQLite version 3.8.10.2 2015-05-20 18:17:19
Enter ".help" for usage hints.
sqlite> SELECT * FROM atable;
sqlite> .tables
atable
sqlite>

the output is always empty (but it looks the table was correctly create). What am I doing wrong here?

The 'file1.txt' for testing is this:

foo 2
bar 0
baz 1

Body:
The SQL syntax for adding rows to your table is:

INSERT INTO atable (id, f1) VALUES (?, ?);

UPDATE will do nothing if there are not already rows in the table.

If you want to insert or replace an existing row, sqlite also supports an INSERT OR REPLACE command.


问:
Discord - Chat to a bot on another server
Basically there is a server with a BOT, i want to make my BOT from my server send a PM to the other BOT, the other BOT is not on my server, is this possible?</p>

答:
This is not possible for two main reasons.

It's explicitly blocked by Discord. You'd get the following error:

The server responded with error 50007: Cannot send messages to this user

Bots can only send a PM to a user if they share a server with the user. So while the other bot does not need to be in your server, your bot will need to be in at least one server with the other bot.

Of course, point 1 makes this a moot point anyway


问:
Using lodash to check whether an array has duplicate values
What do you all think would be the best (best can be interpreted as most readable or most performant, your choice) way to write a function using the lodash utilities in order to check an array for duplicate values.

I want to input ['foo', 'foo', 'bar'] and have the function return true. And input ['foo', 'bar', 'baz'] and have the function return false.

答:
As of ES6 you can simply use Set so this becomes:

let hasDuplicates = arr => new Set(arr).size != arr.length

console.log(hasDuplicates([5,3,2,1,2,1,2,1]))
console.log(hasDuplicates([1,2,3,4,5]))```

Which somewhat negates the use of lodash in this particular case.

ContentLicense: CC BY-SA 3.0

Body:
As of ES6 you can simply use Set so this becomes:

let hasDuplicates = arr => new Set(arr).size != arr.length

console.log(hasDuplicates([5,3,2,1,2,1,2,1]))
console.log(hasDuplicates([1,2,3,4,5]))

Which somewhat negates the use of lodash in this particular case.


问:
Cannot Add Admin User
I've been following the steps listed in https://docs.apostrophecms.org/apostrophe/tutorials/getting-started/creating-your-first-project to set up a new project, but have run into an issue. When I try to run

```<code>node app apostrophe-users:add admin admin
</code>```

I get back:

```<code>That group does not exist.
</code>```

With no other warnings or errors. I'm not sure why the admin group doesn't exist, or how to go about creating it. This is using a fresh database. Am I missing a step somewhere?

答:
The group does not exist because, unlike the apostrophe-boilerplate project, your project does not have a groups option configured for the apostrophe-users module. Perhaps you removed it, or perhaps you started from scratch and did not directly use apostrophe-boilerplate.

In this situation, apostrophe does not force any hardcoded groups on you, and instead lets you manually create them via "Groups" in the admin bar.

This is great but there is a chicken and egg problem getting started as you have seen.

The solution to that is to create the group first:

```<code>node app apostrophe-groups:add admin admin
</code>```

This creates a group called admin with the admin permission, which allows members to do anything.

Then you can add an admin user:

```<code>node app apostrophe-users:add admin admin
</code>```

Again though, this is only necessary because you either did not use apostrophe-boilerplate at all, or opted to remove the groups option from apostrophe-users. Which is fine - many sites require that administrators be able to create new groups on the fly, although simpler sites usually don't, which is why we provide an option to lock down just a few instead.

Title: Cannot Add Admin User

Body:
I've been following the steps listed in https://docs.apostrophecms.org/apostrophe/tutorials/getting-started/creating-your-first-project to set up a new project, but have run into an issue. When I try to run

node app apostrophe-users:add admin admin

I get back:

That group does not exist.

With no other warnings or errors. I'm not sure why the admin group doesn't exist, or how to go about creating it. This is using a fresh database. Am I missing a step somewhere?

Body:
The group does not exist because, unlike the apostrophe-boilerplate project, your project does not have a groups option configured for the apostrophe-users module. Perhaps you removed it, or perhaps you started from scratch and did not directly use apostrophe-boilerplate.

In this situation, apostrophe does not force any hardcoded groups on you, and instead lets you manually create them via "Groups" in the admin bar.

This is great but there is a chicken and egg problem getting started as you have seen.

The solution to that is to create the group first:

node app apostrophe-groups:add admin admin

This creates a group called admin with the admin permission, which allows members to do anything.

Then you can add an admin user:

node app apostrophe-users:add admin admin

Again though, this is only necessary because you either did not use apostrophe-boilerplate at all, or opted to remove the groups option from apostrophe-users. Which is fine - many sites require that administrators be able to create new groups on the fly, although simpler sites usually don't, which is why we provide an option to lock down just a few instead.


问:
Java Apache Spark flatMaps & Data Wrangling
I have to pivot the data in a file and then store it in another file. I am having some difficulty pivoting the data.

I have multiple files, that contain data which looks somewhat like I show below. The columns are variable lengths. I am trying to merge the files, first. But for some reason, the output is not correct. I haven't even tried the pivot method, but am not sure how to use it either.

How can this be achieved?

```<code>File 1:
0,26,27,30,120
201008,100,1000,10,400
201009,200,2000,20,500
201010,300,3000,30,600

File 2:
0,26,27,30,120,145
201008,100,1000,10,400,200
201009,200,2000,20,500,100
201010,300,3000,30,600,150

File 3:
0,26,27,120,145
201008,100,10,400,200
201009,200,20,500,100
201010,300,30,600,150

Output:
201008,26,100
201008,27,1000
201008,30,10
201008,120,400
201008,145,200
201009,26,200
201009,27,2000
201009,30,20
201009,120,500
201009,145,100
.....
</code>```

I am not quite familiar with Spark, but am trying to use flatMap and flatMapValues. I am not sure how I can use it for now, but would appreciate some guidance.

```<code>
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.sql.SparkSession;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExecutionTest {
    public static void main(String[] args) {
        Logger.getLogger("org.apache").setLevel(Level.WARN);
        Logger.getLogger("org.spark_project").setLevel(Level.WARN);
        Logger.getLogger("io.netty").setLevel(Level.WARN);
        log.info("Starting...");
        // Step 1: Create a SparkContext.
        boolean isRunLocally = Boolean.valueOf(args[0]);
        String filePath = args[1];

        SparkConf conf = new SparkConf().setAppName("Variable File").set("serializer",
                "org.apache.spark.serializer.KryoSerializer");
        if (isRunLocally) {
            log.info("System is running in local mode");
            conf.setMaster("local[*]").set("spark.executor.memory", "2g");
        }

        SparkSession session = SparkSession.builder().config(conf).getOrCreate();

        JavaSparkContext jsc = new JavaSparkContext(session.sparkContext());
        jsc.textFile(filePath, 2)
           .map(new Function<String, String[]>() {
                private static final long serialVersionUID = 1L;
                @Override
                public String[] call(String v1) throws Exception {
                    return StringUtils.split(v1, ",");
                }
            })
            .foreach(new VoidFunction<String[]>() {
                private static final long serialVersionUID = 1L;
                @Override
                public void call(String[] t) throws Exception {
                    for (String string : t) {
                        log.info(string);
                    }
                }

            });
    }

}

</code>```

答:
Solution in Scala as I am not a JAVA person, you should be able to adapt. And add sorting, cache, etc.

Data is as follows, 3 files with duplicate entry evident, get rid of that if you do not want.

```<code>      0, 5,10, 15  20
 202008, 5,10, 15, 20
 202009,10,20,100,200
</code>```

8 rows generated above.

```<code>      0,888,999
 202008,  5, 10
 202009, 10, 20
</code>```

4 rows generated above.

```<code>     0, 5
202009,10
</code>```

1 row, which is a duplicate.

```<code>// Bit lazy with columns names, but anyway.

import org.apache.spark.sql.functions.input_file_name
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._
import spark.implicits._

val inputPath: String = "/FileStore/tables/g*.txt"
val rdd = spark.read.text(inputPath)
  .select(input_file_name, $"value")
  .as[(String, String)]
  .rdd

val rdd2 = rdd.zipWithIndex
val rdd3 = rdd2.map(x => (x._1._1, x._2, x._1._2.split(",").toList.map(_.toInt)))
val rdd4 = rdd3.map { case (pfx, pfx2, list) => (pfx,pfx2,list.zipWithIndex) }
val df = rdd4.toDF()
df.show(false)
df.printSchema()

val df2 = df.withColumn("rankF", row_number().over(Window.partitionBy($"_1").orderBy($"_2".asc)))
df2.show(false)
df2.printSchema()

val df3 = df2.withColumn("elements", explode($"_3"))
df3.show(false)
df3.printSchema()

val df4 = df3.select($"_1", $"rankF", $"elements".getField("_1"), $"elements".getField("_2")).toDF("fn", "line_num", "val", "col_pos")
df4.show(false)
df4.printSchema()

df4.createOrReplaceTempView("df4temp")

val df51 = spark.sql("""SELECT hdr.fn, hdr.line_num, hdr.val AS pfx, hdr.col_pos
                          FROM df4temp hdr
                         WHERE hdr.line_num <> 1
                           AND hdr.col_pos = 0
                     """)
df51.show(100,false)

val df52 = spark.sql("""SELECT t1.fn, t1.val AS val1, t1.col_pos, t2.line_num, t2.val AS val2
                          FROM df4temp t1, df4temp t2
                         WHERE t1.col_pos  <> 0
                           AND t1.col_pos  = t2.col_pos
                           AND t1.line_num <> t2.line_num
                           AND t1.line_num = 1
                           AND t1.fn       = t2.fn
                     """)
df52.show(100,false)

df51.createOrReplaceTempView("df51temp")
df52.createOrReplaceTempView("df52temp")

val df53 = spark.sql("""SELECT DISTINCT t1.pfx, t2.val1, t2.val2
                          FROM df51temp t1, df52temp t2
                         WHERE t1.fn = t2.fn
                           AND t1.line_num = t2.line_num
                     """)
df53.show(false)
</code>```

returns:

```<code>+------+----+----+
|pfx   |val1|val2|
+------+----+----+
|202008|888 |5   |
|202009|999 |20  |
|202009|20  |200 |
|202008|5   |5   |
|202008|10  |10  |
|202009|888 |10  |
|202008|15  |15  |
|202009|5   |10  |
|202009|10  |20  |
|202009|15  |100 |
|202008|20  |20  |
|202008|999 |10  |
+------+----+----+
</code>```

What we see is Data Wrangling requiring massaged data for tempview creations and JOINing with SQL appropriately.

The key here is to know how to massage the data to make things easy. Note no groupBy etc. Per file, with varying length stuff, JOINing not attempted in RDD, too inflexible. Rank shows line#, so you know the first line with the 0 business.

This is what we call Data Wrangling. This is what we also call hard work for a few points on SO. This is one of my best efforts, and also one of the last of such efforts.

Weakness of solution is a lot of work to get 1st record of a file, there are alternatives. https://www.cyberciti.biz/faq/unix-linux-display-first-line-of-file/ preprocesing is what I would realistically consider.

Body:
I have to pivot the data in a file and then store it in another file. I am having some difficulty pivoting the data.

I have multiple files, that contain data which looks somewhat like I show below. The columns are variable lengths. I am trying to merge the files, first. But for some reason, the output is not correct. I haven't even tried the pivot method, but am not sure how to use it either.

How can this be achieved?

File 1:
0,26,27,30,120
201008,100,1000,10,400
201009,200,2000,20,500
201010,300,3000,30,600

File 2:
0,26,27,30,120,145
201008,100,1000,10,400,200
201009,200,2000,20,500,100
201010,300,3000,30,600,150

File 3:
0,26,27,120,145
201008,100,10,400,200
201009,200,20,500,100
201010,300,30,600,150

Output:
201008,26,100
201008,27,1000
201008,30,10
201008,120,400
201008,145,200
201009,26,200
201009,27,2000
201009,30,20
201009,120,500
201009,145,100
.....

I am not quite familiar with Spark, but am trying to use flatMap and flatMapValues. I am not sure how I can use it for now, but would appreciate some guidance.

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.sql.SparkSession;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExecutionTest {
    public static void main(String[] args) {
        Logger.getLogger("org.apache").setLevel(Level.WARN);
        Logger.getLogger("org.spark_project").setLevel(Level.WARN);
        Logger.getLogger("io.netty").setLevel(Level.WARN);
        log.info("Starting...");
        // Step 1: Create a SparkContext.
        boolean isRunLocally = Boolean.valueOf(args[0]);
        String filePath = args[1];

        SparkConf conf = new SparkConf().setAppName("Variable File").set("serializer",
                "org.apache.spark.serializer.KryoSerializer");
        if (isRunLocally) {
            log.info("System is running in local mode");
            conf.setMaster("local[*]").set("spark.executor.memory", "2g");
        }

        SparkSession session = SparkSession.builder().config(conf).getOrCreate();

        JavaSparkContext jsc = new JavaSparkContext(session.sparkContext());
        jsc.textFile(filePath, 2)
           .map(new Function<String, String[]>() {
                private static final long serialVersionUID = 1L;
                @Override
                public String[] call(String v1) throws Exception {
                    return StringUtils.split(v1, ",");
                }
            })
            .foreach(new VoidFunction<String[]>() {
                private static final long serialVersionUID = 1L;
                @Override
                public void call(String[] t) throws Exception {
                    for (String string : t) {
                        log.info(string);
                    }
                }

            });
    }

}

Body:
Solution in Scala as I am not a JAVA person, you should be able to adapt. And add sorting, cache, etc.

Data is as follows, 3 files with duplicate entry evident, get rid of that if you do not want.

      0, 5,10, 15  20
 202008, 5,10, 15, 20
 202009,10,20,100,200

8 rows generated above.

      0,888,999
 202008,  5, 10
 202009, 10, 20

4 rows generated above.

     0, 5
202009,10

1 row, which is a duplicate.

// Bit lazy with columns names, but anyway.

import org.apache.spark.sql.functions.input_file_name
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._
import spark.implicits._

val inputPath: String = "/FileStore/tables/g*.txt"
val rdd = spark.read.text(inputPath)
  .select(input_file_name, $"value")
  .as[(String, String)]
  .rdd

val rdd2 = rdd.zipWithIndex
val rdd3 = rdd2.map(x => (x._1._1, x._2, x._1._2.split(",").toList.map(_.toInt)))
val rdd4 = rdd3.map { case (pfx, pfx2, list) => (pfx,pfx2,list.zipWithIndex) }
val df = rdd4.toDF()
df.show(false)
df.printSchema()

val df2 = df.withColumn("rankF", row_number().over(Window.partitionBy($"_1").orderBy($"_2".asc)))
df2.show(false)
df2.printSchema()

val df3 = df2.withColumn("elements", explode($"_3"))
df3.show(false)
df3.printSchema()

val df4 = df3.select($"_1", $"rankF", $"elements".getField("_1"), $"elements".getField("_2")).toDF("fn", "line_num", "val", "col_pos")
df4.show(false)
df4.printSchema()

df4.createOrReplaceTempView("df4temp")

val df51 = spark.sql("""SELECT hdr.fn, hdr.line_num, hdr.val AS pfx, hdr.col_pos
                          FROM df4temp hdr
                         WHERE hdr.line_num <> 1
                           AND hdr.col_pos = 0
                     """)
df51.show(100,false)

val df52 = spark.sql("""SELECT t1.fn, t1.val AS val1, t1.col_pos, t2.line_num, t2.val AS val2
                          FROM df4temp t1, df4temp t2
                         WHERE t1.col_pos  <> 0
                           AND t1.col_pos  = t2.col_pos
                           AND t1.line_num <> t2.line_num
                           AND t1.line_num = 1
                           AND t1.fn       = t2.fn
                     """)
df52.show(100,false)

df51.createOrReplaceTempView("df51temp")
df52.createOrReplaceTempView("df52temp")

val df53 = spark.sql("""SELECT DISTINCT t1.pfx, t2.val1, t2.val2
                          FROM df51temp t1, df52temp t2
                         WHERE t1.fn = t2.fn
                           AND t1.line_num = t2.line_num
                     """)
df53.show(false)

returns:

+------+----+----+
|pfx   |val1|val2|
+------+----+----+
|202008|888 |5   |
|202009|999 |20  |
|202009|20  |200 |
|202008|5   |5   |
|202008|10  |10  |
|202009|888 |10  |
|202008|15  |15  |
|202009|5   |10  |
|202009|10  |20  |
|202009|15  |100 |
|202008|20  |20  |
|202008|999 |10  |
+------+----+----+

What we see is Data Wrangling requiring massaged data for tempview creations and JOINing with SQL appropriately.

The key here is to know how to massage the data to make things easy. Note no groupBy etc. Per file, with varying length stuff, JOINing not attempted in RDD, too inflexible. Rank shows line#, so you know the first line with the 0 business.

This is what we call Data Wrangling. This is what we also call hard work for a few points on SO. This is one of my best efforts, and also one of the last of such efforts.

Weakness of solution is a lot of work to get 1st record of a file, there are alternatives. https://www.cyberciti.biz/faq/unix-linux-display-first-line-of-file/ preprocesing is what I would realistically consider.


问:
How can I solve this problem of installation xampp on fedora?
When I run xampp on fedora this error is showing up on application log

Starting Apache Web Server...
Exit code: 8
Stdout:
apache config test fails, aborting
Stderr:
httpd: Syntax error on line 522 of /opt/lampp/etc/httpd.conf: Syntax error on line 10 of /opt/lampp/etc/extra/httpd-xampp.conf: Cannot load modules/libphp7.so into server: libnsl.so.1: cannot open shared object file: No such file or directory

can anyone tell me how can I solve this?

答:
it seems you're missing libnsl. install it through this command:

sudo dnf install libnsl
```
<p>In case this doesn't work you can then download it manually:</p>
<ol>
<li><p>Visit https://pkgs.org/</p>
</li>
<li><p>In the search box (pkgs.org of course) type libnsl.so.1 and choose the appropriate OS. The version shown might be higher e.g libnsl-2.28-9.fc29.x86_64.rpm, but it doesn't matter, the file needed is also included in this very package.</p>
</li>
<li><p>In the terminal, navigate to the directory where the .rpm was downloaded.</p>
</li>
<li><p>Type the following command to install it:</p>
<pre class="lang-none prettyprint-override"><code>sudo rpm libnsl-2.XX-X.fc29.x86_64.rpm
</code>```

Upon completion everything should be working fine.

Body:
it seems you're missing libnsl. install it through this command:

sudo dnf install libnsl

In case this doesn't work you can then download it manually:

Visit https://pkgs.org/

In the search box (pkgs.org of course) type libnsl.so.1 and choose the appropriate OS. The version shown might be higher e.g libnsl-2.28-9.fc29.x86_64.rpm, but it doesn't matter, the file needed is also included in this very package.

In the terminal, navigate to the directory where the .rpm was downloaded.

Type the following command to install it:

sudo rpm libnsl-2.XX-X.fc29.x86_64.rpm

Upon completion everything should be working fine.


问:
Impossible to initialize choromecast web api in google chrome
I am trying to implement chromecast in a video player but I can't initialize the chromecast API and I can't understand why.

This is the code that I am using taken from the google official page.

```<code>window['__onGCastApiAvailable'] = function(isAvailable) {
 if (isAvailable) {
   initializeCastApi();
 }
</code>```

};

The isAvailable parameter is always false so the cast api is not loaded even if the callback to the __onGCastApiAvailable is firing.

I tried on a setInterval to check if chrome.cast is loaded but it is always undefined.

```<code>setInterval(function(){
    console.log(chrome.cast); // it is always undefined
}, 1000);
</code>```

Do I need to install something in Chrome, I do have the cast button in the menu and I can cast fine the browser.

Any help is much appreciated.

Thank you.

答: window['__onGCastApiAvailable'] is only trigged if the sender app (your webpage) is hosted with https. If you are trying this with http, it will silently fail and chrome.cast will be undefined.</p>

Body:
I am trying to implement chromecast in a video player but I can't initialize the chromecast API and I can't understand why.

This is the code that I am using taken from the google official page.

window['__onGCastApiAvailable'] = function(isAvailable) {
 if (isAvailable) {
   initializeCastApi();
 }

};

The isAvailable parameter is always false so the cast api is not loaded even if the callback to the __onGCastApiAvailable is firing.

I tried on a setInterval to check if chrome.cast is loaded but it is always undefined.

setInterval(function(){
    console.log(chrome.cast); // it is always undefined
}, 1000);

Do I need to install something in Chrome, I do have the cast button in the menu and I can cast fine the browser.

Any help is much appreciated.

Thank you.


问:
Generic type 'Result' specialized with too many type parameters (got 2, but expected 1)

how would I solve this error and it only appears when I import Almofire.

答:
It's Swift.Result<T, Error>, not Swift.Result<T1, T2>. If you want to pass two values, use a tuple, i.e. Swift.Result<([Character], Data), Error> (the tuple can be auto-expanded in a switch/case handling of the result)

Also, Alamofire defines it's own Result<T> type. You should prefix it with Swift. if you want to use the Swift 5 type.


问:
Stretching images when using as background image
I was trying to set an image as background image for my django application. But when i set it, it is getting displayed as tiled image. ie without actually stretching the image, same image is tiled and shown 4 times. Can somebody tell me how to stretch the image and set it as a background image. I will paste my code here. I am sure some attribute must be there setting this, which i couldnt find on googling.</p>

```<code><body bgcolor=" #408080" background="/static/paper.jpg" background-size: 100%; >
</code>```

答:
You need to apply this as a style, not as an attribute. That will work if your browser supports CSS 3:

```<code>style="background: url(/static/paper.jpg); background-size: 100%;"
</code>```

Some background info:

http://css-tricks.com/perfect-full-page-background-image/

http://css-tricks.com/how-to-resizeable-background-image/

Body:
You need to apply this as a style, not as an attribute. That will work if your browser supports CSS 3:

style="background: url(/static/paper.jpg); background-size: 100%;"

Some background info:

http://css-tricks.com/perfect-full-page-background-image/

http://css-tricks.com/how-to-resizeable-background-image/


问:
Lock Google Sheet tab based on date+time
I have a Google worksheet with a specific sheet I'd like to protect from editing based on date and time. I saw code for doing this for specific cell(s), but I want to do it for the entire sheet and to keep the list of editors (just protect from public editing).

I've tried to use some code I found here: Locking cells in Google Sheets at a specific time but not sure how to modify this code for my use case.

EDIT:

Looking closer at this page: https://developers.google.com/apps-script/reference/spreadsheet/protection it appears the following code would help:

```<code>// Protect range A1:B10, then remove all other users from the list of editors.

var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect().setDescription('Sample protected  range');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}
</code>```

However, how do I declare the specific sheet name? I have multiple tabs in my spreadsheet. What is getActive going to pull?

答:
However, how do I declare the specific sheet name? I have multiple tabs in my spreadsheet. What is getActive going to pull?

SpreadsheetApp.getActive() returns a Spreadsheet object representing the spreadsheet that holds the code it the script is a bounded script or the spreadsheet that called a function the add-on that holds the script.

Use getSheetByName(name) to get a Sheet object by it's name.

Body:
I have a Google worksheet with a specific sheet I'd like to protect from editing based on date and time. I saw code for doing this for specific cell(s), but I want to do it for the entire sheet and to keep the list of editors (just protect from public editing).

I've tried to use some code I found here: Locking cells in Google Sheets at a specific time but not sure how to modify this code for my use case.

EDIT:

Looking closer at this page: https://developers.google.com/apps-script/reference/spreadsheet/protection it appears the following code would help:

// Protect range A1:B10, then remove all other users from the list of editors.

var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect().setDescription('Sample protected  range');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

However, how do I declare the specific sheet name? I have multiple tabs in my spreadsheet. What is getActive going to pull?


问:
Unable to kick out some unwanted values from a spreadsheet
I've written a script in vba to clear any cell containing #NAME?. However, every time I run my following macro I get this cel.value=Error 2029.

I've tried with:

```<code>Sub ClearUnwantedRange()
    Dim cel As Range

    For Each cel In ActiveSheet.UsedRange.CurrentRegion
        If InStr(cel, "#")  > 0 Then
            Debug.Print cel.Address
            cel.ClearContents
        End If
    Next cel
End Sub
</code>```

I even tried with If InStr(cel, "#NAME?") > 0 Then but no luck.

How can I kick those unwanted values out?

答:
Try this ...

```<code>If IsError(cel) Then
</code>```

... instead of ...

```<code>If InStr(cel, "#")  > 0 Then
</code>```

Body:
I've written a script in vba to clear any cell containing #NAME?. However, every time I run my following macro I get this cel.value=Error 2029.

I've tried with:

Sub ClearUnwantedRange()
    Dim cel As Range

    For Each cel In ActiveSheet.UsedRange.CurrentRegion
        If InStr(cel, "#")  > 0 Then
            Debug.Print cel.Address
            cel.ClearContents
        End If
    Next cel
End Sub

I even tried with If InStr(cel, "#NAME?") > 0 Then but no luck.

How can I kick those unwanted values out?

Body:
Try this ...

If IsError(cel) Then

... instead of ...

If InStr(cel, "#")  > 0 Then


问:
Extract Character from Filename with RegEx in Excel VBA
My strings are filenames like this:

Filename 1 (A12 V1.1)

Filename 1 (V2) Text (A9 V2.3 8.99)

Filename V2 Text (A34 8.3 V4)

How do I extract only the numbers which start with the 'V', contained within the last brackets only, and excluding the 'V'?

i.e. - 1.1, 2.3, 4

The following Regex UDF was provided by YasserKhalil (Previous Post Here)

However, the UDF is returning on filenames like:

IPV32_20.dll which returns V32-20

IMV1.dll which returns V1.

These filenames do not contain brackets, so they should not be returning anything.

How to modify this UDF?

答:
EDII
   Based on a comment, it seems the OP wants to return only digits and dots after the V, so we change the regex to provide that below.

The following seems to return what you describe:

```<code>Option Explicit
Function vNum(s As String) As String
    Dim re As Object
Set re = CreateObject("vbscript.regexp")
With re
    .Pattern = "\(.*V([\d.]+)(?=.*\))"
' Regex above changed from original to return only digits and dots that immediately follow the V "\(.*V(\S+)(?=.*\))"
    If .test(s) = True Then
        vNum = .Execute(s)(0).submatches(0)
    End If
End With

End Function
</code>```

And here is a description of the regex in detail:

Note that since your description specified "string" and not numbers, that is what this might return.  If you need to restrict it to digits and decimal, that is a simple change

extract the string starting with but excluding the 'V', contained within the last brackets

```<code>\(.*V(\S+)(?=.*\))
</code>```

Options: Case sensitive; ^$ don’t match at line breaks

Match the opening parenthesis character \(

Match any single character that is NOT a line break character (line feed) .*

Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *

Match the character “V” literally (case sensitive) V

Match the regex below and capture its match into backreference number 1 (\S+)

Match a single character that is NOT a “whitespace character” (ASCII space, tab, line feed, carriage return, vertical tab, form feed) \S+

Between one and unlimited times, as many times as possible, giving back as needed (greedy) +

Assert that the regex below can be matched starting at this position (positive lookahead) (?=.*\))

Match any single character that is NOT a line break character (line feed) .*

Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *

Match the closing parenthesis character \)

Created with RegexBuddy

Body:
EDII
   Based on a comment, it seems the OP wants to return only digits and dots after the V, so we change the regex to provide that below.

The following seems to return what you describe:

Option Explicit
Function vNum(s As String) As String
    Dim re As Object
Set re = CreateObject("vbscript.regexp")
With re
    .Pattern = "\(.*V([\d.]+)(?=.*\))"
' Regex above changed from original to return only digits and dots that immediately follow the V "\(.*V(\S+)(?=.*\))"
    If .test(s) = True Then
        vNum = .Execute(s)(0).submatches(0)
    End If
End With

End Function

And here is a description of the regex in detail:

Note that since your description specified "string" and not numbers, that is what this might return.  If you need to restrict it to digits and decimal, that is a simple change

extract the string starting with but excluding the 'V', contained within the last brackets

\(.*V(\S+)(?=.*\))

Options: Case sensitive; ^$ don’t match at line breaks

Match the opening parenthesis character \(

Match any single character that is NOT a line break character (line feed) .*

Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *

Match the character “V” literally (case sensitive) V

Match the regex below and capture its match into backreference number 1 (\S+)

Match a single character that is NOT a “whitespace character” (ASCII space, tab, line feed, carriage return, vertical tab, form feed) \S+

Between one and unlimited times, as many times as possible, giving back as needed (greedy) +

Assert that the regex below can be matched starting at this position (positive lookahead) (?=.*\))

Match any single character that is NOT a line break character (line feed) .*

Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *

Match the closing parenthesis character \)

Created with RegexBuddy


问:
Nologging with noappend mode
I want to execute insert statement with nologging.

As I can see, the only way is to use the APPEND hint in the query.

The problem is that the APPEND hint can't work with DML ERROR LOGGING clause.

In my case, I must use that clause.

What is the connection between APPEND (that actually mean to spit all the data in the end of table and not check for blocks "holes") to the (no)logging? How can I apply a nologging with NOAPPEND mode?

I tried to alter-nologging the table, but the REDO is just grow when the statement is with NOAPPEND hint.

I'm using Oracle 11g.

Thank you.

答:
APPEND hints and NOLOGGING options are just different ways to switch between direct-path writes and conventional writes.  The APPEND hints are used in SQL statements, and NOLOGGING is an option for a table or tablespace.

The problem here is that direct-path writes do not work with DML error logging, and as far as I know there is no direct workaround.  There is no magic combination of hints and options to make those features work together.

There are potentially other ways to improve the performance.  For example, the statement can run in parallel but with conventional writes.  Or, if you're only interested in logging the errors for a few specific constraints, you could disable those constraints, perform the change in a direct-path write, enable the constraints and record the constraint exceptions, and then remove the rows that block the constraint.

Title: Nologging with noappend mode


问:
Android studio back goes to splash screen
I have created this simple splash screen ;

```<code>public class Splashscreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splashscreen);
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {

                Intent i = new Intent(Splashscreen.this, MainActivity.class);
                startActivity(i);

                finish(); } }, 1000);
    }

    }
</code>```

I declared the splash screen to be the first screen that opens like this;

```<code>   <activity android:name="com.androidhunger.opendagapp.Splashscreen"
        android:noHistory="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar"><intent-
        filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter></activity>
</code>```

After the splash screen my mainactivity opens a fragment with menu code inside of it, but I don't think the problem lays there. My problem is, when I open my app and the splash screen is done, and i've loaded my first screen, when I press back once, it takes me to a blank page. I can't recreate it here with easely, but I hope someone recognizes the issue.

答:
you need to clear your activity stack before you start new activity </p>

```<code> Intent i = new Intent(Splashscreen.this, MainActivity.class);
 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 startActivity(i);
</code>```

Body:
I have created this simple splash screen ;

public class Splashscreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splashscreen);
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {

                Intent i = new Intent(Splashscreen.this, MainActivity.class);
                startActivity(i);

                finish(); } }, 1000);
    }

    }

I declared the splash screen to be the first screen that opens like this;

   <activity android:name="com.androidhunger.opendagapp.Splashscreen"
        android:noHistory="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar"><intent-
        filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter></activity>

After the splash screen my mainactivity opens a fragment with menu code inside of it, but I don't think the problem lays there. My problem is, when I open my app and the splash screen is done, and i've loaded my first screen, when I press back once, it takes me to a blank page. I can't recreate it here with easely, but I hope someone recognizes the issue.

Body:
you need to clear your activity stack before you start new activity

 Intent i = new Intent(Splashscreen.this, MainActivity.class);
 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 startActivity(i);


问:
How to bind array to arrystore in order to populate combo in extjs
I am having array as

```<code>var cars = new Array('audi','benz','citron','nissan','alto');
</code>```

I want to add this data to arraystore like below

```<code> var myStore = new Ext.data.ArrayStore({
        data   : cars ,
        fields : ['names']
    });
</code>```

On Binding this array store to combo

```<code> var myCombo = new Ext.form.ComboBox({
        store: myStore ,
        displayField: 'name',
        valueField: 'name',
        typeAhead: true,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        emptyText: 'Select a state...',
        selectOnFocus: true,

    });
</code>```

The combo is showing only first letter of each word in the array as a, b, c, n, a

How can I properly disply the combo as the arry i am using is is populated programatically and then binding to arraystore

答:
The format of data the ArrayStore consumes is an array of arrays. Reformatting your store data as follows should allow it to work:

```<code>var cars = [['audi'], ['benz'], ['citron'], ['nissan'], ['alto']];
</code>```

Converting from your format to the required format is simple enough:

```<code>for ( var i = 0, c = cars.length; i < c; i++ ) {
    cars[i] = [cars[i]];
}
</code>```

Body:
I am having array as

var cars = new Array('audi','benz','citron','nissan','alto');

I want to add this data to arraystore like below

 var myStore = new Ext.data.ArrayStore({
        data   : cars ,
        fields : ['names']
    });

On Binding this array store to combo

 var myCombo = new Ext.form.ComboBox({
        store: myStore ,
        displayField: 'name',
        valueField: 'name',
        typeAhead: true,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        emptyText: 'Select a state...',
        selectOnFocus: true,

    });

The combo is showing only first letter of each word in the array as a, b, c, n, a

How can I properly disply the combo as the arry i am using is is populated programatically and then binding to arraystore

Body:
The format of data the ArrayStore consumes is an array of arrays. Reformatting your store data as follows should allow it to work:

var cars = [['audi'], ['benz'], ['citron'], ['nissan'], ['alto']];

Converting from your format to the required format is simple enough:

for ( var i = 0, c = cars.length; i < c; i++ ) {
    cars[i] = [cars[i]];
}


问:
Proper way to use symbols as accessors
What is the right way to wrap a Matrix and access using Symbols?</p>

```<code>S = OhlcSeries{Float64}(100)
lastClose = S[:close, 0]

struct OhlcSeries{T} <: AbstractArray{T,2}
    data::Matrix{T}

    function OhlcSeries{T}(length::Int) where T
        data = Matrix{T}(4, length)
        new{T}(data)
    end
end

# Base.parent(A::OhlcSeries) = A.data
getindex(s::OhlcSeries,sym::Symbol) = getindex(s,Val{sym})
getindex(s::OhlcSeries,::Type{Val{:close}}) = view(s.data, 4, :)

# @inline function getindex(S::InputOhlcSeries, r::Symbol, col::Int)
#     @match r begin
#         :open => S.data[1, col]
#         :high => S.data[2, col]
#         :low  => S.data[3, col]
#         :close  => S.data[4, col]
#         _      => throw(ArgumentError("Expected one of :open, :high, :low, :close"))
#     end
# end

@inline function setindex!(S::InputOhlcSeries, value, r::Symbol, col::Int)
    @match r begin
        :open => S.data[1, col] = value
        :high => S.data[2, col] = value
        :low  => S.data[3, col] = value
        :close  => S.data[4, col] = value
        _      => throw(ArgumentError("Expected one of :open, :high, :low, :close"))
    end
end

@inline Base.getindex(S::OhlcSeries, i::Int, j::Int) = S.data[i, j]
@inline Base.setindex!(S::OhlcSeries, value, i::Int, j::Int) = S.data[i, j] = value
Base.size(S::OhlcSeries) = size(S.data.data)
Base.eltype(::Type{OhlcSeries{T}}) where {T} = T
Base.IndexStyle(::Type{<:OhlcSeries}) = IndexCartesian()
</code>```

答:
If you want your type to be a subtype of AbstratArray you should minimally implement methods specified in the https://docs.julialang.org/en/latest/manual/interfaces/#man-interface-array-1 API specification. In particular you should decide on IndexStyle (looking at your structure IndexLinear should be efficient).

Then you can add custom indexing on top of it. Examples how this can be done are best looked-up in https://github.com/JuliaArrays/AxisArrays.jl package or https://github.com/davidavdav/NamedArrays.jl. I refer you to the sources as the code can get tricky, so it is best to inspect them in full.

If you prefer not to allow to index columns of your data structure by numbers but only by symbols, then this is also fully doable, but this type will not support AbstractArray API, so if you pass it to standard library functions that assume this API is fulfilled you can get errors.

Title: Proper way to use symbols as accessors

Body:
What is the right way to wrap a Matrix and access using Symbols?

S = OhlcSeries{Float64}(100)
lastClose = S[:close, 0]

struct OhlcSeries{T} <: AbstractArray{T,2}
    data::Matrix{T}

    function OhlcSeries{T}(length::Int) where T
        data = Matrix{T}(4, length)
        new{T}(data)
    end
end

# Base.parent(A::OhlcSeries) = A.data
getindex(s::OhlcSeries,sym::Symbol) = getindex(s,Val{sym})
getindex(s::OhlcSeries,::Type{Val{:close}}) = view(s.data, 4, :)

# @inline function getindex(S::InputOhlcSeries, r::Symbol, col::Int)
#     @match r begin
#         :open => S.data[1, col]
#         :high => S.data[2, col]
#         :low  => S.data[3, col]
#         :close  => S.data[4, col]
#         _      => throw(ArgumentError("Expected one of :open, :high, :low, :close"))
#     end
# end

@inline function setindex!(S::InputOhlcSeries, value, r::Symbol, col::Int)
    @match r begin
        :open => S.data[1, col] = value
        :high => S.data[2, col] = value
        :low  => S.data[3, col] = value
        :close  => S.data[4, col] = value
        _      => throw(ArgumentError("Expected one of :open, :high, :low, :close"))
    end
end

@inline Base.getindex(S::OhlcSeries, i::Int, j::Int) = S.data[i, j]
@inline Base.setindex!(S::OhlcSeries, value, i::Int, j::Int) = S.data[i, j] = value
Base.size(S::OhlcSeries) = size(S.data.data)
Base.eltype(::Type{OhlcSeries{T}}) where {T} = T
Base.IndexStyle(::Type{<:OhlcSeries}) = IndexCartesian()


问:
Service Provider not booting in Laravel 5.8
I've created a new service provider to observe a model (App\Providers\EloquentEventServiceProvider.php), like so:

namespace App\Providers;
use Illuminate\Support\ServiceProvider;

use App\Staff;
use App\Oberservers\StaffObserver;

class EloquentEventServiceProvider extends ServiceProvider
{
  public function boot()
  {
    Staff::observe(StaffObserver::class);
  }
}
```

<p>I've also added it to the config file (<code>config\app.php</code>):</p>

<pre class="lang-php prettyprint-override"><code>return [
  ...
  'providers' => [
    ...
    App\Providers\EloquentEventServiceProvider::class,
    ...
  ]
  ...
]
</code>```

The observer methods aren't working though. If I move Staff::observe(StaffObserver::class); to the AppServiceProvider class, it works just fine. So clearly this is an issue with getting my service provider to boot. I've tried php artisan config:clear, php artisan clear-compiled, composer update and composer dump but none have work. Any help is greatly aprpeciated.

答:
your Oberservers name is wrong, as mentioned in the laravel doc observers laravel doc it should be Observers which means all of your observers should be within App\Observers instead of App\Oberservers.

so here we have 2 solutions :

1- if you want to keep the namespace App\Oberservers, you should run these 2 commands below because autoloading of the files may not work properly because we created a new folder Oberservers:

```<code># Autoloading of files
composer dump

# Configure the cache
php artisan config:cache
</code>```

2- the second solution is to just rename your actual Oberservers folder to Observers, in that way the autoloading of files will work well.

Body:
I've created a new service provider to observe a model (App\Providers\EloquentEventServiceProvider.php), like so:

namespace App\Providers;
use Illuminate\Support\ServiceProvider;

use App\Staff;
use App\Oberservers\StaffObserver;

class EloquentEventServiceProvider extends ServiceProvider
{
  public function boot()
  {
    Staff::observe(StaffObserver::class);
  }
}

I've also added it to the config file (config\app.php):

return [
  ...
  'providers' => [
    ...
    App\Providers\EloquentEventServiceProvider::class,
    ...
  ]
  ...
]

The observer methods aren't working though. If I move Staff::observe(StaffObserver::class); to the AppServiceProvider class, it works just fine. So clearly this is an issue with getting my service provider to boot. I've tried php artisan config:clear, php artisan clear-compiled, composer update and composer dump but none have work. Any help is greatly aprpeciated.

Body:
your Oberservers name is wrong, as mentioned in the laravel doc observers laravel doc it should be Observers which means all of your observers should be within App\Observers instead of App\Oberservers.

so here we have 2 solutions :

1- if you want to keep the namespace App\Oberservers, you should run these 2 commands below because autoloading of the files may not work properly because we created a new folder Oberservers:

# Autoloading of files
composer dump

# Configure the cache
php artisan config:cache

2- the second solution is to just rename your actual Oberservers folder to Observers, in that way the autoloading of files will work well.


问:
Reinterpret C# raw buffer into a blittable structure
I'm looking for a way to reinterpret an arbitrary unsafe memory region as a blittable structure in C#. Here is a failed attempt I could write so far:

```<code>[StructLayout(LayoutKind.Explicit, Size = sizeof(int))]
struct Foo
{
    [FieldOffset(0)]
    public int X;
}

public static unsafe void Main()
{
    // Allocate the buffer
    byte* buffer = stackalloc byte[sizeof(Foo)];

    // A tentative of reinterpreting the buffer as the struct
    Foo foo1 = Unsafe.AsRef<Foo>(buffer);

    // Another tentative to reinterpret as the struct
    Foo foo2 = *(Foo*) buffer;

    // Get back the address of the struct
    void* p1 = &foo1;
    void* p2 = &foo2;

    Console.WriteLine(new IntPtr(buffer).ToString("X"));
    Console.WriteLine(new IntPtr(p1).ToString("X"));
    Console.WriteLine(new IntPtr(p2).ToString("X"));
}
</code>```

Nevertheless, the printed memory addresses are all different (I expected the same address to be printed). The first attempt uses the Unsafe.AsRef<T>(..) provided by Microsoft, where the description of method says:

Reinterprets the given location as a reference to a value of type T.

I'm not sure why the reinterpret is not properly done here.

Any advice ?

答:
The reinterpreting works as intended, the reason the addresses are different is that these two lines create independent copies of data in two new variables:

```<code>Foo foo1 = Unsafe.AsRef<Foo>(buffer);
// ...
Foo foo2 = *(Foo*) buffer;
</code>```

To avoid the copying, you can declare the variables as ref locals (from C#7 onwards) or pointers:

```<code>byte* buffer = ...

// Option 1, pointers only
Foo* foo1 = (Foo*)buffer;
foo1->X = 123;

// Option 2, ref local cast from pointer
ref Foo foo2 = ref *(Foo*)buffer;
foo2.X = 456;

// Option 3, ref local with Unsafe.AsRef
// Unlike option 2 this also allows reinterpreting non-blittable types,
// but in most cases that's probably undesirable
ref Foo foo3 = ref Unsafe.AsRef<Foo>(buffer);
foo3.X = 789;
</code>```

Body:
I'm looking for a way to reinterpret an arbitrary unsafe memory region as a blittable structure in C#. Here is a failed attempt I could write so far:

[StructLayout(LayoutKind.Explicit, Size = sizeof(int))]
struct Foo
{
    [FieldOffset(0)]
    public int X;
}

public static unsafe void Main()
{
    // Allocate the buffer
    byte* buffer = stackalloc byte[sizeof(Foo)];

    // A tentative of reinterpreting the buffer as the struct
    Foo foo1 = Unsafe.AsRef<Foo>(buffer);

    // Another tentative to reinterpret as the struct
    Foo foo2 = *(Foo*) buffer;

    // Get back the address of the struct
    void* p1 = &foo1;
    void* p2 = &foo2;

    Console.WriteLine(new IntPtr(buffer).ToString("X"));
    Console.WriteLine(new IntPtr(p1).ToString("X"));
    Console.WriteLine(new IntPtr(p2).ToString("X"));
}

Nevertheless, the printed memory addresses are all different (I expected the same address to be printed). The first attempt uses the Unsafe.AsRef<T>(..) provided by Microsoft, where the description of method says:

Reinterprets the given location as a reference to a value of type T.

I'm not sure why the reinterpret is not properly done here.

Any advice ?

Body:
The reinterpreting works as intended, the reason the addresses are different is that these two lines create independent copies of data in two new variables:

Foo foo1 = Unsafe.AsRef<Foo>(buffer);
// ...
Foo foo2 = *(Foo*) buffer;

To avoid the copying, you can declare the variables as ref locals (from C#7 onwards) or pointers:

byte* buffer = ...

// Option 1, pointers only
Foo* foo1 = (Foo*)buffer;
foo1->X = 123;

// Option 2, ref local cast from pointer
ref Foo foo2 = ref *(Foo*)buffer;
foo2.X = 456;

// Option 3, ref local with Unsafe.AsRef
// Unlike option 2 this also allows reinterpreting non-blittable types,
// but in most cases that's probably undesirable
ref Foo foo3 = ref Unsafe.AsRef<Foo>(buffer);
foo3.X = 789;


问:
How to load a file in Azure Function using PowerShell
I have a small function that takes an array of US telephone area codes and returns an array of area codes paired to the state they are in.

The "master list" of area codes to states is a long variable in my function. I'd like to put that in a CSV file instead.

I'm a beginner to using Azure Functions but, even when the file is in the root folder, Get-Content .\filename.csv does not work.

答:
It's never really a good idea to reference absolute paths as things may change. To use a variable that will always point you to the correct path you can use:

$EXECUTION_CONTEXT_FUNCTIONDIRECTORY which will return the current folder your Azure Functions runs from.

To use this in your question at hand:

```<code>Get-Content -Path "$EXECUTION_CONTEXT_FUNCTIONDIRECTORY\filename.csv"
</code>```

Documentation on this:
https://github.com/Azure/azure-functions-host/wiki/Retrieving-information-about-the-currently-running-function#powershell-php-python-bash-batch-and-other-scripting-languages

Body:
It's never really a good idea to reference absolute paths as things may change. To use a variable that will always point you to the correct path you can use:

$EXECUTION_CONTEXT_FUNCTIONDIRECTORY which will return the current folder your Azure Functions runs from.

To use this in your question at hand:

Get-Content -Path "$EXECUTION_CONTEXT_FUNCTIONDIRECTORY\filename.csv"

Documentation on this:
https://github.com/Azure/azure-functions-host/wiki/Retrieving-information-about-the-currently-running-function#powershell-php-python-bash-batch-and-other-scripting-languages


问:
Return Map object by DAO method
I would like to have method like this in my dao object

```<code>@Query("SELECT c.name, sum(p.value) FROM payments p, paymentCategories c WHERE p.categoryId = c.id GROUP BY c.name")
fun getCategoryStats(): Map<String, Float>
</code>```

but i get the error

error: Not sure how to convert a Cursor to this method's return type
      public abstract java.util.Map

Is it possible to change it to working version?

So it can be different type to return but the main conditions are

It must be only one query in db

I would like to avoid extra code like creating additional data structure only for this method

答:
While I don't think this can be done in the Dao it can easily be done when querying the LiveData in the repository or the viewModel (or where ever you are querying the list) using a transformation. Since I don't know your datanames I'm using made up ones:

```<code>val categoryStatsMap: LiveData<Map<String, Float>> =
    Transformations.map(
        database.categoryStatsDao.getCategoryStats()) {it ->
            it.map {it.key to it.value}.toMap()
}
</code>```

'it.key' and 'it.value' are the fields in the entity object that you want to use as... key and value pairs in the map.
Transformations give you a live data object based on another live data object. I don't know what the overhead is, but I assume it shouldn't be too big.

Title: Return Map object by DAO method

Body:
I would like to have method like this in my dao object

@Query("SELECT c.name, sum(p.value) FROM payments p, paymentCategories c WHERE p.categoryId = c.id GROUP BY c.name")
fun getCategoryStats(): Map<String, Float>

but i get the error

error: Not sure how to convert a Cursor to this method's return type
      public abstract java.util.Map

Is it possible to change it to working version?

So it can be different type to return but the main conditions are

It must be only one query in db

I would like to avoid extra code like creating additional data structure only for this method

Body:
While I don't think this can be done in the Dao it can easily be done when querying the LiveData in the repository or the viewModel (or where ever you are querying the list) using a transformation. Since I don't know your datanames I'm using made up ones:

val categoryStatsMap: LiveData<Map<String, Float>> =
    Transformations.map(
        database.categoryStatsDao.getCategoryStats()) {it ->
            it.map {it.key to it.value}.toMap()
}

'it.key' and 'it.value' are the fields in the entity object that you want to use as... key and value pairs in the map.
Transformations give you a live data object based on another live data object. I don't know what the overhead is, but I assume it shouldn't be too big.


问:
ng server rebuild all instead of detect unchanged chunks
When I do an ng serve, it builds without errors, but when I do a small change in a CSS or HTML, it rebuild the entire app with all node_modules. I remember that few weeks ago this didn't happen.

It's annoying because now when I'm developing, any change delays 1 minute or more recompiling.

Maybe is a missconfiguration in the config files so I paste here:

package.json (XX.XX.XX.XX is my server IP)

```<code>{
  "name": "miac",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "gesti": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng serve --configuration gestiobra --aot --source-map=false --host XXX.XXX.XXX.XXX --port 4200 --vendorChunk=true",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^7.2.15",
    "@angular/cdk": "^7.3.7",
    "@angular/common": "^7.2.15",
    "@angular/compiler": "^7.2.15",
    "@angular/core": "^7.2.15",
    "@angular/flex-layout": "^7.0.0-beta.24",
    "@angular/forms": "^7.2.15",
    "@angular/http": "^7.2.15",
    "@angular/material": "^7.3.7",
    "@angular/platform-browser": "^7.2.15",
    "@angular/platform-browser-dynamic": "^7.2.15",
    "@angular/platform-server": "^7.2.15",
    "@angular/router": "^7.2.15",
    "angular-moment": "^1.3.0",
    "chart.js": "^2.8.0",
    "core-js": "^3.1.2",
    "file-saver": "^2.0.2",
    "font-awesome": "^4.7.0",
    "moment": "^2.24.0",
    "primeflex": "^1.0.0-rc.1",
    "primeicons": "^1.0.0",
    "primeng": "^7.1.3",
    "rxjs": "^6.5.2",
    "rxjs-compat": "^6.5.2",
    "version": "^0.1.2",
    "xlsx": "^0.14.3",
    "zone.js": "^0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.13.9",
    "@angular/cli": "^7.3.9",
    "@angular/compiler-cli": "^7.2.15",
    "@angular/language-service": "^7.2.15",
    "@angularclass/hmr": "^2.1.3",
    "@types/jasmine": "^3.3.12",
    "@types/jasminewd2": "^2.0.6",
    "@types/node": "^12.0.2",
    "codelyzer": "^5.0.1",
    "jasmine-core": "^3.4.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-cli": "^2.0.0",
    "karma-coverage-istanbul-reporter": "~2.0.5",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "^5.4.2",
    "rxjs-tslint": "^0.1.7",
    "terser": "^4.0.0",
    "ts-node": "^8.1.1",
    "tslint": "^5.16.0",
    "typescript": "^3.2.4",
    "webpack": "^4.32.2"
  }
}
</code>```

angular.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "miac": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "go",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "node_modules/primeicons/primeicons.css",
              "node_modules/primeng/resources/themes/nova-light/theme.css",
              "node_modules/primeng/resources/primeng.min.css",
              "node_modules/primeflex/primeflex.css",
              "node_modules/font-awesome/css/font-awesome.min.css"
            ],
            "scripts": ["node_modules/moment/min/moment.min.js"]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": false
            },
            "miac": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment_0.ts"
                },
                {
                  "replace": "src/favicon.ico",
                  "with": "src/assets/favicon_0.ico"
                }
              ],
              "optimization": true,
              "outputHashing": "none",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "miac:build"
          },
          "configurations": {
            "miac": {
              "browserTarget": "miac:build:miac"
            },
            "production": {
              "browserTarget": "miac:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "miac:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "miac-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "miac:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "miac"
}
</code>```

答:
I saw the error.

```<code>"vendorChunk": false
</code>```

Must be true to avoid a complete rebuild.

Body:
When I do an ng serve, it builds without errors, but when I do a small change in a CSS or HTML, it rebuild the entire app with all node_modules. I remember that few weeks ago this didn't happen.

It's annoying because now when I'm developing, any change delays 1 minute or more recompiling.

Maybe is a missconfiguration in the config files so I paste here:

package.json (XX.XX.XX.XX is my server IP)

{
  "name": "miac",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "gesti": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng serve --configuration gestiobra --aot --source-map=false --host XXX.XXX.XXX.XXX --port 4200 --vendorChunk=true",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^7.2.15",
    "@angular/cdk": "^7.3.7",
    "@angular/common": "^7.2.15",
    "@angular/compiler": "^7.2.15",
    "@angular/core": "^7.2.15",
    "@angular/flex-layout": "^7.0.0-beta.24",
    "@angular/forms": "^7.2.15",
    "@angular/http": "^7.2.15",
    "@angular/material": "^7.3.7",
    "@angular/platform-browser": "^7.2.15",
    "@angular/platform-browser-dynamic": "^7.2.15",
    "@angular/platform-server": "^7.2.15",
    "@angular/router": "^7.2.15",
    "angular-moment": "^1.3.0",
    "chart.js": "^2.8.0",
    "core-js": "^3.1.2",
    "file-saver": "^2.0.2",
    "font-awesome": "^4.7.0",
    "moment": "^2.24.0",
    "primeflex": "^1.0.0-rc.1",
    "primeicons": "^1.0.0",
    "primeng": "^7.1.3",
    "rxjs": "^6.5.2",
    "rxjs-compat": "^6.5.2",
    "version": "^0.1.2",
    "xlsx": "^0.14.3",
    "zone.js": "^0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.13.9",
    "@angular/cli": "^7.3.9",
    "@angular/compiler-cli": "^7.2.15",
    "@angular/language-service": "^7.2.15",
    "@angularclass/hmr": "^2.1.3",
    "@types/jasmine": "^3.3.12",
    "@types/jasminewd2": "^2.0.6",
    "@types/node": "^12.0.2",
    "codelyzer": "^5.0.1",
    "jasmine-core": "^3.4.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-cli": "^2.0.0",
    "karma-coverage-istanbul-reporter": "~2.0.5",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "^5.4.2",
    "rxjs-tslint": "^0.1.7",
    "terser": "^4.0.0",
    "ts-node": "^8.1.1",
    "tslint": "^5.16.0",
    "typescript": "^3.2.4",
    "webpack": "^4.32.2"
  }
}

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "miac": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "go",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "node_modules/primeicons/primeicons.css",
              "node_modules/primeng/resources/themes/nova-light/theme.css",
              "node_modules/primeng/resources/primeng.min.css",
              "node_modules/primeflex/primeflex.css",
              "node_modules/font-awesome/css/font-awesome.min.css"
            ],
            "scripts": ["node_modules/moment/min/moment.min.js"]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": false
            },
            "miac": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment_0.ts"
                },
                {
                  "replace": "src/favicon.ico",
                  "with": "src/assets/favicon_0.ico"
                }
              ],
              "optimization": true,
              "outputHashing": "none",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "miac:build"
          },
          "configurations": {
            "miac": {
              "browserTarget": "miac:build:miac"
            },
            "production": {
              "browserTarget": "miac:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "miac:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "miac-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "miac:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "miac"
}

Body:
I saw the error.

"vendorChunk": false

Must be true to avoid a complete rebuild.


问:
How to replace DOM element in place using Javascript?
I am looking to replace an element in the DOM.

For example, there is an  element that I want to replace with a  instead.

How would I go and do that?

答:
Given the already proposed options the easiest solution without finding a parent:</p>

```<code>var parent = document.createElement("div");
var child = parent.appendChild(document.createElement("a"));
var span = document.createElement("span");

// for IE
if("replaceNode" in child)
  child.replaceNode(span);

// for other browsers
if("replaceWith" in child)
  child.replaceWith(span);

console.log(parent.outerHTML);
</code>```

Body:
Given the already proposed options the easiest solution without finding a parent:

var parent = document.createElement("div");
var child = parent.appendChild(document.createElement("a"));
var span = document.createElement("span");

// for IE
if("replaceNode" in child)
  child.replaceNode(span);

// for other browsers
if("replaceWith" in child)
  child.replaceWith(span);

console.log(parent.outerHTML);


问:
How to get a data from an URL
An API like http://www.yourWebService.com/PIP.jsp?request=aaa&param=2

Lets consider the above API gives an JSON value. I use the below coding to get that JSON:

```<code>NSURL *url =[NSURL URLWithString:@"http://www.yourWebService.com/PIP.jsp?request=aaa&param=2"];

NSString *resultedString=[[NSString alloc] initWithContentsOfURL:url];
</code>```

It returns the JSON to the resultedString variable. It is somewhat small amount of Data.
If that API has large amount of data like in 100's of KB's then whether this coding will work fine, or It will crash?

答: If you are working with JSON responses from web server you can use JSON parser to get the results in the form of NSDictionary.

Title: How to get a data from an URL

Body:
An API like http://www.yourWebService.com/PIP.jsp?request=aaa&param=2

Lets consider the above API gives an JSON value. I use the below coding to get that JSON:

NSURL *url =[NSURL URLWithString:@"http://www.yourWebService.com/PIP.jsp?request=aaa&param=2"];

NSString *resultedString=[[NSString alloc] initWithContentsOfURL:url];

It returns the JSON to the resultedString variable. It is somewhat small amount of Data.
If that API has large amount of data like in 100's of KB's then whether this coding will work fine, or It will crash?


问:
Apostrophe-CMS PageBeforeSend Specific to Module
I have a module that is extending apostrophe-custom-pages. I'm trying to add some extra data into the page request (in an async way, preventing use of a helper).

I was hoping to hook into the pageBeforeSend event, but then realized that it runs for EVERY page request, even ones that don't actually hit the pages in the module.

Is there an equivalent method to pageBeforeSend that will only be called if the page being requested is actually in the module where the method is defined?

I'm currently using dispatch to handle this, but I was hoping there might be a better way.

答:
The short answer to your question is no. In Apostrophe 2.x (the current stable release) you must decide for yourself if your pageBeforeSend function is interested in a particular document and return or invoke the callback (if you have one) immediately if it is not relevant.

However here is a longer answer that may shed more light on the question for you.

The pageBeforeSend method is special: it is invoked for every module in which it exists. This is known as a callAll method.

So in callAll methods you are responsible for deciding whether the request or document is relevant to your interests or not. And if you look at our own callAll method handlers you will note that if there is any doubt, we always begin by immediately invoking the callback and returning if the request or document is not relevant.

Please note that in new code you should not write new callAll handlers. You should write promise event handlers instead. This is recommended in 2.x and in 3.x it will be the only way. However in 2.x your question has the same answer when writing promise event handlers: you must determine if the request or document is relevant to your interests, and if not, politely return without doing anything.

In 3.x, we will be improving on this. The 3.x code (very much a work in progress, not ready for projects!) emits events like beforeInsert via the document manager module for the document in question, but lets you decide whether to catch them via that module's name, or via a parent class like apostrophe-doc-type-manager (matching all beforeInsert events for all doc types) or apostrophe-pieces (matching all beforeInsert events for pieces, but not for pages).


问:
How to skip option values and return first some
I have a list of options, i want to skip none values and return the first some.

```<code>val list = List(None, None, None, Some(3));

list.dropWhile(!_.exists).take(1) // return 3
</code>```

Actually it's like this:

```<code>val list = List(1, 2, 3, 4)
def solve(value: Int): Option[Int] = ???
list.dropWhile(!solve(_).isDefined).take(1) // returns the result of solve method
</code>```

and I need solve functions to be called once for each None results, and once for the last Some result.

答:
val list = List(None, None, None, Some(3));
list.flatten.headOption
```

<p>And answer to your second question:</p>

<pre class="lang-scala prettyprint-override"><code>val list = List(1, 2, 3, 4)
def solve(value: Int): Option[Int] = ???
list.toStream.flatMap(solve).headOption // or call .head if you know what you're doing
</code>```

Body:
I have a list of options, i want to skip none values and return the first some.

val list = List(None, None, None, Some(3));

list.dropWhile(!_.exists).take(1) // return 3

Actually it's like this:

val list = List(1, 2, 3, 4)
def solve(value: Int): Option[Int] = ???
list.dropWhile(!solve(_).isDefined).take(1) // returns the result of solve method

and I need solve functions to be called once for each None results, and once for the last Some result.

Body:
val list = List(None, None, None, Some(3));
list.flatten.headOption

And answer to your second question:

val list = List(1, 2, 3, 4)
def solve(value: Int): Option[Int] = ???
list.toStream.flatMap(solve).headOption // or call .head if you know what you're doing