问:
Difference between two lists in Java
I started learning data structures and algorithms with Java.

I started with list and the first concept which I learnt is difference between array and list.

Now in list I learn how to insert and element in to list and displaying on the screen. I got two pieces of code. The first one I understood very well; where the second one is confusing.

My confusion is what is the Node here? In the beginning we declare Node head;. So basically what is Node here?

Is it predefined datatype or something? Also, how does the second program flow? How is the second program different from the first? And what is the difference?

Also I understood that we are using util here, but still I want to know because how people use it in the industry.

The first method:

```<code>import java.util.*;

public class TestCollection7 {
    public static void main(String args[]) {

        LinkedList<String> al = new LinkedList<String>();
        al.add("Ravi");
        al.add("Vijay");
        al.add("Ravi");
        al.add("Ajay");

        Iterator<String> itr = al.iterator();
        while(itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}
</code>```

Second method:

```<code>package javaapplication3;

public class LIstTEst {
    Node head;

    static class Node {
        int data;
        Node next;
        Node(int d) {
            data = d;
            next = null;
        }
    }

    public void PrintList() {
        Node n = head;
        while(n != null){
            System.out.print(n.data+" ");
            n = n.next;
        }
    }

    public static void main(String args[]) {
        LIstTEst llist = new LIstTEst();
        llist.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(7);

        llist.head.next = second;
        second.next = third; = third;

        llist.PrintList();
    }
}
</code>```

答:
That

```<code>public class LIstTEst
</code>```

is nothing else but the first step towards self-implementing a list. Whereas your first piece of source code makes use of the linked list implementation that comes as part of the "standard" Java collection classes.

A "linked list" (in generic terms) is nothing else but, well, a list of connected thingies (of the same type). Those "thingies" are expressed using that internal Node class.

Thus, the real answer is: avoid mixing up concepts and implementation. In order to understand how Java is dealing with "linked lists"; you should first step back and understand the concept "linked list" itself. For example, by reading its Wikipedia entry:

In computer science, a linked list is a linear collection of data elements, called nodes, each pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in the sequence. This structure allows for efficient insertion or removal of elements from any position in the sequence during iteration. More complex variants add additional links, allowing efficient insertion or removal from arbitrary element references.

In other words: programming languages are about implementing common algorithms and data structures for that given language. Therefore it is very much advised to start your research by learning about those common concepts.

Beyond that: the reason why you might find the second example confusing:

probably you have not learned about inner classes yet

the example is incomplete; important methods to add or remove list elements are still missing!

Title: Difference between two lists in Java

Body:
I started learning data structures and algorithms with Java.

I started with list and the first concept which I learnt is difference between array and list.

Now in list I learn how to insert and element in to list and displaying on the screen. I got two pieces of code. The first one I understood very well; where the second one is confusing.

My confusion is what is the Node here? In the beginning we declare Node head;. So basically what is Node here?

Is it predefined datatype or something? Also, how does the second program flow? How is the second program different from the first? And what is the difference?

Also I understood that we are using util here, but still I want to know because how people use it in the industry.

The first method:

import java.util.*;

public class TestCollection7 {
    public static void main(String args[]) {

        LinkedList<String> al = new LinkedList<String>();
        al.add("Ravi");
        al.add("Vijay");
        al.add("Ravi");
        al.add("Ajay");

        Iterator<String> itr = al.iterator();
        while(itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Second method:

package javaapplication3;

public class LIstTEst {
    Node head;

    static class Node {
        int data;
        Node next;
        Node(int d) {
            data = d;
            next = null;
        }
    }

    public void PrintList() {
        Node n = head;
        while(n != null){
            System.out.print(n.data+" ");
            n = n.next;
        }
    }

    public static void main(String args[]) {
        LIstTEst llist = new LIstTEst();
        llist.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(7);

        llist.head.next = second;
        second.next = third; = third;

        llist.PrintList();
    }
}

Body:
That

public class LIstTEst

is nothing else but the first step towards self-implementing a list. Whereas your first piece of source code makes use of the linked list implementation that comes as part of the "standard" Java collection classes.

A "linked list" (in generic terms) is nothing else but, well, a list of connected thingies (of the same type). Those "thingies" are expressed using that internal Node class.

Thus, the real answer is: avoid mixing up concepts and implementation. In order to understand how Java is dealing with "linked lists"; you should first step back and understand the concept "linked list" itself. For example, by reading its Wikipedia entry:

In computer science, a linked list is a linear collection of data elements, called nodes, each pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in the sequence. This structure allows for efficient insertion or removal of elements from any position in the sequence during iteration. More complex variants add additional links, allowing efficient insertion or removal from arbitrary element references.

In other words: programming languages are about implementing common algorithms and data structures for that given language. Therefore it is very much advised to start your research by learning about those common concepts.

Beyond that: the reason why you might find the second example confusing:

probably you have not learned about inner classes yet

the example is incomplete; important methods to add or remove list elements are still missing!


来源: stackexchange

问:
How to Intent into specific Tab Fragment?
T have two Activities: MainActivity and LoginActivity. I have one Fragment too, the name is TabFragment (with a TabLayout), its parent is MainActivity. How can I intent into the specific TabFragment from my Login Activity.

This is my Main Activity:

```<code> protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id = getIntent().getStringExtra("id");

        if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new FragmentUtama()).commit();
            getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new TabFragment()).commit();
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        sharedPreferences = getSharedPreferences("login.conf", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", "");
        String password = sharedPreferences.getString("password", "");
        Log.d(TAG, "Username:"+username+"\npassword:"+password);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }
</code>```

And This my Tab Fragment:

```<code>  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager, null);

        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        viewPager = (ViewPager)view.findViewById(R.id.viewpager);
        viewPager.setAdapter(new Adapterbaru(getChildFragmentManager()));
         tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        return view;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }
    public class Adapterbaru extends FragmentPagerAdapter{
        public Adapterbaru(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0 : {
                    return new Fragmentone();
                }
                case 1 : {
                    return new FragmentTwo();

                }
                case 2 : {
                    return new Fragmenttree();

                }
            }
            return null;
        }

        @Override
        public int getCount() {
           return jumlah_tab;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position){
                case 0 : {
                    return "First";

                }
                case 1 : {
                    return "Second";

                }
                case 2 : {
                    return "Third";
                }
            }
            return null;
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
T have two Activities: MainActivity and LoginActivity. I have one Fragment too, the name is TabFragment (with a TabLayout), its parent is MainActivity. How can I intent into the specific TabFragment from my Login Activity.

This is my Main Activity:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id = getIntent().getStringExtra("id");

        if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new FragmentUtama()).commit();
            getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new TabFragment()).commit();
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        sharedPreferences = getSharedPreferences("login.conf", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", "");
        String password = sharedPreferences.getString("password", "");
        Log.d(TAG, "Username:"+username+"\npassword:"+password);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

And This my Tab Fragment:

  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager, null);

        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        viewPager = (ViewPager)view.findViewById(R.id.viewpager);
        viewPager.setAdapter(new Adapterbaru(getChildFragmentManager()));
         tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        return view;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }
    public class Adapterbaru extends FragmentPagerAdapter{
        public Adapterbaru(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0 : {
                    return new Fragmentone();
                }
                case 1 : {
                    return new FragmentTwo();

                }
                case 2 : {
                    return new Fragmenttree();

                }
            }
            return null;
        }

        @Override
        public int getCount() {
           return jumlah_tab;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position){
                case 0 : {
                    return "First";

                }
                case 1 : {
                    return "Second";

                }
                case 2 : {
                    return "Third";
                }
            }
            return null;
        }

Body: viewpager.setCurrentItem(posotion);


问:
IIS Web Serive Idle Timeout
I know that this is a common issue and has been discussed here long time ago and some solutions are suggested. However, none of them really solve my problem.

I have Windows Server R2 with IIS 7.5 installed. There were over 40 web services hosted in the same application pool. The problem is some web services will go idle after some time, due to those web services are less active. The web services have to be always ready since they are used to handle phone banking transactions. When those web services being called after idling, they take longer time to respond and hence hit the timeout. Customer will experience the transaction performed is unable to process on the phone.

There is an interim solution for this problem, which is a small application was developed and implemented to send dummy request to each web services twice a day, in order to wake up the web services. However, this cannot be done too frequently as this will affect the bank's reporting.

The settings below are set for the application pool:

```<code>startMode = AlwaysRunning, idleTimeout = 00:00:00,
preloadEnabled = true
</code>```

Is there any other way instead of the settings above to overcome such problem? Any comments or suggestions would be appreciated.

答: The obvious solution is not to add those dummy requests to the reports. Log them in a technical log, but don't expose them to the client.</p>

Title: IIS Web Serive Idle Timeout

Body:
I know that this is a common issue and has been discussed here long time ago and some solutions are suggested. However, none of them really solve my problem.

I have Windows Server R2 with IIS 7.5 installed. There were over 40 web services hosted in the same application pool. The problem is some web services will go idle after some time, due to those web services are less active. The web services have to be always ready since they are used to handle phone banking transactions. When those web services being called after idling, they take longer time to respond and hence hit the timeout. Customer will experience the transaction performed is unable to process on the phone.

There is an interim solution for this problem, which is a small application was developed and implemented to send dummy request to each web services twice a day, in order to wake up the web services. However, this cannot be done too frequently as this will affect the bank's reporting.

The settings below are set for the application pool:

startMode = AlwaysRunning, idleTimeout = 00:00:00,
preloadEnabled = true

Is there any other way instead of the settings above to overcome such problem? Any comments or suggestions would be appreciated.


问:
ReactJS ES6 limit lines and characters from a textarea
I was searching for some ways to limit the lines and chars for a textarea with react and es6.
I found a few ways but they dont realy work for all browsers like e.key, where i could limit chars for a line.
I would like to have a text area where i can only have 5 lines and 40 chars each line.

It should be like

```<code>Line 1 -> 1234567890123456789012345678901234567890
Line 2 -> 1234567890123456789012345678901234567890
Line 3 -> 1234567890123456789012345678901234567890
Line 4 -> 1234567890123456789012345678901234567890
Line 5 -> 1234567890123456789012345678901234567890
</code>```

What i already tried:

```<code>add(event){
    let allowedLines = 4;
    let lineLength = 40;
    let maxTextLength = 200;

    if(!(this.state.textAreaValue.length % lineLength)){
        this.setState({
            textAreaValue: this.state.textAreaValue + "\n"
        });
    }

    let maxLines = this.state.textAreaValue.split("\n");
    if(this.state.textAreaValue < maxTextLength
        && maxLines.length <= allowedLines){

        this.setState({
            textAreaValue: this.state.textAreaValue + event.key
        });
    }
}
render(){
    let textValue = this.state.textAreaValue;
    return (
        <textarea className="textArea-big" id="textarea" rows="5" cols="40"
        placeholer="some placeholer here" onKeyPress={this.add} value={textValue} />
    );
}
</code>```

I hope someone can help me with this. thx

答:
Well, found a solution but i think there could be a better way.
Here is my solution:</p>

```<code>setTextAreaFormat() {
    let lines = [];
    let text = "";
    let maxLines = 5;
    let maxTextForLine = 40;
    text = document.getElementById("textarea").value;

    if(text.length >= maxTextForLine){
        lines = text.match(/.{1,35}/g);
    }
    if(lines.length > maxLines){
        lines.length = maxLines;
    }
    if(lines.length > 0){
        document.getElementById("textarea").value = lines.join("\n");
    } else {
        document.getElementById("textarea").value = text;
    }
}
</code>```

Body:
I was searching for some ways to limit the lines and chars for a textarea with react and es6.
I found a few ways but they dont realy work for all browsers like e.key, where i could limit chars for a line.
I would like to have a text area where i can only have 5 lines and 40 chars each line.

It should be like

Line 1 -> 1234567890123456789012345678901234567890
Line 2 -> 1234567890123456789012345678901234567890
Line 3 -> 1234567890123456789012345678901234567890
Line 4 -> 1234567890123456789012345678901234567890
Line 5 -> 1234567890123456789012345678901234567890

What i already tried:

add(event){
    let allowedLines = 4;
    let lineLength = 40;
    let maxTextLength = 200;

    if(!(this.state.textAreaValue.length % lineLength)){
        this.setState({
            textAreaValue: this.state.textAreaValue + "\n"
        });
    }

    let maxLines = this.state.textAreaValue.split("\n");
    if(this.state.textAreaValue < maxTextLength
        && maxLines.length <= allowedLines){

        this.setState({
            textAreaValue: this.state.textAreaValue + event.key
        });
    }
}
render(){
    let textValue = this.state.textAreaValue;
    return (
        <textarea className="textArea-big" id="textarea" rows="5" cols="40"
        placeholer="some placeholer here" onKeyPress={this.add} value={textValue} />
    );
}

I hope someone can help me with this. thx

Body:
Well, found a solution but i think there could be a better way.
Here is my solution:

setTextAreaFormat() {
    let lines = [];
    let text = "";
    let maxLines = 5;
    let maxTextForLine = 40;
    text = document.getElementById("textarea").value;

    if(text.length >= maxTextForLine){
        lines = text.match(/.{1,35}/g);
    }
    if(lines.length > maxLines){
        lines.length = maxLines;
    }
    if(lines.length > 0){
        document.getElementById("textarea").value = lines.join("\n");
    } else {
        document.getElementById("textarea").value = text;
    }
}


问:
C# query in Linq
I'm using C# in Visual Studio 2015.
I have a List<MagicItem> magicItemList and I'm trying to do a simple query using Linq to fetch an Object that matches the Id that the user inputs.
This is my code:

```<code>int itemId = Convert.ToInt32(Console.ReadLine());

var query = from MagicItem magicItem in magicItemList
                where magicItem.Id == itemId
                select magicItem;
</code>```

The thing that confuses me is that query's type is System.Collections.Generic.IEnumerable, so I can't fetch any of its attributes as a normal Object.

Is there a way to cast it so I can use it as a normal Object? Thanks in advance.

This is my MagicItem Class:

```<code>class MagicItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int StockLevel { get; set; }
    }
</code>```

答:
You can use FirstOrDefault() to get your item. If there is no item with the id you will get null. That's why you have to check for null.

```<code>var item = magicItemList.FirstOrDefault(x => x.Id = itemId);
if(item != null)
{
    //do something with item
}
</code>```

With your code you are getting a collection because you are checking one property and you'll get all items in your collection which are matching this property.

For more information have a look at the MSDN

Title: C# query in Linq

Body:
I'm using C# in Visual Studio 2015.
I have a List<MagicItem> magicItemList and I'm trying to do a simple query using Linq to fetch an Object that matches the Id that the user inputs.
This is my code:

int itemId = Convert.ToInt32(Console.ReadLine());

var query = from MagicItem magicItem in magicItemList
                where magicItem.Id == itemId
                select magicItem;

The thing that confuses me is that query's type is System.Collections.Generic.IEnumerable, so I can't fetch any of its attributes as a normal Object.

Is there a way to cast it so I can use it as a normal Object? Thanks in advance.

This is my MagicItem Class:

class MagicItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int StockLevel { get; set; }
    }

Body:
You can use FirstOrDefault() to get your item. If there is no item with the id you will get null. That's why you have to check for null.

var item = magicItemList.FirstOrDefault(x => x.Id = itemId);
if(item != null)
{
    //do something with item
}

With your code you are getting a collection because you are checking one property and you'll get all items in your collection which are matching this property.

For more information have a look at the MSDN


问:
Create the Provider db tables after RecreateDatabaseIfModelChanges
I'm new to EF4, usign CPT4 Code-First and SQLExpress (MVC2 + Ninject but does not matter). It's working good but I do have one question/problem. When I change my model the database get drop and created back because I added this line in my OnApplicationStart()

```<code>{ Database.SetInitializer<CorpiqDb>(new RecreateDatabaseIfModelChanges<CorpiqDb>()); }
</code>```

But I use the Applications Services (membership and role management) that I first created using aspnet_regsql.exe But I don't want to have to run this everytime my model changes, is it possible to have a script that will add these features to my DB? As for right now, after a change to my model I get this error :
Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.

Thanks!

答: What I've done, and it's working quite well, is that I have two seprates DBs, one for my domain and one other for asp.net Membership. When my model changes I call an action that drop model's database and remove users from the membership's one. Event better, I can seed my new database with data I want to have for my test.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm new to EF4, usign CPT4 Code-First and SQLExpress (MVC2 + Ninject but does not matter). It's working good but I do have one question/problem. When I change my model the database get drop and created back because I added this line in my OnApplicationStart()

{ Database.SetInitializer<CorpiqDb>(new RecreateDatabaseIfModelChanges<CorpiqDb>()); }

But I use the Applications Services (membership and role management) that I first created using aspnet_regsql.exe But I don't want to have to run this everytime my model changes, is it possible to have a script that will add these features to my DB? As for right now, after a change to my model I get this error :
Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.

Thanks!


问:
Unity : Can't read the string from the JSON file
i'm trying to read stringfrom json file and pass it to my UI Text in Unity, The issue i'm facing is that the string is always null and i'm not sure why, Right now i find the JSON file path and read it, but when i try to access the string it's null. i'm not sure how to read the json. I really don't understand how this all works. i'm new to JSON format and i'm trying to practice it. This is my first approach. i'm using Unity Engine, and i'm reading the json file using Streaming Assets

Read Data from Json Script:

```<code>using UnityEngine;
using System.IO;

public class ReadFromJson : MonoBehaviour {

private string _filePath = "myText.json";

Data dh;

string str;
 void Start()
{

    LoadGameData();
}

public Data getCurrentRoundData()
{
    return dh;
}

private void LoadGameData()
{
    string filePath = Path.Combine(Application.streamingAssetsPath, _filePath);

    if (File.Exists(filePath))
    {

        string dataAsJSON = File.ReadAllText(filePath);
        DataHolder loadedData = JsonUtility.FromJson<DataHolder>(dataAsJSON);

        dh = loadedData.data;
        str = loadedData.data.TextToPass;
        Debug.Log("My Text is" + dh.TextToPass);

        Debug.Log("Path Exist");

    }

    else
    {
        Debug.LogError("CANNOT LOAD GAME DATA!!");
    }

}

}
</code>```

Manager that applies the json data to my UI Text

```<code>    DataController = FindObjectOfType<ReadFromJson>();

    _data = DataController.getCurrentRoundData();

    myText.text = _data.TextToPass;
</code>```

DataHolder.cs

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]

public class DataHolder {

public Data data;
</code>```

}

Json Text

```<code>{"DataHolder":

    {
        "TextToPass":"I'm A Horse"
    }
</code>```

}

Data.cs

```<code>[System.Serializable]
public class Data {

public string TextToPass ;
}
</code>```

What i get is TextToPass is null

答:
I'm not sure but this might solve your problem. Change your models to this:

Data model:

```<code>[System.Serializable]

public class Data {

public DataHolder dataHolder;

}
</code>```

And your DataHolder model:

```<code>[System.Serializable]

public class DataHolder  {

public string TextToPass;

}
</code>```

Hope it helps!

Body:
i'm trying to read stringfrom json file and pass it to my UI Text in Unity, The issue i'm facing is that the string is always null and i'm not sure why, Right now i find the JSON file path and read it, but when i try to access the string it's null. i'm not sure how to read the json. I really don't understand how this all works. i'm new to JSON format and i'm trying to practice it. This is my first approach. i'm using Unity Engine, and i'm reading the json file using Streaming Assets

Read Data from Json Script:

using UnityEngine;
using System.IO;

public class ReadFromJson : MonoBehaviour {

private string _filePath = "myText.json";

Data dh;

string str;
 void Start()
{

    LoadGameData();
}

public Data getCurrentRoundData()
{
    return dh;
}

private void LoadGameData()
{
    string filePath = Path.Combine(Application.streamingAssetsPath, _filePath);

    if (File.Exists(filePath))
    {

        string dataAsJSON = File.ReadAllText(filePath);
        DataHolder loadedData = JsonUtility.FromJson<DataHolder>(dataAsJSON);

        dh = loadedData.data;
        str = loadedData.data.TextToPass;
        Debug.Log("My Text is" + dh.TextToPass);

        Debug.Log("Path Exist");

    }

    else
    {
        Debug.LogError("CANNOT LOAD GAME DATA!!");
    }

}

}

Manager that applies the json data to my UI Text

    DataController = FindObjectOfType<ReadFromJson>();

    _data = DataController.getCurrentRoundData();

    myText.text = _data.TextToPass;

DataHolder.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]

public class DataHolder {

public Data data;

}

Json Text

{"DataHolder":

    {
        "TextToPass":"I'm A Horse"
    }

}

Data.cs

[System.Serializable]
public class Data {

public string TextToPass ;
}

What i get is TextToPass is null

Body:
I'm not sure but this might solve your problem. Change your models to this:

Data model:

[System.Serializable]

public class Data {

public DataHolder dataHolder;

}

And your DataHolder model:

[System.Serializable]

public class DataHolder  {

public string TextToPass;

}

Hope it helps!


答:
It is going to fetch all instances that match your condition magicItem.Id == itemId.
If you are certain that that will be a single item, I recommend using query.FirstOrDefault() to get that item.

Title: C# query in Linq


问:
Can't install pip packages inside a docker container with Ubuntu
I'm following the fig guide to using docker with a python application, but when docker gets up to the command

```<code>RUN pip install -r requirements.txt
</code>```

I get the following error message:

```<code>Step 3 : RUN pip install -r requirements.txt
 ---> Running in fe0b84217ad1
Collecting blinker==1.3 (from -r requirements.txt (line 1))
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/blinker/
</code>```

This repeats several times and then I get another message:

```<code>Could not find any downloads that satisfy the requirement blinker==1.3 (from -r requirements.txt (line 1))
  No distributions at all found for blinker==1.3 (from -r requirements.txt (line 1))
</code>```

So for some reason pip can't access any packages from inside a docker container. Is there anything I need to do to allow it internet access?

However pip works fine to install things outside of the docker container, and worked fine even with that exact package (blinker==1.3) so that's not the problem. Also this problem isn't specific to that package. I get the same issue with any pip install command for any package.

Does anyone have any idea what's going on here?

答:
For Ubuntu users

You need to add new DNS addresses in the docker config

```<code>sudo nano /lib/systemd/system/docker.service
</code>```

Add the dns after ExecStar.

```<code>--dns 10.252.252.252 --dns 10.253.253.253
</code>```

Should look like that:

```<code>ExecStart=/usr/bin/dockerd -H fd:// --dns 10.252.252.252 --dns 10.253.253.253
</code>```

Then do:

```<code>systemctl daemon-reload
sudo service docker restart
</code>```

Should work.

Body:
I'm following the fig guide to using docker with a python application, but when docker gets up to the command

RUN pip install -r requirements.txt

I get the following error message:

Step 3 : RUN pip install -r requirements.txt
 ---> Running in fe0b84217ad1
Collecting blinker==1.3 (from -r requirements.txt (line 1))
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/blinker/

This repeats several times and then I get another message:

Could not find any downloads that satisfy the requirement blinker==1.3 (from -r requirements.txt (line 1))
  No distributions at all found for blinker==1.3 (from -r requirements.txt (line 1))

So for some reason pip can't access any packages from inside a docker container. Is there anything I need to do to allow it internet access?

However pip works fine to install things outside of the docker container, and worked fine even with that exact package (blinker==1.3) so that's not the problem. Also this problem isn't specific to that package. I get the same issue with any pip install command for any package.

Does anyone have any idea what's going on here?

Body:
For Ubuntu users

You need to add new DNS addresses in the docker config

sudo nano /lib/systemd/system/docker.service

Add the dns after ExecStar.

--dns 10.252.252.252 --dns 10.253.253.253

Should look like that:

ExecStart=/usr/bin/dockerd -H fd:// --dns 10.252.252.252 --dns 10.253.253.253

Then do:

systemctl daemon-reload
sudo service docker restart

Should work.

ContentLicense: CC BY-SA 4.0


问:
Best way to separate read and write concerns using interfaces?
Lately I've been realizing the benefit of (some would argue overuse of) immutable objects to cut down dramatically on read-write dependency issues in my object model and their resulting conditions and side-effects, to ultimately make the code simpler to manage (kind of functional-programming-esque).

This practice has led me to create read-only objects that are provided values at creation/construction time and then to make available only public getters for external callers to access the properties with. Protected, internal and private setters allow internal control to be maintained over writing to the object model.

When creating interfaces while making an API over my object model, I've started considering the same issues about immutability. For example, by providing only public getters on my interfaces, and leaving it up to implementors to decide upon setters and how to handle that aspect.

An example of a "read-only" interface for implementation that I'm talking about is this Valuable Item (just for demonstration):

```<code>public interface IValuableItem {
    decimal Amount {get;}
    string Currency {get;}
}
</code>```

However I got to wondering how I should provide a companion interface that allows for writing (and if I should), and not combine those operations within the same interface as to not "taint" its immutability.

The following ideas have come to mind, just off the top of my head. Without providing what I think are pros and cons to each, what do you think the best approach is? Is there a coding methodology common in the industry for managing this concept?

```<code>// companion writer
public interface IValuableModifier {
    decimal Amount {set;}
    string Currency {set;}
}
</code>```

or

```<code>// explicit methods to enforce importance of or deviance in the programming
public interface IValuableModifier {
    void SetAmount(decimal val);
    void SetCurrency(string cur);
}
</code>```

or

```<code>// companion writer that inherits the original interface
public interface IValuableModifier : IValuableItem { //...
</code>```

or

```<code>// Let a concrete class choose one and/or the other.
class Concrete  : IValuableModifer, IValuableItem { //...
</code>```

or

etc...

What else can help me imbue writing on my otherwise immutable programming model and keep it moderately flexible or at least to separate the concerns for better control over it?

答:
Consider using a builder pattern:  Builder objects construct immutable instances of the core object.  .NET Strings are like this - the string object is immutable, and there is a StringBuilder class for efficient construction of string objects.  (string + string + string is much less efficient than using a StringBuilder to do the same)

Note also that builder objects exist solely for building the target object - builders are not instances of the target object / do not implement the target interface themselves.

It's worth the effort to make your system run on immutable objects, as immutability washes away a lot of headaches in threading / concurrency / parallel execution scenarios, as well as data caching / data versioning scenarios.

Body:
Lately I've been realizing the benefit of (some would argue overuse of) immutable objects to cut down dramatically on read-write dependency issues in my object model and their resulting conditions and side-effects, to ultimately make the code simpler to manage (kind of functional-programming-esque).

This practice has led me to create read-only objects that are provided values at creation/construction time and then to make available only public getters for external callers to access the properties with. Protected, internal and private setters allow internal control to be maintained over writing to the object model.

When creating interfaces while making an API over my object model, I've started considering the same issues about immutability. For example, by providing only public getters on my interfaces, and leaving it up to implementors to decide upon setters and how to handle that aspect.

An example of a "read-only" interface for implementation that I'm talking about is this Valuable Item (just for demonstration):

public interface IValuableItem {
    decimal Amount {get;}
    string Currency {get;}
}

However I got to wondering how I should provide a companion interface that allows for writing (and if I should), and not combine those operations within the same interface as to not "taint" its immutability.

The following ideas have come to mind, just off the top of my head. Without providing what I think are pros and cons to each, what do you think the best approach is? Is there a coding methodology common in the industry for managing this concept?

// companion writer
public interface IValuableModifier {
    decimal Amount {set;}
    string Currency {set;}
}

or

// explicit methods to enforce importance of or deviance in the programming
public interface IValuableModifier {
    void SetAmount(decimal val);
    void SetCurrency(string cur);
}

or

// companion writer that inherits the original interface
public interface IValuableModifier : IValuableItem { //...

or

// Let a concrete class choose one and/or the other.
class Concrete  : IValuableModifer, IValuableItem { //...

or

etc...

What else can help me imbue writing on my otherwise immutable programming model and keep it moderately flexible or at least to separate the concerns for better control over it?


问:
rpmbuild install dependency
I'm new to rpmbuild + spec files and I tried the following tutorial to build the "hello world" example.

Manage to get it working, but I wanted to learn how dependencies/requires works. Therefore, I tried to duplicate another "hello world 2" example and link it as a dependency to the first in the spec file below.

However I keep getting the error below. Is there a way that yum install will pick up the helloworld1 and install automatically when i yum install helloworld2 ?

Any example for me learn from?

SPEC FILE

```<code>Name:           helloworld2
Version:        2.0
Release:        1%{?dist}
Summary:        A hello world program

License:        GPLv3+
URL:            https://blog.packagecloud.io
Source0:        helloworld2-2.0.tar.gz

#BuildRequires: helloworld1
Requires(preun):  helloworld1
#PreReq: testYW

%description
A helloworld program from the packagecloud.io blog!

%prep
%setup

%build
make PREFIX=/usr %{?_smp_mflags}

%install
make PREFIX=/usr DESTDIR=%{?buildroot} install
echo %{?buildroot}

%clean
rm -rf %{buildroot}

%files
%{_bindir}/helloworld2
</code>```

ERORR

COMMAND >> yum install RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm

```<code>Loaded plugins: product-id, search-disabled-repos, security, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
Setting up Install Process
Examining RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm: helloworld2-2.0-1.el6.x86_64
Marking RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package helloworld2.x86_64 0:2.0-1.el6 will be installed
--> Processing Dependency: helloworld1 for package: helloworld2-2.0-1.el6.x86_64
--> Finished Dependency Resolution
Error: Package: helloworld2-2.0-1.el6.x86_64 (/helloworld2-2.0-1.el6.x86_64)
           Requires: helloworld1
 You could try using --skip-broken to work around the problem
</code>```

答:
okay ! i got the answer !

i can either do a yum install *.rpm , which it will do its own dependency

else putting all the new rpm file into the repository and it will pick it up :)

Title: rpmbuild install dependency

Body:
I'm new to rpmbuild + spec files and I tried the following tutorial to build the "hello world" example.

Manage to get it working, but I wanted to learn how dependencies/requires works. Therefore, I tried to duplicate another "hello world 2" example and link it as a dependency to the first in the spec file below.

However I keep getting the error below. Is there a way that yum install will pick up the helloworld1 and install automatically when i yum install helloworld2 ?

Any example for me learn from?

SPEC FILE

Name:           helloworld2
Version:        2.0
Release:        1%{?dist}
Summary:        A hello world program

License:        GPLv3+
URL:            https://blog.packagecloud.io
Source0:        helloworld2-2.0.tar.gz

#BuildRequires: helloworld1
Requires(preun):  helloworld1
#PreReq: testYW

%description
A helloworld program from the packagecloud.io blog!

%prep
%setup

%build
make PREFIX=/usr %{?_smp_mflags}

%install
make PREFIX=/usr DESTDIR=%{?buildroot} install
echo %{?buildroot}

%clean
rm -rf %{buildroot}

%files
%{_bindir}/helloworld2

ERORR

COMMAND >> yum install RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm

Loaded plugins: product-id, search-disabled-repos, security, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
Setting up Install Process
Examining RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm: helloworld2-2.0-1.el6.x86_64
Marking RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package helloworld2.x86_64 0:2.0-1.el6 will be installed
--> Processing Dependency: helloworld1 for package: helloworld2-2.0-1.el6.x86_64
--> Finished Dependency Resolution
Error: Package: helloworld2-2.0-1.el6.x86_64 (/helloworld2-2.0-1.el6.x86_64)
           Requires: helloworld1
 You could try using --skip-broken to work around the problem


问:
How to create factory in AngularJS?
I had created a factory in angular but i am  getting the following  error

```<code>Unknown provider:
</code>```

Here is the factory:

```<code>app.factory("getFoo", function($scope){
    return {
       getCommi: function(val,id){
          var array = ["hello","world"];
          return array;
       }
     }
});
</code>```

The controller is:

```<code>app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
   $scope.myArr = getFoo.getCommi(4,1);
}])
</code>```

What can I have to do for  fix this? I just don't see any problem.

答:
Remove $scope from your factory and add factory "getFoo" as a dependency in your app's run module like this:

app.run(['$rootScope', '$location', 'getFoo', function($rootScope, $location, getFoo) {

}]);

Title: How to create factory in AngularJS?

Body:
I had created a factory in angular but i am  getting the following  error

Unknown provider:

Here is the factory:

app.factory("getFoo", function($scope){
    return {
       getCommi: function(val,id){
          var array = ["hello","world"];
          return array;
       }
     }
});

The controller is:

app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
   $scope.myArr = getFoo.getCommi(4,1);
}])

What can I have to do for  fix this? I just don't see any problem.


答:
First example

LinkedList is an implementation of a linked-list data structure in Java.

Second example

It is manually written implementation of the same data structure. Node is you class, which describes one cell in this linked list.

Both implementations are not the same. Java's implementation provides a bunch of convenient methods to work with list, while yours do not. You can start with an implementation of add method.

```<code>// Appends the specified element to the end of this list.
public void add(int data) {

    // Create Node only in case of first element
    if (head == null) {
        head = new Node(data);
    }

    Node temp = new Node(data);
    Node current = head;

    // Check if there is first element
    if (current != null) {

        // Starting at the head node, iterate to the end of the list and then add element after last node
        while (current.getNext() != null) {
            current = current.getNext();
        }

        // The last node's "next" reference set to our new node
        current.setNext(temp);
    }
}
</code>```

What is a linked list?

Long story short: a linked list is a chain of cells. Each cell knows about the next one. The last cell knows that there is no next cell. A linked-list class (which manipulates those cells (nodes)) contains reference for the first node.

Look at this interactive demo: https://visualgo.net/list

Title: Difference between two lists in Java

Body:
First example

LinkedList is an implementation of a linked-list data structure in Java.

Second example

It is manually written implementation of the same data structure. Node is you class, which describes one cell in this linked list.

Both implementations are not the same. Java's implementation provides a bunch of convenient methods to work with list, while yours do not. You can start with an implementation of add method.

// Appends the specified element to the end of this list.
public void add(int data) {

    // Create Node only in case of first element
    if (head == null) {
        head = new Node(data);
    }

    Node temp = new Node(data);
    Node current = head;

    // Check if there is first element
    if (current != null) {

        // Starting at the head node, iterate to the end of the list and then add element after last node
        while (current.getNext() != null) {
            current = current.getNext();
        }

        // The last node's "next" reference set to our new node
        current.setNext(temp);
    }
}

What is a linked list?

Long story short: a linked list is a chain of cells. Each cell knows about the next one. The last cell knows that there is no next cell. A linked-list class (which manipulates those cells (nodes)) contains reference for the first node.

Look at this interactive demo: https://visualgo.net/list


问:
File Upload Angular 2 & Sails Js
I am trying to upload multiple files from Angular 2 and Sails Js server. I want to place file inside public folder of SailJs App.

The file is uploaded from Angular 2 App by getting file from an event fired. the code for single file upload is as follows:

Angular 2 service:

```<code>fileChange(event: any): Promise<string>  {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('myFile', file, file.name);
        let headers = new Headers();
        let cToken = this.cookie.getCookie("token");
        headers.append('Authorization', 'Bearer ' + cToken);
        headers.append('Content-Type', undefined);

        //headers.append('Content-Type', 'multipart/form-data');

        headers.append('Accept', 'application/json');
        let options: RequestOptionsArgs = { headers: headers, withCredentials: true }
        return new Promise((resolve, reject) => {
            this.http.post( this.apiEndpoint + "project/reffile/add/all", formData, options).toPromise()
            .then(response => {
                // The promise is resolved once the HTTP call is successful.
                let jsonData = response.json();
                if (jsonData.apiStatus == 1) {
                    resolve(jsonData);
                }
                else reject(jsonData.message);
            })
            // The promise is rejected if there is an error with the HTTP call.
            // if we don't get any answers the proxy/api will probably be down
            .catch(reason => reject(reason.statusText));
        });
    }
}
</code>```

SailsJs method:

```<code>  /**
   * `FileController.upload()`
   *
   * Upload file(s) to the server's disk.
   */
   addAll: function (req, res) {

    // e.g.
    // 0 => infinite
    // 240000 => 4 minutes (240,000 miliseconds)
    // etc.
    //
    // Node defaults to 2 minutes.
    res.setTimeout(0);

    console.log("req.param('filename')");
    console.log(req.param('filename'));
    req.file('myFile')
    .upload({

      // You can apply a file upload limit (in bytes)
      maxBytes: 1000000

    }, function whenDone(err, uploadedFiles) {
      if (err) return res.serverError(err);
      else return res.json({
        files: uploadedFiles,
        textParams: req.allParams()
      });
    });
  },
</code>```

after posting form, I didn't get file in HTTP call response also not able to console.log(req.param('filename'));.

please help me what I am doing wrong here. I also tried changing/removing header, but still not working,

some expert says that HTTP currently cant upload files, need to use native XHR request for this. please view Thierry Templier's answer here

答:
Try specifying a directory for file upload:

```<code>    req.file('file').upload({
        dirname: '../../assets/uploads'
    },function (err, files) {
        if (err) return res.serverError(err);
        var fileNameArray = files[0].fd.split("/");
        var fileName = fileNameArray[fileNameArray.length - 1];
        console.log("fileName: ",fileName);
    });
</code>```

To access the uploaded file - you can append the fileName to the upload directory that you have specified. File will be accessible

Title: File Upload Angular 2 & Sails Js

Body:
I am trying to upload multiple files from Angular 2 and Sails Js server. I want to place file inside public folder of SailJs App.

The file is uploaded from Angular 2 App by getting file from an event fired. the code for single file upload is as follows:

Angular 2 service:

fileChange(event: any): Promise<string>  {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('myFile', file, file.name);
        let headers = new Headers();
        let cToken = this.cookie.getCookie("token");
        headers.append('Authorization', 'Bearer ' + cToken);
        headers.append('Content-Type', undefined);

        //headers.append('Content-Type', 'multipart/form-data');

        headers.append('Accept', 'application/json');
        let options: RequestOptionsArgs = { headers: headers, withCredentials: true }
        return new Promise((resolve, reject) => {
            this.http.post( this.apiEndpoint + "project/reffile/add/all", formData, options).toPromise()
            .then(response => {
                // The promise is resolved once the HTTP call is successful.
                let jsonData = response.json();
                if (jsonData.apiStatus == 1) {
                    resolve(jsonData);
                }
                else reject(jsonData.message);
            })
            // The promise is rejected if there is an error with the HTTP call.
            // if we don't get any answers the proxy/api will probably be down
            .catch(reason => reject(reason.statusText));
        });
    }
}

SailsJs method:

  /**
   * `FileController.upload()`
   *
   * Upload file(s) to the server's disk.
   */
   addAll: function (req, res) {

    // e.g.
    // 0 => infinite
    // 240000 => 4 minutes (240,000 miliseconds)
    // etc.
    //
    // Node defaults to 2 minutes.
    res.setTimeout(0);

    console.log("req.param('filename')");
    console.log(req.param('filename'));
    req.file('myFile')
    .upload({

      // You can apply a file upload limit (in bytes)
      maxBytes: 1000000

    }, function whenDone(err, uploadedFiles) {
      if (err) return res.serverError(err);
      else return res.json({
        files: uploadedFiles,
        textParams: req.allParams()
      });
    });
  },

after posting form, I didn't get file in HTTP call response also not able to console.log(req.param('filename'));.

please help me what I am doing wrong here. I also tried changing/removing header, but still not working,

some expert says that HTTP currently cant upload files, need to use native XHR request for this. please view Thierry Templier's answer here

Body:
Try specifying a directory for file upload:

    req.file('file').upload({
        dirname: '../../assets/uploads'
    },function (err, files) {
        if (err) return res.serverError(err);
        var fileNameArray = files[0].fd.split("/");
        var fileName = fileNameArray[fileNameArray.length - 1];
        console.log("fileName: ",fileName);
    });

To access the uploaded file - you can append the fileName to the upload directory that you have specified. File will be accessible


答:
The problem is that you will not per se obtain one element: at code level it is unknown that the id is unique.

You can use .First() or .FirstOrDefault() to obtain the first element that matches the condition:

```<code>var query = (from MagicItem magicItem in magicItemList
                where magicItem.Id == itemId
                select magicItem)<b>.First()</b>;</code>```

Title: C# query in Linq

Body:
The problem is that you will not per se obtain one element: at code level it is unknown that the id is unique.

You can use .First() or .FirstOrDefault() to obtain the first element that matches the condition:

var query = (from MagicItem magicItem in magicItemList
                where magicItem.Id == itemId
                select magicItem).First();


问:
ES2015 ${ } syntax apply toString() on a Buffer?
seems like in ES2015, Template String ${ } syntax will apply toString() to a Buffer object

```<code>let a = Buffer.from('hello')

let b = () => {
    console.log(`es6 : ${a}`) // hello
    console.log('raw a : ', a) // <Buffer 68 65 6c 6c 6f>
    console.log('compiled to es5 : ' + a) // hello
    console.log(+a) // NaN
}

b()
</code>```

I can't find enough information on this topic, can anyone explain this ?

答:
${} syntax causes to invoke toString method on any js object:

let a = {toString: ()=>("I'm a string")};
console.log(`result: ${a}`);```

Body:
seems like in ES2015, Template String ${ } syntax will apply toString() to a Buffer object

let a = Buffer.from('hello')

let b = () => {
    console.log(`es6 : ${a}`) // hello
    console.log('raw a : ', a) // <Buffer 68 65 6c 6c 6f>
    console.log('compiled to es5 : ' + a) // hello
    console.log(+a) // NaN
}

b()

I can't find enough information on this topic, can anyone explain this ?


问:
Modify the content of a dataframe in R
I would like to transform/modify the content of dataframe. Basically I have a dataframe like below:

```<code>        bins      pval
1   2L:1:150 0.9224217
2 2L:151:300 0.9478824
3 2L:301:450 0.9671139
4 2L:451:600 0.9280847
5 2L:601:750 0.9698584
6 2L:751:900 0.9725379
</code>```

And I would like to transform/modify into another dataframe like this, where I split the content of my "bins" column (first row) into 150 rows containing the same values. And so on for the second row.

```<code>    chr  pos    pval
1   2L   1 0.9224217
2   2L   2 0.9224217
3   2L   3 0.9224217
4   2L   4 0.9224217
5   2L   5 0.9224217
...
150  2L   150 0.9224217
151  2L   151 0.9478824
152  2L   152 0.9478824
153  2L   153 0.9478824
etc...
</code>```

Any help much appreciated,

Ben

答:
Here's an attempt at a more generalized answer that could be made more efficient. I couldn't find an easy way to convert from a factor to numeric while retaining the levels in the new numeric column. Regardless, this should work and can support different values for the "chr" column and different numbers of rows:

```<code>library(plyr)

df <- read.table(textConnection("        bins      pval
1   2L:1:150 0.9224217
2 2L:151:300 0.9478824
3 2L:301:450 0.9671139
4 2L:451:600 0.9280847
5 2L:601:750 0.9698584
6 2L:751:900 0.9725379
"), header = TRUE)

#Split bins
df.split <- data.frame(matrix(unlist(strsplit(as.character(df$bins), ":")), ncol = 3, byrow = TRUE ))

colnames(df.split) <- c("chr", "low", "high")

df.split$low <- as.numeric(as.character(df.split$low))
df.split$high <- as.numeric(as.character(df.split$high))

#Attach the pval from original df
df.split$pval <- df[, 2]

df.new <- adply(df.split, 1, summarise, pos = (low - 1) + seq(low:high))
df.new <- df.new[, c(1, 5, 4)]
</code>```

Title: Modify the content of a dataframe in R

Body:
I would like to transform/modify the content of dataframe. Basically I have a dataframe like below:

        bins      pval
1   2L:1:150 0.9224217
2 2L:151:300 0.9478824
3 2L:301:450 0.9671139
4 2L:451:600 0.9280847
5 2L:601:750 0.9698584
6 2L:751:900 0.9725379

And I would like to transform/modify into another dataframe like this, where I split the content of my "bins" column (first row) into 150 rows containing the same values. And so on for the second row.

    chr  pos    pval
1   2L   1 0.9224217
2   2L   2 0.9224217
3   2L   3 0.9224217
4   2L   4 0.9224217
5   2L   5 0.9224217
...
150  2L   150 0.9224217
151  2L   151 0.9478824
152  2L   152 0.9478824
153  2L   153 0.9478824
etc...

Any help much appreciated,

Ben

Body:
Here's an attempt at a more generalized answer that could be made more efficient. I couldn't find an easy way to convert from a factor to numeric while retaining the levels in the new numeric column. Regardless, this should work and can support different values for the "chr" column and different numbers of rows:

library(plyr)

df <- read.table(textConnection("        bins      pval
1   2L:1:150 0.9224217
2 2L:151:300 0.9478824
3 2L:301:450 0.9671139
4 2L:451:600 0.9280847
5 2L:601:750 0.9698584
6 2L:751:900 0.9725379
"), header = TRUE)

#Split bins
df.split <- data.frame(matrix(unlist(strsplit(as.character(df$bins), ":")), ncol = 3, byrow = TRUE ))

colnames(df.split) <- c("chr", "low", "high")

df.split$low <- as.numeric(as.character(df.split$low))
df.split$high <- as.numeric(as.character(df.split$high))

#Attach the pval from original df
df.split$pval <- df[, 2]

df.new <- adply(df.split, 1, summarise, pos = (low - 1) + seq(low:high))
df.new <- df.new[, c(1, 5, 4)]


问:
How to get contact change, add and remove with URI provided by system call back onChange android?
I am building an app , there is a requirement of notifying app when a new contact added or existing contact gets edited or removed. Although a lot of questions are already available those have answers as well. But my question is little bit different. I am using approach of Content Observer as mentioned below in the code

```<code>ContactChangeObserver contactChangeObserver = new ContactChangeObserver(this, new Handler());
    getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactChangeObserver);
</code>```

and in ContactChangeObserver class I am overriding onChange() method as it was already recommended in many of the post. Code is mentioned below

```<code>public class ContactChangeObserver extends ContentObserver {

private Context mContext;
public ContactChangeObserver(Context context, Handler handler) {
    super(handler);
    mContext = context;
}

@Override
public void onChange(boolean selfChange, Uri uri) {
    super.onChange(selfChange, uri);
    List<ContactsModel> listOfDBContact = new ChildTrackingDB().getAllContacts(ChildTrackingDB.getInstance(mContext));
    List<ContactsModel> listOfCellPhoneContact = ContactUtility.readContactDirectoryOfPhone(mContext);
    if (listOfCellPhoneContact.size() == listOfDBContact.size()) {
        //this is edit case
    } else  if (listOfCellPhoneContact.size() > listOfDBContact.size()) {
        //this is add case

    }else  {
        //this is remove case
    }
}
</code>```

}

I am getting call back of onChange() as expected(in all cases of adding, removing and editing case). As mentioned in above example, I am overriding onChange() that has URI param. And when I get call back i also receive uri as well. my question is that can that uri be useful to only get that contact which got changed or added? The uri I am getting is

```<code>content://com.android.contacts
</code>```

In my example code, if contact is edited and the device has let's suppose more than thousands contacts then it is a very time consuming to iterate over each contact.Or is there any better approach available for the problem.

答:
I've faced a similar kind of problem. First of all the Uri which you are getting in onChange() method is vague. From my previous encounter I can tell, You won't be able to detect which contact got inserted, updated or deleted. So yes it becomes very time-consuming to detect which contact to get and perform Crud.

To answer your second question, I would suggest you to use Set instead of List. Here is a sample class which you might helpful. It's a linear operation and i've tested it with 2-3k+ data. And it performs well.

```<code>public class AddressBookObserver extends ContentObserver {

private static final String TAG = "AddressBookObserver";
private static final String FLAG_INSERT = "INSERT";
private static final String FLAG_DELETE = "DELETE";

private long lastTimeOfCall = 0L;
private long lastTimeOfUpdate = 0L;
private long threshold_time = 5000;
private WeakReference<Context> mContextWeakReference;

public AddressBookObserver(Handler handler, Context context) {
    super(handler);
    this.mContextWeakReference = new WeakReference<Context>(context);
}

@Override
public void onChange(boolean selfChange) {
    onChange(selfChange, null);
}

@Override
public void onChange(boolean selfChange, Uri uri) {
    Log.d(TAG, "onChange() Address Book Changed!");

    lastTimeOfCall = System.currentTimeMillis();

    Set<String> phoneBookSet = new HashSet<>();
    Set<String> providerSet = new HashSet<>();

    if (checkContactPermission() && (lastTimeOfCall - lastTimeOfUpdate > threshold_time) && General.getIsContactListImported(mContextWeakReference.get())) {
        lastTimeOfUpdate = System.currentTimeMillis();

        phoneBookSet.addAll(getOnlyPhoneNumbers());
        providerSet.addAll(getProviderNumbers());

        int bookCount = phoneBookSet.size();
        int providerCount = providerSet.size();

        Log.e(TAG, "onChange: bookCount: " + bookCount + " providerCount: " + providerCount);

        if (bookCount > providerCount) {
            Log.i(TAG, "onChange() Insert!");
            phoneBookSet.removeAll(providerSet);
            String val = phoneBookSet.toString().replaceAll("[\\(\\)\\[\\]\\{\\}]", "");
            Log.w(TAG, "value to insert: " + val);
            //DO Insert Operations

        } else if (bookCount < providerCount) {
            Log.i(TAG, "onChange() DELETE!");
            providerSet.removeAll(phoneBookSet);
            String val = providerSet.toString().replaceAll("[\\(\\)\\[\\]\\{\\}]", "");
            Log.w(TAG, "value to delete: " + val);
            //Do Delete Operations
        } else {
            Log.i(TAG, "onChange() UPDATE!");
            Set<String> tempPhoneBookSet = new HashSet<>();
            tempPhoneBookSet.addAll(phoneBookSet);

            phoneBookSet.removeAll(providerSet);
            String newData = phoneBookSet.toString().replaceAll("[\\(\\)\\[\\]\\{\\}]", "");
            Log.e(TAG, "newData: " + newData);

            providerSet.removeAll(tempPhoneBookSet);
            String deleteData = providerSet.toString().replaceAll("[\\(\\)\\[\\]\\{\\}]", "");
            Log.e(TAG, "deleteData: " + deleteData);

            if (!newData.equals(deleteData)) {
                //DO Update Operations
            } else {
                Log.i(TAG, "onChange() Nothing to update!");
            }
        }
    } else if (!checkContactPermission()) {
        Log.e(TAG, "onChange() Contact Permission not granted!");
    } else {
        Log.e(TAG, "onChange() Time threshold not reached Or Contacts not imported yet!");
    }

}

private boolean checkContactPermission() {
    return ContextCompat.checkSelfPermission(mContextWeakReference.get(), Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
}

/**
 * Get only phone numbers from device's addressBook
 *
 * @return - Set of distinct phone numbers
 */
private Set<String> getOnlyPhoneNumbers() {
    Log.d(TAG, "getOnlyPhoneNumbers()");
    Cursor phones = mContextWeakReference.get().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " ASC");

    Set<String> uniquePhoneContacts = new HashSet<>();

    while (phones.moveToNext()) {
        String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("\\D", "");
        String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
        String photoUri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));

        if (uniquePhoneContacts.add(id + "," + name + "," + photoUri + "," + phoneNumber)) {
            Log.w(TAG, "Book#" + id + "," + name + "," + photoUri + "," + phoneNumber);
        }
    }
    phones.close();
    return uniquePhoneContacts;

}

/**
 * Get all the Contacts from provider which are not deletable
 *
 * @return - All distinct phone numbers from app's provider
 */
private Set<String> getProviderNumbers() {
    Log.d(TAG, "getProviderNumbers()");
    Cursor phones = mContextWeakReference.get().getContentResolver().query(MyContactProvider.CONTENT_URI, null, PhoneContactController.COL_IS_DELETABLE + "=?",
            new String[]{"0"}, MyContactProvider.COL_CONTACT_ID + " ASC");
    Set<String> uniquePhoneContacts = new HashSet<>();
    while (phones.moveToNext()) {
        String id = phones.getString(phones.getColumnIndex(MyContactProvider.COL_CONTACT_ID));
        String name = phones.getString(phones.getColumnIndex(MyContactProvider.COL_NAME));
        String phoneNumber = phones.getString(phones.getColumnIndex(MyContactProvider.COL_CONTACT_NO));
        String photoUri = phones.getString(phones.getColumnIndex(MyContactProvider.COL_PHOTO_URI));

        if (uniquePhoneContacts.add(id + "," + name + "," + photoUri + "," + phoneNumber)) {
            Log.w(TAG, "QueryProvider#" + id + "," + name + "," + photoUri + "," + phoneNumber);
        }
    }
    phones.close();
    return uniquePhoneContacts;
}

}
</code>```

I hope this helps.

Body:
I am building an app , there is a requirement of notifying app when a new contact added or existing contact gets edited or removed. Although a lot of questions are already available those have answers as well. But my question is little bit different. I am using approach of Content Observer as mentioned below in the code

ContactChangeObserver contactChangeObserver = new ContactChangeObserver(this, new Handler());
    getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactChangeObserver);

and in ContactChangeObserver class I am overriding onChange() method as it was already recommended in many of the post. Code is mentioned below

public class ContactChangeObserver extends ContentObserver {

private Context mContext;
public ContactChangeObserver(Context context, Handler handler) {
    super(handler);
    mContext = context;
}

@Override
public void onChange(boolean selfChange, Uri uri) {
    super.onChange(selfChange, uri);
    List<ContactsModel> listOfDBContact = new ChildTrackingDB().getAllContacts(ChildTrackingDB.getInstance(mContext));
    List<ContactsModel> listOfCellPhoneContact = ContactUtility.readContactDirectoryOfPhone(mContext);
    if (listOfCellPhoneContact.size() == listOfDBContact.size()) {
        //this is edit case
    } else  if (listOfCellPhoneContact.size() > listOfDBContact.size()) {
        //this is add case

    }else  {
        //this is remove case
    }
}

}

I am getting call back of onChange() as expected(in all cases of adding, removing and editing case). As mentioned in above example, I am overriding onChange() that has URI param. And when I get call back i also receive uri as well. my question is that can that uri be useful to only get that contact which got changed or added? The uri I am getting is

content://com.android.contacts

In my example code, if contact is edited and the device has let's suppose more than thousands contacts then it is a very time consuming to iterate over each contact.Or is there any better approach available for the problem.

Body:
I've faced a similar kind of problem. First of all the Uri which you are getting in onChange() method is vague. From my previous encounter I can tell, You won't be able to detect which contact got inserted, updated or deleted. So yes it becomes very time-consuming to detect which contact to get and perform Crud.

To answer your second question, I would suggest you to use Set instead of List. Here is a sample class which you might helpful. It's a linear operation and i've tested it with 2-3k+ data. And it performs well.

public class AddressBookObserver extends ContentObserver {

private static final String TAG = "AddressBookObserver";
private static final String FLAG_INSERT = "INSERT";
private static final String FLAG_DELETE = "DELETE";

private long lastTimeOfCall = 0L;
private long lastTimeOfUpdate = 0L;
private long threshold_time = 5000;
private WeakReference<Context> mContextWeakReference;

public AddressBookObserver(Handler handler, Context context) {
    super(handler);
    this.mContextWeakReference = new WeakReference<Context>(context);
}

@Override
public void onChange(boolean selfChange) {
    onChange(selfChange, null);
}

@Override
public void onChange(boolean selfChange, Uri uri) {
    Log.d(TAG, "onChange() Address Book Changed!");

    lastTimeOfCall = System.currentTimeMillis();

    Set<String> phoneBookSet = new HashSet<>();
    Set<String> providerSet = new HashSet<>();

    if (checkContactPermission() && (lastTimeOfCall - lastTimeOfUpdate > threshold_time) && General.getIsContactListImported(mContextWeakReference.get())) {
        lastTimeOfUpdate = System.currentTimeMillis();

        phoneBookSet.addAll(getOnlyPhoneNumbers());
        providerSet.addAll(getProviderNumbers());

        int bookCount = phoneBookSet.size();
        int providerCount = providerSet.size();

        Log.e(TAG, "onChange: bookCount: " + bookCount + " providerCount: " + providerCount);

        if (bookCount > providerCount) {
            Log.i(TAG, "onChange() Insert!");
            phoneBookSet.removeAll(providerSet);
            String val = phoneBookSet.toString().replaceAll("[\\(\\)\\[\\]\\{\\}]", "");
            Log.w(TAG, "value to insert: " + val);
            //DO Insert Operations

        } else if (bookCount < providerCount) {
            Log.i(TAG, "onChange() DELETE!");
            providerSet.removeAll(phoneBookSet);
            String val = providerSet.toString().replaceAll("[\\(\\)\\[\\]\\{\\}]", "");
            Log.w(TAG, "value to delete: " + val);
            //Do Delete Operations
        } else {
            Log.i(TAG, "onChange() UPDATE!");
            Set<String> tempPhoneBookSet = new HashSet<>();
            tempPhoneBookSet.addAll(phoneBookSet);

            phoneBookSet.removeAll(providerSet);
            String newData = phoneBookSet.toString().replaceAll("[\\(\\)\\[\\]\\{\\}]", "");
            Log.e(TAG, "newData: " + newData);

            providerSet.removeAll(tempPhoneBookSet);
            String deleteData = providerSet.toString().replaceAll("[\\(\\)\\[\\]\\{\\}]", "");
            Log.e(TAG, "deleteData: " + deleteData);

            if (!newData.equals(deleteData)) {
                //DO Update Operations
            } else {
                Log.i(TAG, "onChange() Nothing to update!");
            }
        }
    } else if (!checkContactPermission()) {
        Log.e(TAG, "onChange() Contact Permission not granted!");
    } else {
        Log.e(TAG, "onChange() Time threshold not reached Or Contacts not imported yet!");
    }

}

private boolean checkContactPermission() {
    return ContextCompat.checkSelfPermission(mContextWeakReference.get(), Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
}

/**
 * Get only phone numbers from device's addressBook
 *
 * @return - Set of distinct phone numbers
 */
private Set<String> getOnlyPhoneNumbers() {
    Log.d(TAG, "getOnlyPhoneNumbers()");
    Cursor phones = mContextWeakReference.get().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " ASC");

    Set<String> uniquePhoneContacts = new HashSet<>();

    while (phones.moveToNext()) {
        String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("\\D", "");
        String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
        String photoUri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));

        if (uniquePhoneContacts.add(id + "," + name + "," + photoUri + "," + phoneNumber)) {
            Log.w(TAG, "Book#" + id + "," + name + "," + photoUri + "," + phoneNumber);
        }
    }
    phones.close();
    return uniquePhoneContacts;

}

/**
 * Get all the Contacts from provider which are not deletable
 *
 * @return - All distinct phone numbers from app's provider
 */
private Set<String> getProviderNumbers() {
    Log.d(TAG, "getProviderNumbers()");
    Cursor phones = mContextWeakReference.get().getContentResolver().query(MyContactProvider.CONTENT_URI, null, PhoneContactController.COL_IS_DELETABLE + "=?",
            new String[]{"0"}, MyContactProvider.COL_CONTACT_ID + " ASC");
    Set<String> uniquePhoneContacts = new HashSet<>();
    while (phones.moveToNext()) {
        String id = phones.getString(phones.getColumnIndex(MyContactProvider.COL_CONTACT_ID));
        String name = phones.getString(phones.getColumnIndex(MyContactProvider.COL_NAME));
        String phoneNumber = phones.getString(phones.getColumnIndex(MyContactProvider.COL_CONTACT_NO));
        String photoUri = phones.getString(phones.getColumnIndex(MyContactProvider.COL_PHOTO_URI));

        if (uniquePhoneContacts.add(id + "," + name + "," + photoUri + "," + phoneNumber)) {
            Log.w(TAG, "QueryProvider#" + id + "," + name + "," + photoUri + "," + phoneNumber);
        }
    }
    phones.close();
    return uniquePhoneContacts;
}

}

I hope this helps.


答:
Node is a class nested inside LIstTEst.

You have its definition:

```<code>static class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
    }
}
</code>```

It represents a link in a linked list. It contains a numeric value (data) and a reference to the next Node in the list.

```<code>Node head;
</code>```

is a member of the LIstTEst which refers to the first link in the list.

Note that the posted implementation of LIstTEst is lacking. It should use an add method instead of the main creating Nodes and directly manipulating the links.

Title: Difference between two lists in Java

Body:
I started learning data structures and algorithms with Java.

I started with list and the first concept which I learnt is difference between array and list.

Now in list I learn how to insert and element in to list and displaying on the screen. I got two pieces of code. The first one I understood very well; where the second one is confusing.

My confusion is what is the Node here? In the beginning we declare Node head;. So basically what is Node here?

Is it predefined datatype or something? Also, how does the second program flow? How is the second program different from the first? And what is the difference?

Also I understood that we are using util here, but still I want to know because how people use it in the industry.

The first method:

import java.util.*;

public class TestCollection7 {
    public static void main(String args[]) {

        LinkedList<String> al = new LinkedList<String>();
        al.add("Ravi");
        al.add("Vijay");
        al.add("Ravi");
        al.add("Ajay");

        Iterator<String> itr = al.iterator();
        while(itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Second method:

package javaapplication3;

public class LIstTEst {
    Node head;

    static class Node {
        int data;
        Node next;
        Node(int d) {
            data = d;
            next = null;
        }
    }

    public void PrintList() {
        Node n = head;
        while(n != null){
            System.out.print(n.data+" ");
            n = n.next;
        }
    }

    public static void main(String args[]) {
        LIstTEst llist = new LIstTEst();
        llist.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(7);

        llist.head.next = second;
        second.next = third; = third;

        llist.PrintList();
    }
}

Body:
Node is a class nested inside LIstTEst.

You have its definition:

static class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
    }
}

It represents a link in a linked list. It contains a numeric value (data) and a reference to the next Node in the list.

Node head;

is a member of the LIstTEst which refers to the first link in the list.

Note that the posted implementation of LIstTEst is lacking. It should use an add method instead of the main creating Nodes and directly manipulating the links.


问:
Jboss EAP 6.3 and Spring boot 1.5.2 - deployment starup issue with logback
Environment:
 - Spring Boot 1.5.2 (war)
 - java 1.7

 - jboss EAP 6.3

I am stuck with following error while running spring boot application war on jboss EAP:

Same issue listed here but did not mention what to do with Jboss EAP 6.3.

Appreciate your help!

17:48:22,682 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-13) MSC000001: Failed to start service jboss.deployment.unit."basp.war".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.unit."basp.war".INSTALL: JBAS018733: Failed to process phase INSTALL of deployment "basp.war"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:166) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1980) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1913) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_80]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_80]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_80]
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018104: Deployment error processing SCI for jar: logback-classic-1.1.11.jar
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:210)
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.deploy(ServletContainerInitializerDeploymentProcessor.java:131)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:159) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
    ... 5 more
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018104: Deployment error processing SCI for jar: logback-classic-1.1.11.jar
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:202)
    ... 7 more
Caused by: java.lang.ClassNotFoundException: # See javax.servlet.ServletContainerInitializer javadocs from [Module "deployment.basp.war:main" from Service Module Loader]

    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:213) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:194)
    ... 7 more

Dependencies as following:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<properties>
    <java.version>1.7</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>

            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>

        </exclusions>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>6.0</version>
    </dependency>
</dependencies>
</code>```

答: Including this and many other issues followed this I have captured into  Spring boot and Jboss Integration</p>

Body:
Environment:
 - Spring Boot 1.5.2 (war)
 - java 1.7

 - jboss EAP 6.3

I am stuck with following error while running spring boot application war on jboss EAP:

Same issue listed here but did not mention what to do with Jboss EAP 6.3.

Appreciate your help!

17:48:22,682 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-13) MSC000001: Failed to start service jboss.deployment.unit."basp.war".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.unit."basp.war".INSTALL: JBAS018733: Failed to process phase INSTALL of deployment "basp.war"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:166) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1980) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1913) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_80]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_80]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_80]
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018104: Deployment error processing SCI for jar: logback-classic-1.1.11.jar
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:210)
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.deploy(ServletContainerInitializerDeploymentProcessor.java:131)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:159) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
    ... 5 more
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018104: Deployment error processing SCI for jar: logback-classic-1.1.11.jar
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:202)
    ... 7 more
Caused by: java.lang.ClassNotFoundException: # See javax.servlet.ServletContainerInitializer javadocs from [Module "deployment.basp.war:main" from Service Module Loader]

    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:213) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:194)
    ... 7 more

Dependencies as following:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<properties>
    <java.version>1.7</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>

            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>

        </exclusions>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>6.0</version>
    </dependency>
</dependencies>


问:
Server-side events tracking with GTM
I'm looking for a way to implement server-side event tracking and link it somehow with GTM. Need to say I don't have a lot of experience with both  and all my experience is from developer-side.

When I worked with Google Analytics only to do server-side events tracking, I simply used Measurement Protocol they have.

But now it seems like just pushing events to GA is not enough to make GTM have any idea about this events. Or, at least, to have proper idea about the event.

But now the question is:

How should I notify GTM about events which is server-sided by nature in the right way? Is it possible it all?

As far as I understand, one can "push" data to "data layer" as they call it, but once again, this push can be done from client-side only. And I need to make it server-side.

答:
GTM is a client-side javascript injector. It does not have a server-side component (you could download the generated Javascript file and host in on your own server, and it would still work).

Since GTM is not a tracking tool there is usually not need to run it on the server side (if you want to send data to an external tool from your server it is usually easier to cut out the middle man).

So the only way to push serverside events to GTM would be to run a client on the server, e.g. a headless browser like phantomjs. That could load a page with the GTM code and you could automate it to execute javascript functions based on input from your server side application. While technically feasible this sounds like a horrible PITA.

Update: Google has announced a closed beta for server-side tracking, where you run a container in a cloud environment that then distributes the requests. Simo Ahava has a little info in his twitter feed: https://twitter.com/SimoAhava/status/1222459714614841346. This is not yet a production feature.

Title: Server-side events tracking with GTM


问:
Codeigniter - multiple checkbox values returns NULL
I have multiple check boxes from my View but it returns NULL value when passed to Controller.

I've searched (here, and here, and from other sites) for all possible answers to my problem but nothing helped.

Here are some of my CI codes:

Model (My_Model)

```<code>public function get_query_array($query_statement)
{
    $query = $this->db->query($query_statement);
    return $query->result();
}
</code>```

Controller (view_leave)

```<code>$data["leave_list"] = $this->My_Model->get_query_array("SELECT * FROM Leave_List WHERE Leave_Status='ACTIVE'");

$this->load->view('header_view');
$this->load->view('view_leave', $data);
$this->load->view('footer_view');
</code>```

PHP/HTML (view_leave.php)

```<code><form role="form" method="post" action="<?php echo base_url();?>index.php/home/update_leave" >
<?php
    // assign all leave data into checkboxes and will be submitted to /updated_leave
    foreach($leave_list as $row)
    {
       echo "<input type='checkbox' name='leave_types[]' value='".$row->Leave_Code."'> ".$row->Leave_Description."<br/>";
    }
?>
<input type="submit" value="Submit" name="submit_form" id="submit_form">
</form>
</code>```

Controller (update_leave)

```<code>$data = $this->input->post('leave_types');
var_dump($data);

// Here I got some errors when I checked on the boxes
// I use the code above to check if my check boxes are working
// Unfortunately, it returns a NULL value
</code>```

Why and how can I check for the checkbox values?

Please help.

Thanks!

答:
Model (My_Model)

```<code>public function get_query_array()
{
    $this->db->where('Leave_Status', 'ACTIVE');
    $query = $this->db->get('Leave_List');
    return $query->result();
}
</code>```

Controller (View_leave)

```<code>$data["leave_list"] = $this->My_Model->get_query_array();

$this->load->view('header_view');
$this->load->view('view_leave', $data);
$this->load->view('footer_view');
</code>```

PHP/HTML (view_leave.php)

```<code><?php
// assign all leave data into checkboxes and will be submitted to /updated_leave
foreach($leave_list as $row)
{
   echo "<input type='checkbox' name='leave_types[]' value='".$row->Leave_Code."' /> ".$row->Leave_Description."<br/>";
}
?>
</code>```

Controller (update_leave)

```<code>$data = $this->input->post('leave_types[]');
var_dump($data);
</code>```

Body:
I have multiple check boxes from my View but it returns NULL value when passed to Controller.

I've searched (here, and here, and from other sites) for all possible answers to my problem but nothing helped.

Here are some of my CI codes:

Model (My_Model)

public function get_query_array($query_statement)
{
    $query = $this->db->query($query_statement);
    return $query->result();
}

Controller (view_leave)

$data["leave_list"] = $this->My_Model->get_query_array("SELECT * FROM Leave_List WHERE Leave_Status='ACTIVE'");

$this->load->view('header_view');
$this->load->view('view_leave', $data);
$this->load->view('footer_view');

PHP/HTML (view_leave.php)

<form role="form" method="post" action="<?php echo base_url();?>index.php/home/update_leave" >
<?php
    // assign all leave data into checkboxes and will be submitted to /updated_leave
    foreach($leave_list as $row)
    {
       echo "<input type='checkbox' name='leave_types[]' value='".$row->Leave_Code."'> ".$row->Leave_Description."
";
    }
?>
<input type="submit" value="Submit" name="submit_form" id="submit_form">
</form>

Controller (update_leave)

$data = $this->input->post('leave_types');
var_dump($data);

// Here I got some errors when I checked on the boxes
// I use the code above to check if my check boxes are working
// Unfortunately, it returns a NULL value

Why and how can I check for the checkbox values?

Please help.

Thanks!

Body:
Model (My_Model)

public function get_query_array()
{
    $this->db->where('Leave_Status', 'ACTIVE');
    $query = $this->db->get('Leave_List');
    return $query->result();
}

Controller (View_leave)

$data["leave_list"] = $this->My_Model->get_query_array();

$this->load->view('header_view');
$this->load->view('view_leave', $data);
$this->load->view('footer_view');

PHP/HTML (view_leave.php)

<?php
// assign all leave data into checkboxes and will be submitted to /updated_leave
foreach($leave_list as $row)
{
   echo "<input type='checkbox' name='leave_types[]' value='".$row->Leave_Code."' /> ".$row->Leave_Description."<br/>";
}
?>

Controller (update_leave)

$data = $this->input->post('leave_types[]');
var_dump($data);