问:
Determining if a string is an Isogram
The Task:

Write a program that checks if a word supplied as the argument is an Isogram. An Isogram is a word in which no letter occurs more than once.

Create a method called is_isogram that takes one argument, a word to test if it's an isogram. This method should return a tuple of the word and a boolean indicating whether it is an isogram.

If the argument supplied is an empty string, return the argument and False: (argument, False). If the argument supplied is not a string, raise a TypeError with the message 'Argument should be a string'.

Example:

```<code>is_isogram("abolishment")
</code>```

Expected result:

```<code>("abolishment", True)
</code>```

The Visible test

```<code>from unittest import TestCase

class IsogramTestCases(TestCase):
  def test_checks_for_isograms(self):
    word = 'abolishment'
    self.assertEqual(
      is_isogram(word),
      (word, True),
      msg="Isogram word, '{}' not detected correctly".format(word)
    )

  def test_returns_false_for_nonisograms(self):
    word = 'alphabet'
    self.assertEqual(
      is_isogram(word),
      (word, False),
      msg="Non isogram word, '{}' falsely detected".format(word)
    )

  def test_it_only_accepts_strings(self):
    with self.assertRaises(TypeError) as context:
      is_isogram(2)
      self.assertEqual(
        'Argument should be a string',
        context.exception.message,
        'String inputs allowed only'
      )
</code>```

My Solution:

```<code>def is_isogram(word):
    if type(word) != str:
        raise TypeError('Argument should be a string')

    elif word == "":
      return (word, False)
    else:
        word = word.lower()
        for char in word:
            if word.count(char) > 1:
                return (word, False)
            else:
                return (word, True)
</code>```

But it the function refuses to pass some hidden test: What is wrong with my solution? Is there another elegant way of writing this function?

答:
I have tried in this way:

```<code>def isogram(n):
 if not isinstance(n, str):
    return n,False
 elif len(n) < 1:
    return n,False
 n = n.lower()
 if len(n) == len(set(n)):
    return n,True
 else:
    return n,False
</code>```

The second line checks if the input n is a string, if it isn't it returns    False.

The line 4 checks if the length of the input is smaller than 1, in that case the input is empty and we cannot check if it is an isogram or not.

'n = n.lower()' in line 6 assures us that the input becomes a string with lowercase letters.

In line 7 we check if the length of the input is equal to the length of the set(n). The function set() converts a collection or a sequence or an iterator object into a set. For example: set('lists') returns {'s', 't', 'l', 'i'}, as you can see the letter 's' which appears twice in 'lists', does not appear in the set. This is useful to check if the length of the set is equal to the length of the input, if there is a letter which appears twice in the input the condition is False.

I hope this explanation makes the script clear.

Title: Determining if a string is an Isogram

Body:
The Task:

Write a program that checks if a word supplied as the argument is an Isogram. An Isogram is a word in which no letter occurs more than once.

Create a method called is_isogram that takes one argument, a word to test if it's an isogram. This method should return a tuple of the word and a boolean indicating whether it is an isogram.

If the argument supplied is an empty string, return the argument and False: (argument, False). If the argument supplied is not a string, raise a TypeError with the message 'Argument should be a string'.

Example:

is_isogram("abolishment")

Expected result:

("abolishment", True)

The Visible test

from unittest import TestCase

class IsogramTestCases(TestCase):
  def test_checks_for_isograms(self):
    word = 'abolishment'
    self.assertEqual(
      is_isogram(word),
      (word, True),
      msg="Isogram word, '{}' not detected correctly".format(word)
    )

  def test_returns_false_for_nonisograms(self):
    word = 'alphabet'
    self.assertEqual(
      is_isogram(word),
      (word, False),
      msg="Non isogram word, '{}' falsely detected".format(word)
    )

  def test_it_only_accepts_strings(self):
    with self.assertRaises(TypeError) as context:
      is_isogram(2)
      self.assertEqual(
        'Argument should be a string',
        context.exception.message,
        'String inputs allowed only'
      )

My Solution:

def is_isogram(word):
    if type(word) != str:
        raise TypeError('Argument should be a string')

    elif word == "":
      return (word, False)
    else:
        word = word.lower()
        for char in word:
            if word.count(char) > 1:
                return (word, False)
            else:
                return (word, True)

But it the function refuses to pass some hidden test: What is wrong with my solution? Is there another elegant way of writing this function?

Body:
I have tried in this way:

def isogram(n):
 if not isinstance(n, str):
    return n,False
 elif len(n) < 1:
    return n,False
 n = n.lower()
 if len(n) == len(set(n)):
    return n,True
 else:
    return n,False

The second line checks if the input n is a string, if it isn't it returns    False.

The line 4 checks if the length of the input is smaller than 1, in that case the input is empty and we cannot check if it is an isogram or not.

'n = n.lower()' in line 6 assures us that the input becomes a string with lowercase letters.

In line 7 we check if the length of the input is equal to the length of the set(n). The function set() converts a collection or a sequence or an iterator object into a set. For example: set('lists') returns {'s', 't', 'l', 'i'}, as you can see the letter 's' which appears twice in 'lists', does not appear in the set. This is useful to check if the length of the set is equal to the length of the input, if there is a letter which appears twice in the input the condition is False.

I hope this explanation makes the script clear.


来源: stackexchange

问:
Ruby on Rails: Array to Hash with (key, array of values)
Lets say I have an Array of content_categories (content_categories = user.content_categories)

I now want to add every element belonging to a certain categorie to content_categories with the category as a key and the the content-item IDs as elements of a set

In PHP something like this is possible:

```<code>foreach ($content_categories as $key => $category) {
  $contentsByCategoryIDArray = Category.getContents($category[id])
  $content_categories[$key][$contentsByCategoryIDArray]
}
</code>```

Is there an easy way in rails to do this?

Greets,

Nico

答:
I'd use Enumerable#inject</p>

```<code>content_categories = content_categories_array.inject({}){ |memo, category| memo[category] = Category.get_contents(category); memo }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Lets say I have an Array of content_categories (content_categories = user.content_categories)

I now want to add every element belonging to a certain categorie to content_categories with the category as a key and the the content-item IDs as elements of a set

In PHP something like this is possible:

foreach ($content_categories as $key => $category) {
  $contentsByCategoryIDArray = Category.getContents($category[id])
  $content_categories[$key][$contentsByCategoryIDArray]
}

Is there an easy way in rails to do this?

Greets,

Nico

Body:
I'd use Enumerable#inject

content_categories = content_categories_array.inject({}){ |memo, category| memo[category] = Category.get_contents(category); memo }


问:
For loop in R return error 'object not found'
I'm learning R and have written my first for-loop. For 1000 iterations I create 4 vectors, each with the dimensions 10, 100, 1000  and 10000 elements. These so called theta1 values are not recognised. I tried running one theta1 at the time and it works but running all 4 gives the error 'object not found'. It's not obvious to me what's wrong here, can anyone explain?</p>

```<code>k=1000

'Method1'

for(i in 1:k){
  N10=runif(10)
  N100=runif(100)
  N1000=runif(1000)
  N10000=runif(10000)
  theta1_10[i]=(1/10)*4*sum(sqrt(1-N10^2))
  theta1_100[i]=(1/100)*4*sum(sqrt(1-N100^2))
  theta1_1000[i]=(1/1000)*4*sum(sqrt(1-N1000^2))
  theta1_10000[i]=(1/10000)*4*sum(sqrt(1-N10000^2))
}

'Result Method 1'
m_theta1_10 = mean(theta1_10)
sd_theta1_10 = sd(theta1_10)
m_theta1_100 = mean(theta1_100)
sd_theta1_100 = sd(theta1_100)
m_theta1_1000 = mean(theta1_1000)
sd_theta1_1000 = sd(theta1_1000)
m_theta1_10000 = mean(theta1_10000)
sd_theta1_10000 = sd(theta1_10000)
</code>```

答:
I'm writing this answer because both the question and the accepted answer (before it was edited) demonstrate bad programming style in R: They are growing a vector in a for loop. (See Circle 2 of Patrick Burns' The R Inferno.)

The effect will become clear from a simple benchmark. The task is to create a vector x which will contain the integer numbers 1 to k:

```<code>k <- 10000L
microbenchmark::microbenchmark(
  grow = {
    x <- integer(0)
    for (i in seq.int(k)) x <- c(x, i)
    x
  },
  subscript = {
    x <- integer(k)
    for (i in seq.int(k)) x[i] <- i
    x
  },
  colon_operator = {
    x <- 1L:k
    x
  },
  times = 10L
)
#Unit: microseconds
#           expr       min        lq        mean    median        uq        max neval
#           grow 93491.676 96127.568 104219.0140 97123.627 99459.343 165545.063    10
#      subscript  9067.607  9215.996   9483.0962  9551.288  9771.795   9938.307    10
# colon_operator     5.664     7.552      7.9675     8.307     8.685      9.063    10
</code>```

It's evident that even for a small vector of length 10000 appending elements is a magnitude slower than allocating the required length beforehand. The timing of the colon operator is included here to demonstrate the benefit of the built-in vectorized functions.

So both codes in question and answer need to be re-written to use subscripting in order to improve efficiency.

```<code># initialize the random number generator for reproducible results
set.seed(1234L)
# allocate memory for the vectors beforehand
theta1_10 = numeric(k)
theta1_100 = numeric(k)
theta1_1000 = numeric(k)
theta1_10000 = numeric(k)

# Method1
for(i in seq.int(k)){
  N10=runif(10)
  N100=runif(100)
  N1000=runif(1000)
  N10000=runif(10000)
  # update by subscripting
  theta1_10[i] = (1/10)*4*sum(sqrt(1-N10^2))
  theta1_100[i] = (1/100)*4*sum(sqrt(1-N100^2))
  theta1_1000[i] = (1/1000)*4*sum(sqrt(1-N1000^2))
  theta1_10000[i] = (1/10000)*4*sum(sqrt(1-N10000^2))
}
</code>```

However, the whole code can be re-written in a much more concise way:

```<code>library(data.table)
set.seed(1234)
k <- 1000L
N <- 10^(1:4)
rbindlist(
  lapply(N, function(i) {
    theta1 <- replicate(k, 4 / i * sum(sqrt(1 - runif(i)^2)))
    data.table(N = i, mean = mean(theta1), sd = sd(theta1))
  }))
#       N     mean         sd
#1:    10 3.144974 0.27238683
#2:   100 3.140716 0.09040696
#3:  1000 3.141791 0.02654225
#4: 10000 3.141585 0.00886737
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm learning R and have written my first for-loop. For 1000 iterations I create 4 vectors, each with the dimensions 10, 100, 1000  and 10000 elements. These so called theta1 values are not recognised. I tried running one theta1 at the time and it works but running all 4 gives the error 'object not found'. It's not obvious to me what's wrong here, can anyone explain?

k=1000

'Method1'

for(i in 1:k){
  N10=runif(10)
  N100=runif(100)
  N1000=runif(1000)
  N10000=runif(10000)
  theta1_10[i]=(1/10)*4*sum(sqrt(1-N10^2))
  theta1_100[i]=(1/100)*4*sum(sqrt(1-N100^2))
  theta1_1000[i]=(1/1000)*4*sum(sqrt(1-N1000^2))
  theta1_10000[i]=(1/10000)*4*sum(sqrt(1-N10000^2))
}

'Result Method 1'
m_theta1_10 = mean(theta1_10)
sd_theta1_10 = sd(theta1_10)
m_theta1_100 = mean(theta1_100)
sd_theta1_100 = sd(theta1_100)
m_theta1_1000 = mean(theta1_1000)
sd_theta1_1000 = sd(theta1_1000)
m_theta1_10000 = mean(theta1_10000)
sd_theta1_10000 = sd(theta1_10000)

Body:
I'm writing this answer because both the question and the accepted answer (before it was edited) demonstrate bad programming style in R: They are growing a vector in a for loop. (See Circle 2 of Patrick Burns' The R Inferno.)

The effect will become clear from a simple benchmark. The task is to create a vector x which will contain the integer numbers 1 to k:

k <- 10000L
microbenchmark::microbenchmark(
  grow = {
    x <- integer(0)
    for (i in seq.int(k)) x <- c(x, i)
    x
  },
  subscript = {
    x <- integer(k)
    for (i in seq.int(k)) x[i] <- i
    x
  },
  colon_operator = {
    x <- 1L:k
    x
  },
  times = 10L
)
#Unit: microseconds
#           expr       min        lq        mean    median        uq        max neval
#           grow 93491.676 96127.568 104219.0140 97123.627 99459.343 165545.063    10
#      subscript  9067.607  9215.996   9483.0962  9551.288  9771.795   9938.307    10
# colon_operator     5.664     7.552      7.9675     8.307     8.685      9.063    10

It's evident that even for a small vector of length 10000 appending elements is a magnitude slower than allocating the required length beforehand. The timing of the colon operator is included here to demonstrate the benefit of the built-in vectorized functions.

So both codes in question and answer need to be re-written to use subscripting in order to improve efficiency.

# initialize the random number generator for reproducible results
set.seed(1234L)
# allocate memory for the vectors beforehand
theta1_10 = numeric(k)
theta1_100 = numeric(k)
theta1_1000 = numeric(k)
theta1_10000 = numeric(k)

# Method1
for(i in seq.int(k)){
  N10=runif(10)
  N100=runif(100)
  N1000=runif(1000)
  N10000=runif(10000)
  # update by subscripting
  theta1_10[i] = (1/10)*4*sum(sqrt(1-N10^2))
  theta1_100[i] = (1/100)*4*sum(sqrt(1-N100^2))
  theta1_1000[i] = (1/1000)*4*sum(sqrt(1-N1000^2))
  theta1_10000[i] = (1/10000)*4*sum(sqrt(1-N10000^2))
}

However, the whole code can be re-written in a much more concise way:

library(data.table)
set.seed(1234)
k <- 1000L
N <- 10^(1:4)
rbindlist(
  lapply(N, function(i) {
    theta1 <- replicate(k, 4 / i * sum(sqrt(1 - runif(i)^2)))
    data.table(N = i, mean = mean(theta1), sd = sd(theta1))
  }))
#       N     mean         sd
#1:    10 3.144974 0.27238683
#2:   100 3.140716 0.09040696
#3:  1000 3.141791 0.02654225
#4: 10000 3.141585 0.00886737

ContentLicense: CC BY-SA 4.0


问:
Android: Unable to display JSON Data, unknown reason
There is no error in the app, the logcat also does not show anything useful, the app doesn't crash, but, it also doesn't show anything. Here is the type of JSON response I'm receiving:

```<code>{
"backdrop_path": "/mmxxEpTqVdwBlu5Pii7tbedBkPC.jpg",
"created_by": [
    {
        "id": 1216615,
        "name": "Andrew Kreisberg",
        "profile_path": "/giFmwdBAw6uwC8yeHPaW6dq6YT8.jpg"
    },
    {
        "id": 211962,
        "name": "Geoff Johns",
        "profile_path": "/xkaRZu1o1NILQ4PcRXqnjOrJ0Y0.jpg"
    }
],
"episode_run_time": [
    44
],
"first_air_date": "2014-10-07",
"genres": [
    {
        "id": 18,
        "name": "Drama"
    },
    {
        "id": 10765,
        "name": "Sci-Fi & Fantasy"
    }
],
"homepage": "http://www.cwtv.com/shows/the-flash/",
"id": 60735,
"in_production": true,
"languages": [
    "en"
],
"last_air_date": "2017-04-25",
"name": "The Flash",
"networks": [
    {
        "id": 71,
        "name": "The CW"
    }
],
"number_of_episodes": 65,
"number_of_seasons": 3,
"origin_country": [
    "US"
],
"original_language": "en",
"original_name": "The Flash",
"overview": "After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become...The Flash.",
"popularity": 50.611816,
"poster_path": "/lUFK7ElGCk9kVEryDJHICeNdmd1.jpg",
"production_companies": [
    {
        "name": "Warner Bros. Television",
        "id": 1957
    },
    {
        "name": "DC Entertainment",
        "id": 9993
    },
    {
        "name": "Berlanti Productions",
        "id": 27711
    }
],
"seasons": [
    {
        "air_date": "2016-04-19",
        "episode_count": 5,
        "id": 79954,
        "poster_path": null,
        "season_number": 0
    },
    {
        "air_date": "2014-10-07",
        "episode_count": 23,
        "id": 60523,
        "poster_path": "/hJysBrladxYuP5065vCAf91KcyB.jpg",
        "season_number": 1
    },
    {
        "air_date": "2015-10-06",
        "episode_count": 23,
        "id": 66922,
        "poster_path": "/8xWZPVX1cv9V5YD1RPeLj9QZDE9.jpg",
        "season_number": 2
    },
    {
        "air_date": "2016-10-04",
        "episode_count": 19,
        "id": 77888,
        "poster_path": "/6F8v0n37xbGY4syGcW6pRcB9BcY.jpg",
        "season_number": 3
    }
],
"status": "Returning Series",
"type": "Scripted",
"vote_average": 6.7,
"vote_count": 984
}
</code>```

Here is a screenshot of what the app is displaying:
Click here to see the image

Please note that the main poster, backdrop and all the other things including the tabLayout are a part of the MainActivity, the viewPager consists of 5 fragments of which 2 work fine in this activity; one is supposed to work and is working when I use it with another activity but doesn't work here and the other two don't work at all.

The MainActivity is able to load the data fine. Before now, I was trying to send a Bundle from this activity to the rest fragments, but out of five, three turned out to be null, the rest two are still loading the data just fine. Now, I'm using a function in MainActivity which returns the data and then am using the getActivity() method in the fragments, I know that I won't be able to use these fragments anywhere else. Now, I've checked everything and the fragments are receiving the data, but even now, they aren't displaying anything. Here is the code parsing the JSON, I'm using a recyclerView, also I'm using Volley inside AsyncTask so that the default messgaes are displayed only when everything is set:

```<code>private class connectToTheInternet extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... strings) {

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("receivedData", response);

                        try {
                            JSONObject parentObject = new JSONObject(response);
                            Log.d("receivedData", response);

                            JSONArray genreArray = parentObject.getJSONArray("genres");
                            for (int i = 0; i < genreArray.length(); i++) {
                                JSONObject tempObject = genreArray.getJSONObject(i);
                                if (i < genreArray.length() - 1) {
                                    genreCollector = genreCollector + tempObject.getString("name") + ", ";
                                } else
                                    genreCollector = genreCollector + tempObject.getString("name");
                            }
                            genre.setText(genreCollector);

                            if (genreArray.length() == 1) {
                                genreTag.setText("Genres: ");
                            } else
                                genreTag.setText("Genre: ");

                            JSONArray creatorArray = parentObject.getJSONArray("created_by");
                            for (int i = 0; i < creatorArray.length(); i++) {
                                JSONObject tempObject = creatorArray.getJSONObject(i);

                                if (i < creatorArray.length() - 1) {
                                    creatorName = creatorName + tempObject.getString("name") + ", ";
                                } else {
                                    creatorName = creatorName + tempObject.getString("name");
                                }
                            }
                            createdBy.setText(creatorName);

                            JSONArray runTimeArray = parentObject.getJSONArray("episode_run_time");
                            int arrayLength = runTimeArray.length();

                            for (int i = 0; i < runTimeArray.length(); i++) {
                                //No need for a tempObject, as the values in this array don't have a 'key'.....
                                runTimeCollector += runTimeArray.getInt(i);
                            }
                            runTimeCollector = runTimeCollector / arrayLength;
                            runtime.setText(runTimeCollector);

                            numberOfSeasons.setText(parentObject.getInt("number_of_seasons"));
                            numberOfEpisodes.setText(parentObject.getInt("number_of_episodes"));

                            lastAirDate.setText(convertDate(parentObject.getString("last_air_date")));

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), "Error Detected", Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        runTimeTag.setText("RunTime:");
        numberOfSeasonsTag.setText("Number Of Seasons:");
        numberOfEpisodesTag.setText("Number Of Episodes:");
        lastAirDateTag.setText("Last Air Date:");
        createdByTag.setText("Created By:");
        overViewTag.setText("OVERVIEW:");
    }
}
</code>```

Here is the logcat trace:

```<code>    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err: org.json.JSONException: No value for credits
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.getJSONObject(JSONObject.java:609)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at com.example.android.jsontutorial.credits$1.onResponse(credits.java:109)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at                                         com.example.android.jsontutorial.credits$1.onResponse(credits.java:103)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Looper.loop(Looper.java:154)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    04-01 09:24:09.710 1503-1682/com.example.android.jsontutorial D/Volley: [132] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] https://api.themoviedb.org/3/tv/top_rated?api_key=43630259102f25bfa2d21a3039b&language=en-US&page=1 0x89bd75e7 NORMAL 1> [lifetime=22435], [size=18147], [rc=200], [retryCount=1]
    04-01 09:36:07.024 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 5.062ms
    04-01 09:39:12.493 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 26.896ms
</code>```

Please help as I'm new and don't know what to do.....

P.S. 'Credits' is the name of another java class that is supposed to display a list of all the celebrities acting in that particular movie. This isn't supposed to hinder the functioning of the other two classes that aren't displaying any data.

答:
You are accessing credits key value which is not exiting in your json. So please try to get credits value like this, it will get credits key value if its exits in json otherwise it will skip.

if your credit value is string then please try to use like

```<code>String credit = jsonObject.optString("credits")
</code>```

if your credit value is JSONObject then please try to use like

```<code>JSONObject credit = jsonObject.optJSONObject("credits")
</code>```

if your credit value is JSONArray then please try to use like

```<code>JSONArray credit = jsonObject.optJSONArray("credits")
</code>```

Body:
There is no error in the app, the logcat also does not show anything useful, the app doesn't crash, but, it also doesn't show anything. Here is the type of JSON response I'm receiving:

{
"backdrop_path": "/mmxxEpTqVdwBlu5Pii7tbedBkPC.jpg",
"created_by": [
    {
        "id": 1216615,
        "name": "Andrew Kreisberg",
        "profile_path": "/giFmwdBAw6uwC8yeHPaW6dq6YT8.jpg"
    },
    {
        "id": 211962,
        "name": "Geoff Johns",
        "profile_path": "/xkaRZu1o1NILQ4PcRXqnjOrJ0Y0.jpg"
    }
],
"episode_run_time": [
    44
],
"first_air_date": "2014-10-07",
"genres": [
    {
        "id": 18,
        "name": "Drama"
    },
    {
        "id": 10765,
        "name": "Sci-Fi & Fantasy"
    }
],
"homepage": "http://www.cwtv.com/shows/the-flash/",
"id": 60735,
"in_production": true,
"languages": [
    "en"
],
"last_air_date": "2017-04-25",
"name": "The Flash",
"networks": [
    {
        "id": 71,
        "name": "The CW"
    }
],
"number_of_episodes": 65,
"number_of_seasons": 3,
"origin_country": [
    "US"
],
"original_language": "en",
"original_name": "The Flash",
"overview": "After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become...The Flash.",
"popularity": 50.611816,
"poster_path": "/lUFK7ElGCk9kVEryDJHICeNdmd1.jpg",
"production_companies": [
    {
        "name": "Warner Bros. Television",
        "id": 1957
    },
    {
        "name": "DC Entertainment",
        "id": 9993
    },
    {
        "name": "Berlanti Productions",
        "id": 27711
    }
],
"seasons": [
    {
        "air_date": "2016-04-19",
        "episode_count": 5,
        "id": 79954,
        "poster_path": null,
        "season_number": 0
    },
    {
        "air_date": "2014-10-07",
        "episode_count": 23,
        "id": 60523,
        "poster_path": "/hJysBrladxYuP5065vCAf91KcyB.jpg",
        "season_number": 1
    },
    {
        "air_date": "2015-10-06",
        "episode_count": 23,
        "id": 66922,
        "poster_path": "/8xWZPVX1cv9V5YD1RPeLj9QZDE9.jpg",
        "season_number": 2
    },
    {
        "air_date": "2016-10-04",
        "episode_count": 19,
        "id": 77888,
        "poster_path": "/6F8v0n37xbGY4syGcW6pRcB9BcY.jpg",
        "season_number": 3
    }
],
"status": "Returning Series",
"type": "Scripted",
"vote_average": 6.7,
"vote_count": 984
}

Here is a screenshot of what the app is displaying:
Click here to see the image

Please note that the main poster, backdrop and all the other things including the tabLayout are a part of the MainActivity, the viewPager consists of 5 fragments of which 2 work fine in this activity; one is supposed to work and is working when I use it with another activity but doesn't work here and the other two don't work at all.

The MainActivity is able to load the data fine. Before now, I was trying to send a Bundle from this activity to the rest fragments, but out of five, three turned out to be null, the rest two are still loading the data just fine. Now, I'm using a function in MainActivity which returns the data and then am using the getActivity() method in the fragments, I know that I won't be able to use these fragments anywhere else. Now, I've checked everything and the fragments are receiving the data, but even now, they aren't displaying anything. Here is the code parsing the JSON, I'm using a recyclerView, also I'm using Volley inside AsyncTask so that the default messgaes are displayed only when everything is set:

private class connectToTheInternet extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... strings) {

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("receivedData", response);

                        try {
                            JSONObject parentObject = new JSONObject(response);
                            Log.d("receivedData", response);

                            JSONArray genreArray = parentObject.getJSONArray("genres");
                            for (int i = 0; i < genreArray.length(); i++) {
                                JSONObject tempObject = genreArray.getJSONObject(i);
                                if (i < genreArray.length() - 1) {
                                    genreCollector = genreCollector + tempObject.getString("name") + ", ";
                                } else
                                    genreCollector = genreCollector + tempObject.getString("name");
                            }
                            genre.setText(genreCollector);

                            if (genreArray.length() == 1) {
                                genreTag.setText("Genres: ");
                            } else
                                genreTag.setText("Genre: ");

                            JSONArray creatorArray = parentObject.getJSONArray("created_by");
                            for (int i = 0; i < creatorArray.length(); i++) {
                                JSONObject tempObject = creatorArray.getJSONObject(i);

                                if (i < creatorArray.length() - 1) {
                                    creatorName = creatorName + tempObject.getString("name") + ", ";
                                } else {
                                    creatorName = creatorName + tempObject.getString("name");
                                }
                            }
                            createdBy.setText(creatorName);

                            JSONArray runTimeArray = parentObject.getJSONArray("episode_run_time");
                            int arrayLength = runTimeArray.length();

                            for (int i = 0; i < runTimeArray.length(); i++) {
                                //No need for a tempObject, as the values in this array don't have a 'key'.....
                                runTimeCollector += runTimeArray.getInt(i);
                            }
                            runTimeCollector = runTimeCollector / arrayLength;
                            runtime.setText(runTimeCollector);

                            numberOfSeasons.setText(parentObject.getInt("number_of_seasons"));
                            numberOfEpisodes.setText(parentObject.getInt("number_of_episodes"));

                            lastAirDate.setText(convertDate(parentObject.getString("last_air_date")));

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), "Error Detected", Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        runTimeTag.setText("RunTime:");
        numberOfSeasonsTag.setText("Number Of Seasons:");
        numberOfEpisodesTag.setText("Number Of Episodes:");
        lastAirDateTag.setText("Last Air Date:");
        createdByTag.setText("Created By:");
        overViewTag.setText("OVERVIEW:");
    }
}

Here is the logcat trace:

    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err: org.json.JSONException: No value for credits
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.getJSONObject(JSONObject.java:609)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at com.example.android.jsontutorial.credits$1.onResponse(credits.java:109)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at                                         com.example.android.jsontutorial.credits$1.onResponse(credits.java:103)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Looper.loop(Looper.java:154)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    04-01 09:24:09.710 1503-1682/com.example.android.jsontutorial D/Volley: [132] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] https://api.themoviedb.org/3/tv/top_rated?api_key=43630259102f25bfa2d21a3039b&language=en-US&page=1 0x89bd75e7 NORMAL 1> [lifetime=22435], [size=18147], [rc=200], [retryCount=1]
    04-01 09:36:07.024 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 5.062ms
    04-01 09:39:12.493 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 26.896ms

Please help as I'm new and don't know what to do.....

P.S. 'Credits' is the name of another java class that is supposed to display a list of all the celebrities acting in that particular movie. This isn't supposed to hinder the functioning of the other two classes that aren't displaying any data.

Body:
You are accessing credits key value which is not exiting in your json. So please try to get credits value like this, it will get credits key value if its exits in json otherwise it will skip.

if your credit value is string then please try to use like

String credit = jsonObject.optString("credits")

if your credit value is JSONObject then please try to use like

JSONObject credit = jsonObject.optJSONObject("credits")

if your credit value is JSONArray then please try to use like

JSONArray credit = jsonObject.optJSONArray("credits")


问:
How create spring with random port?
Spring-boot has random port generation as described here. But this example about web configuration. Is there a way to generate random port number, check that it is avalible, and reserve it for bean creation? E.g. something like that:

```<code>@Bean
public void myBean (@Value("${somePort}") String port) {
    return new MyBean(port);
}
</code>```

Please note, that spring has random properties like ${random.int} but this does not garante that port is free to use.

答:
To know if a port is available to use or not, the simple test os try to open that port and see if there is no error. If it is ok, then you are free to use it. There are several answers here in SO how to do it:

Sockets: Discover port availability using Java

If you want a random port every time, just use 0. It will use the next available port:

```<code>import java.io.IOException;
import java.net.ServerSocket;

public class DemoApplication {

    public static void main(String[] args) {
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(0);

            System.out.println(socket.getLocalPort());
            socket.accept();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null)
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}
</code>```

Title: How create spring with random port?

Body:
Spring-boot has random port generation as described here. But this example about web configuration. Is there a way to generate random port number, check that it is avalible, and reserve it for bean creation? E.g. something like that:

@Bean
public void myBean (@Value("${somePort}") String port) {
    return new MyBean(port);
}

Please note, that spring has random properties like ${random.int} but this does not garante that port is free to use.

Body:
To know if a port is available to use or not, the simple test os try to open that port and see if there is no error. If it is ok, then you are free to use it. There are several answers here in SO how to do it:

Sockets: Discover port availability using Java

If you want a random port every time, just use 0. It will use the next available port:

import java.io.IOException;
import java.net.ServerSocket;

public class DemoApplication {

    public static void main(String[] args) {
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(0);

            System.out.println(socket.getLocalPort());
            socket.accept();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null)
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}


问:
Meta data for Big and Small files in regards to Hadoop
I read about Hadoop's HDFS and came to know that hadoop is designed to process smaller number of larger sized files, rather than large number of small sized files.

The reason for this being that if there are larger number of small sized files, then Namenode's memory is quickly eaten away. I am having difficulty in understanding this argument.

Consider the following scenario:

1000 small files and each having size of 128 MB (the same block size of hdfs block).

So, this would mean 1000 entries in Namenode's memory holding this information.

Now, consider the following scenarios:

one single BIG file, who has 128 MB * 1000 block size.

Now won't Namenode have 1000 entries for this BIG single file?

Is this conclusion correct that in both these cases the Namenode would have same number of entries in memory regarding the block information of the file? If so, then how come hadoop is efficient for small number of larger sized files rather than larger number of small sized files?

Can anyone help in understanding this?

答:
Every file, directory and block in HDFS is represented as an object in
  the namenode’s memory, each of which occupies ~150 bytes.

Case 1:

```<code>Number of Files = 1000
Number of Blocks per file = 1
Total Number of Blocks = 1000 (Number of Files * Number of Blocks per file)
Total number of objects in Namenode's namespace = 2000 (Number of Files + Total Number of Blocks)
Total Namenode Memory Used = 2000 * 150 bytes
</code>```

Case 2:

```<code>Number of Files = 1
Number of Blocks per file = 1000
Total Number of Blocks = 1000 (Number of Files * Number of Blocks per file)
Total number of objects in Namenode's namespace = 1001 (Number of Files + Total Number of Blocks)
Total Namenode Memory Used = 1001 * 150 bytes
</code>```

In both the cases, the total size occupied by the data remains same. But in the first scenario 300KB of namenode's memory is used whereas only 150.15KB is used in the second scenario.

Body:
Every file, directory and block in HDFS is represented as an object in
  the namenode’s memory, each of which occupies ~150 bytes.

Case 1:

Number of Files = 1000
Number of Blocks per file = 1
Total Number of Blocks = 1000 (Number of Files * Number of Blocks per file)
Total number of objects in Namenode's namespace = 2000 (Number of Files + Total Number of Blocks)
Total Namenode Memory Used = 2000 * 150 bytes

Case 2:

Number of Files = 1
Number of Blocks per file = 1000
Total Number of Blocks = 1000 (Number of Files * Number of Blocks per file)
Total number of objects in Namenode's namespace = 1001 (Number of Files + Total Number of Blocks)
Total Namenode Memory Used = 1001 * 150 bytes

In both the cases, the total size occupied by the data remains same. But in the first scenario 300KB of namenode's memory is used whereas only 150.15KB is used in the second scenario.


问:
How to visualize heapdump?
We have developed a server using golang which will receive concurrent request and process the request(creates big object - a tree) and then send back reply. But the objects are not garbage collected. So I decided to analyze the objects that live in the memory. To start with, I wrote a simple program </p>

```<code>package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "runtime/debug"
)

func main() {
    var i_am_a int = 10
    _ = i_am_a
    func() {
        f, err := os.Create("dump")
        defer f.Close()
        if err != nil {
            panic(err)
        }
        debug.WriteHeapDump(f.Fd())
    }()

    b, err := ioutil.ReadFile("dump")
    if err != nil {
        panic(err)
    }
    fmt.Print(string(b))

}
</code>```

<p>But I couldn't understand the representaion(https://github.com/golang/go/wiki/heapdump13 - this didn't help). All I wanted is to trace back from the memory(big object) to the place(variable in go app code) which holds the root address of the object. So that I can release the reference and let GC to collect it in it's cycle. Is there a latest tool to visualize heapdump? or Is there a better approach to this problem? </p>

答:
There is, currently, no complete solution to your problem. The newest heap dump format explains that some information previously available is no longer tracked by the runtime.

Go Issue 16410 has lots of details and information on work in progress.

One tool - a work in progress - that may help is goheapdump

Title: How to visualize heapdump?

Body:
We have developed a server using golang which will receive concurrent request and process the request(creates big object - a tree) and then send back reply. But the objects are not garbage collected. So I decided to analyze the objects that live in the memory. To start with, I wrote a simple program

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "runtime/debug"
)

func main() {
    var i_am_a int = 10
    _ = i_am_a
    func() {
        f, err := os.Create("dump")
        defer f.Close()
        if err != nil {
            panic(err)
        }
        debug.WriteHeapDump(f.Fd())
    }()

    b, err := ioutil.ReadFile("dump")
    if err != nil {
        panic(err)
    }
    fmt.Print(string(b))

}

But I couldn't understand the representaion(https://github.com/golang/go/wiki/heapdump13 - this didn't help). All I wanted is to trace back from the memory(big object) to the place(variable in go app code) which holds the root address of the object. So that I can release the reference and let GC to collect it in it's cycle. Is there a latest tool to visualize heapdump? or Is there a better approach to this problem?


问:
How to find sum of files for all directories and sub directories (separately) and them sort them by size
Could you please advise me how to find the sum of all files in directories and sub directories?
I try to make this script but is not working.</p>

```<code>find . -xdev -type d  | while read l;do ls -l "$l" |
  awk '{sum+=$5}END{print sum/1024/1024 "" $l }';done | sort -k 1
</code>```

答:
The problem is which program expands which variable. You expect the shell to expand the $l in your awk-command, but the awk command is in single quotes and therefore the shell does not expand $l.

Passing $l as a variable to awk should solve your problem:

find . -xdev -type d |
while read l; do
  ls -l "$l" |
  awk -v "l=$l" ' {sum+=$5} END{print sum " " l} '
done |
sort -n
```

Body:
Could you please advise me how to find the sum of all files in directories and sub directories?
I try to make this script but is not working.

find . -xdev -type d  | while read l;do ls -l "$l" |
  awk '{sum+=$5}END{print sum/1024/1024 "" $l }';done | sort -k 1


问:
Set a certain area of a canvas to be clickable
I need an example of this:
I have a canvas. And it refreshes constantly, I want to make an area of this canvas clickable, like a certain rectangular area of the canvas clickable, but not the whole canvas.</p>

答:
One simple way to do it is to add transparent button, where you want the "background" to be clickable: </p>

```<code>import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class APanel extends JPanel{

    APanel(){
        setPreferredSize(new Dimension(600,400));
        setBackground(Color.YELLOW); //panel color to make it distinct

        //add button
        JButton btn = new JButton();
        btn.setPreferredSize(new Dimension(100,30)); //use layout manager to place it where you want
        btn.setContentAreaFilled(false);//make btn transparent
        btn.setCursor(new Cursor(Cursor.HAND_CURSOR));//change button cursor
        //optionally : remove border by btn.setBorder(null);

        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("button pressed !");
            }
        });
        add(btn);
    }

    public static void main(String[] args){

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        JPanel panel = new APanel();
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}
</code>```

Body:
One simple way to do it is to add transparent button, where you want the "background" to be clickable:

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class APanel extends JPanel{

    APanel(){
        setPreferredSize(new Dimension(600,400));
        setBackground(Color.YELLOW); //panel color to make it distinct

        //add button
        JButton btn = new JButton();
        btn.setPreferredSize(new Dimension(100,30)); //use layout manager to place it where you want
        btn.setContentAreaFilled(false);//make btn transparent
        btn.setCursor(new Cursor(Cursor.HAND_CURSOR));//change button cursor
        //optionally : remove border by btn.setBorder(null);

        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("button pressed !");
            }
        });
        add(btn);
    }

    public static void main(String[] args){

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        JPanel panel = new APanel();
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}


问:
How to delete the item on the click of the button in every item?
I'm new to Html and ASP.Net MVC.

I want to make the view looks like this:

each item will be deleted when each button is on click

And here are my simple codes

```<code>@using ControllerPractice.Models
@model IEnumerable<Table>

@{
    ViewBag.Title = "Index";
}

<h2>Index , Data amounts @Model.Count()</h2>
<ul>
    @foreach (var t in Model)
    {
        <li><h2>@t.Title</h2></li>
        <li>@t.Text</li>
        using (Html.BeginForm("Delete", "Home"))
        {
            <input type="hidden" name="Id" value=@t.Id />
            <input type="submit" value="Delete" />
        }
    }
</ul>

<div>
    @using (Html.BeginForm("Post", "Home"))
    {
        <p>
            Title: <input type="text" name="Title">
            Content: <input type="text" name="Text">
            <input type="submit" value="Submit">
        </p>
    }
</div>
<div>

</div>
</code>```

and my API

```<code>[HttpPost]
        public ActionResult Delete(int? Id)
        {
            db.Table.Remove(db.Table.Find(Id));
            db.SaveChanges();
            return View("Index", db.Table.ToList());
        }
</code>```

I'm wondering is there any better solution instead of using  <input type="hidden" / > ?

  Or how to put the form outside of the 'ul' tag ?

  Please improve my codes , thanks.

答:
You use HttpPost for Delete method, so there is nothing wrong when using hidden field to store submit parameters.
But you could move the form to outside of the 'ul' tag by updating your code like this.

Razor code

```<code><h2>Index , Data amounts @Model.Count()</h2>
using (Html.BeginForm("Delete", "Home"))
{
    <ul>
        @foreach (var t in Model)
        {
            <li><h2>@t.Title</h2></li>
            <li>@t.Text</li>
                <input type="hidden" name="Id" value="" />
                <input type="submit" value="Delete" onclick="setDeletedId('@t.Id')" />
        }
    </ul>
}
</code>```

Javascript

```<code>function setDeletedId(deletedId) {
   var hidden = document.getElementById("Id");
   hidden.value = deletedId;
}
</code>```

Another method is updating your Delete method to HttpGet and using Html.ActionLink

Razor code

```<code><h2>Index , Data amounts @Model.Count()</h2>
<ul>
    @foreach (var t in Model)
    {
        <li><h2>@t.Title</h2></li>
        <li>@t.Text</li>
        <%=Html.ActionLink("Delete", "Delete", "Home", new {id = "@t.Id"}, null)%>
    }
</ul>
</code>```

Controller

```<code>[HttpGet]
public ActionResult Delete(int? Id)
{
    db.Table.Remove(db.Table.Find(Id));
    db.SaveChanges();
    return View("Index", db.Table.ToList());
}
</code>```

Body:
I'm new to Html and ASP.Net MVC.

I want to make the view looks like this:

each item will be deleted when each button is on click

And here are my simple codes

@using ControllerPractice.Models
@model IEnumerable

@{
    ViewBag.Title = "Index";
}

Index , Data amounts @Model.Count()

    @foreach (var t in Model)
    {

@t.Title

@t.Text

        using (Html.BeginForm("Delete", "Home"))
        {
            <input type="hidden" name="Id" value=@t.Id />
            <input type="submit" value="Delete" />
        }
    }

    @using (Html.BeginForm("Post", "Home"))
    {

            Title: <input type="text" name="Title">
            Content: <input type="text" name="Text">
            <input type="submit" value="Submit">

    }

and my API

[HttpPost]
        public ActionResult Delete(int? Id)
        {
            db.Table.Remove(db.Table.Find(Id));
            db.SaveChanges();
            return View("Index", db.Table.ToList());
        }

I'm wondering is there any better solution instead of using  <input type="hidden" / > ?

  Or how to put the form outside of the 'ul' tag ?

  Please improve my codes , thanks.

Body:
You use HttpPost for Delete method, so there is nothing wrong when using hidden field to store submit parameters.
But you could move the form to outside of the 'ul' tag by updating your code like this.

Razor code

<h2>Index , Data amounts @Model.Count()</h2>
using (Html.BeginForm("Delete", "Home"))
{
    <ul>
        @foreach (var t in Model)
        {
            <li><h2>@t.Title</h2></li>
            <li>@t.Text</li>
                <input type="hidden" name="Id" value="" />
                <input type="submit" value="Delete" onclick="setDeletedId('@t.Id')" />
        }
    </ul>
}

Javascript

function setDeletedId(deletedId) {
   var hidden = document.getElementById("Id");
   hidden.value = deletedId;
}

Another method is updating your Delete method to HttpGet and using Html.ActionLink

Razor code

<h2>Index , Data amounts @Model.Count()</h2>
<ul>
    @foreach (var t in Model)
    {
        <li><h2>@t.Title</h2></li>
        <li>@t.Text</li>
        <%=Html.ActionLink("Delete", "Delete", "Home", new {id = "@t.Id"}, null)%>
    }
</ul>

Controller

[HttpGet]
public ActionResult Delete(int? Id)
{
    db.Table.Remove(db.Table.Find(Id));
    db.SaveChanges();
    return View("Index", db.Table.ToList());
}


问:
MEF CompositionException
I have the CompositionException exception with this message:
"The ComposablePart of type 'SomeService' cannot be recomposed because it is in an invalid state. It can only be recomposed if it has already been fully previewed or composed."

Exception is thrown by this code:

```<code>public class SomeService : ISomeService
{
   [Import(typeof(ISomeType))]
   public ISomeType SomeType { get; set; }

   public SomeService()
   {
      Container.ComposeParts(this);
   }
}
</code>```

but everything fine with this:

```<code>public class SomeService : ISomeService
{
   [Import(typeof(ISomeType))]
   public ISomeType SomeType { get; set; }

   public SomeService()
   {
      this.SomeType = Container.GetExportedValue<ISomeType>();
   }
}
</code>```

I have this code "Container.ComposeParts(this)" in other places and it works but here it doesn't.

I didn't found nothing interesting after googling with "cannot be recomposed because it is in an invalid state".

What does this message mean?
Thank you!

答: This might be because you are using the CompositionContainer from multiple threads.  Are you diong that?</p>

Title: MEF CompositionException

Body:
I have the CompositionException exception with this message:
"The ComposablePart of type 'SomeService' cannot be recomposed because it is in an invalid state. It can only be recomposed if it has already been fully previewed or composed."

Exception is thrown by this code:

public class SomeService : ISomeService
{
   [Import(typeof(ISomeType))]
   public ISomeType SomeType { get; set; }

   public SomeService()
   {
      Container.ComposeParts(this);
   }
}

but everything fine with this:

public class SomeService : ISomeService
{
   [Import(typeof(ISomeType))]
   public ISomeType SomeType { get; set; }

   public SomeService()
   {
      this.SomeType = Container.GetExportedValue<ISomeType>();
   }
}

I have this code "Container.ComposeParts(this)" in other places and it works but here it doesn't.

I didn't found nothing interesting after googling with "cannot be recomposed because it is in an invalid state".

What does this message mean?
Thank you!


问:
How to initialize a 2d array and how to access it from a main method in java?
The 2d array created overwrites the previously created 2d array each time the loop continues, how can I create a seperate 2d array and access/change it in the way listed below.

I'm currently a highschool student taking an online computer sciences course and would like to improve my efficiency with coding and get some tips on bad habbits I have. Here is my program:

```<code>import java.util.Arrays;
import java.util.Scanner;

public class FundRaising
{

    public static void main(String[] args)
    {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Would you like to input donation information regarding the selected schools?\n0 - Yes\n1 - No"); //runs the program or ends the program
        Integer loop = scanner.nextInt();

        while (loop == 0) //while the user would like to run the program, the code will look
            {
            if (loop == 0) //continues if the user would like to continue
                {
                System.out.println("Which school is fundraising?\n0 - Central\n1 - Holy Cross\n2 - John Paul II\n3 - Teresa\n4 - Regina\n5 - Joeseph\n6 - Mary\n7 - Thomas Aquinas");
                Integer school = scanner.nextInt(); //asks which school information will be input for

                System.out.println("Amount donated?\n0 - 25 cents\n1 - 50 cents\n2 - 1 dollar\n3 - 2 dollars");
                Integer donation = scanner.nextInt(); //asks the amount donated

                System.out.println("School population?");
                Integer population = scanner.nextInt(); //asks the population of the school

                if (donation == 0) //if the first donation amount is selected then this selection will be used
                    {
                    double schoolTotal = 0.25*population; //the donation amount times the population gives the total for the school selected
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total"); //prints out headers for the 2d array

                    int rows = 4; //set the initial size of the 2d array according to schools and donations
                    int columns = 10;
                    double totals [][] = new double [rows][columns]; //initialize the 2d array
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5; //set various positions on the 2d array to equal the donation amounts
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal; //set the positions corredsponding to the input school and donation in order to create a "total" column on the 2d array
                    totals[donation][9] = totals[0][0]+totals[0][1]+totals[0][2]+totals[0][3]+totals[0][4]+totals[0][5]+totals[0][6]+totals[0][7]; //the sums of everything in the row is used to find a value for the total column

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9]; //adds the total for each school in the total column to create a final total for donations

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n ")); //prints out the 2d array with slight modifications for easier viewing
                    System.out.println("\nTotals donations:" + finalDonations +""); //prints the total amount of donations to the user

                    }

                if (donation == 1) //each subsequence if statement is used if the donation amount differs (4 different donations amounts, 25 cents, 50 cents, 1 dollar and 2 dollars
                    { //remainder of code is drycut paste with small modifications to adjust for differing donation amount
                    double schoolTotal = 0.50*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[1][0]+totals[1][1]+totals[1][2]+totals[1][3]+totals[1][4]+totals[1][5]+totals[1][6]+totals[1][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                if (donation == 2)
                    {
                    double schoolTotal = 1.00*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[2][0]+totals[2][1]+totals[2][2]+totals[2][3]+totals[2][4]+totals[2][5]+totals[2][6]+totals[2][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                if (donation == 3)
                    {
                    double schoolTotal = 2.00*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[3][0]+totals[3][1]+totals[3][2]+totals[3][3]+totals[3][4]+totals[3][5]+totals[3][6]+totals[3][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                }

            else //if the user did not chose to run the program this message is displayed
                {
                        System.out.println("You did not not choose to input information");
                }

            }

    }
}
</code>```

答: Consider using Collections instead of arrays for manipulating data like this. E.g. a Map<String, Integer> for working with different donation sources and values

Body:
The 2d array created overwrites the previously created 2d array each time the loop continues, how can I create a seperate 2d array and access/change it in the way listed below.

I'm currently a highschool student taking an online computer sciences course and would like to improve my efficiency with coding and get some tips on bad habbits I have. Here is my program:

import java.util.Arrays;
import java.util.Scanner;

public class FundRaising
{

    public static void main(String[] args)
    {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Would you like to input donation information regarding the selected schools?\n0 - Yes\n1 - No"); //runs the program or ends the program
        Integer loop = scanner.nextInt();

        while (loop == 0) //while the user would like to run the program, the code will look
            {
            if (loop == 0) //continues if the user would like to continue
                {
                System.out.println("Which school is fundraising?\n0 - Central\n1 - Holy Cross\n2 - John Paul II\n3 - Teresa\n4 - Regina\n5 - Joeseph\n6 - Mary\n7 - Thomas Aquinas");
                Integer school = scanner.nextInt(); //asks which school information will be input for

                System.out.println("Amount donated?\n0 - 25 cents\n1 - 50 cents\n2 - 1 dollar\n3 - 2 dollars");
                Integer donation = scanner.nextInt(); //asks the amount donated

                System.out.println("School population?");
                Integer population = scanner.nextInt(); //asks the population of the school

                if (donation == 0) //if the first donation amount is selected then this selection will be used
                    {
                    double schoolTotal = 0.25*population; //the donation amount times the population gives the total for the school selected
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total"); //prints out headers for the 2d array

                    int rows = 4; //set the initial size of the 2d array according to schools and donations
                    int columns = 10;
                    double totals [][] = new double [rows][columns]; //initialize the 2d array
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5; //set various positions on the 2d array to equal the donation amounts
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal; //set the positions corredsponding to the input school and donation in order to create a "total" column on the 2d array
                    totals[donation][9] = totals[0][0]+totals[0][1]+totals[0][2]+totals[0][3]+totals[0][4]+totals[0][5]+totals[0][6]+totals[0][7]; //the sums of everything in the row is used to find a value for the total column

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9]; //adds the total for each school in the total column to create a final total for donations

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n ")); //prints out the 2d array with slight modifications for easier viewing
                    System.out.println("\nTotals donations:" + finalDonations +""); //prints the total amount of donations to the user

                    }

                if (donation == 1) //each subsequence if statement is used if the donation amount differs (4 different donations amounts, 25 cents, 50 cents, 1 dollar and 2 dollars
                    { //remainder of code is drycut paste with small modifications to adjust for differing donation amount
                    double schoolTotal = 0.50*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[1][0]+totals[1][1]+totals[1][2]+totals[1][3]+totals[1][4]+totals[1][5]+totals[1][6]+totals[1][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                if (donation == 2)
                    {
                    double schoolTotal = 1.00*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[2][0]+totals[2][1]+totals[2][2]+totals[2][3]+totals[2][4]+totals[2][5]+totals[2][6]+totals[2][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                if (donation == 3)
                    {
                    double schoolTotal = 2.00*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[3][0]+totals[3][1]+totals[3][2]+totals[3][3]+totals[3][4]+totals[3][5]+totals[3][6]+totals[3][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                }

            else //if the user did not chose to run the program this message is displayed
                {
                        System.out.println("You did not not choose to input information");
                }

            }

    }
}


问:
How to update a document in documentdb using linq
My json document is like the one mentioned below

```<code>{
"HotelCriteria": {
    "HotelCode": "101671",
    "HotelName": "TestTulip Inn"
},
"RoomTypes": {
    "RoomTypeList": [
        {
            "InvTypeCode": "DLX",
            "Name": "Deluxe",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 16,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        },
        {
            "InvTypeCode": "SUIR",
            "Name": "Suite Room",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 2,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        },
        {
            "InvTypeCode": "SUP",
            "Name": "Superior",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 35,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        }
    ]
},
"id": "ee24e984-a73b-4d22-bc9c-7cf71374362f",
}
</code>```

At later stage i want to update the field Availability to 1 in the above json . How to do using linq?

My sample c# code

```<code>public class HotelCriteria
    {
        public string HotelCode { get; set; }
        public string HotelName { get; set; }
    }
   public class RoomTypeList
    {
        public string InvTypeCode { get; set; }
        public string Name { get; set; }
        public int BaseOccupancy { get; set; }
        public int MaxOccupancy { get; set; }
        public int Quantity { get; set; }
        public int IsRoomActive { get; set; }
        public string RoomDescription { get; set; }
        public int Availability { get; set; }
    }

      public class RoomTypes
    {
        public List<RoomTypeList> RoomTypeList { get; set; }
    }

public class monthwiseinsert
    {
        public HotelCriteria HotelCriteria { get; set; }
        public RoomTypes RoomTypes { get; set; }
    }
</code>```

The method which is used to create the document (This is created from other documents which i have in my collection):

```<code>public IHttpActionResult InventoryInsertDate()
    {
        Database database = GetDatabase("xyz").Result;
        DocumentCollection collection = GetCollection(database, "xyzCollection").Result;
        List<monthwiseinsert> roomtypeavail = new List<monthwiseinsert>();

        var Hotelwithroomtype = (client.CreateDocumentQuery<monthwiseinsert>(collection.SelfLink).Where(x=>x.HotelCriteria.HotelName!=null)
                   ).ToList();
        foreach(var item in Hotelwithroomtype)
        {
            client.CreateDocumentAsync(collection.SelfLink, item);

        }

        return Json("OK");
    }
</code>```

答: And pay attention the ID field must be "id" - lower case.</p>

Body:
My json document is like the one mentioned below

{
"HotelCriteria": {
    "HotelCode": "101671",
    "HotelName": "TestTulip Inn"
},
"RoomTypes": {
    "RoomTypeList": [
        {
            "InvTypeCode": "DLX",
            "Name": "Deluxe",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 16,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        },
        {
            "InvTypeCode": "SUIR",
            "Name": "Suite Room",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 2,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        },
        {
            "InvTypeCode": "SUP",
            "Name": "Superior",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 35,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        }
    ]
},
"id": "ee24e984-a73b-4d22-bc9c-7cf71374362f",
}

At later stage i want to update the field Availability to 1 in the above json . How to do using linq?

My sample c# code

public class HotelCriteria
    {
        public string HotelCode { get; set; }
        public string HotelName { get; set; }
    }
   public class RoomTypeList
    {
        public string InvTypeCode { get; set; }
        public string Name { get; set; }
        public int BaseOccupancy { get; set; }
        public int MaxOccupancy { get; set; }
        public int Quantity { get; set; }
        public int IsRoomActive { get; set; }
        public string RoomDescription { get; set; }
        public int Availability { get; set; }
    }

      public class RoomTypes
    {
        public List<RoomTypeList> RoomTypeList { get; set; }
    }

public class monthwiseinsert
    {
        public HotelCriteria HotelCriteria { get; set; }
        public RoomTypes RoomTypes { get; set; }
    }

The method which is used to create the document (This is created from other documents which i have in my collection):

public IHttpActionResult InventoryInsertDate()
    {
        Database database = GetDatabase("xyz").Result;
        DocumentCollection collection = GetCollection(database, "xyzCollection").Result;
        List<monthwiseinsert> roomtypeavail = new List<monthwiseinsert>();

        var Hotelwithroomtype = (client.CreateDocumentQuery<monthwiseinsert>(collection.SelfLink).Where(x=>x.HotelCriteria.HotelName!=null)
                   ).ToList();
        foreach(var item in Hotelwithroomtype)
        {
            client.CreateDocumentAsync(collection.SelfLink, item);

        }

        return Json("OK");
    }


问:
PHP in userdir not working
My /etc/apache2/mods-enabled/userdir.conf file looks like:

```<code><IfModule mod_userdir.c>
        UserDir /var/zpanel/hostdata/*/public_html/
        UserDir disabled root

        <Directory /var/zpanel/hostdata/*/public_html/*>
                AllowOverride All
                Options MultiViews Indexes SymLinksIfOwnerMatch
                <Limit GET POST OPTIONS>
                        # Apache <= 2.2:
                        Order allow,deny
                        Allow from all

                        # Apache >= 2.4:
                        # Require all granted
                </Limit>
                <LimitExcept GET POST OPTIONS>
                        # Apache <= 2.2:
                        Order deny,allow
                        Deny from all

                        # Apache >= 2.4:
                        #Require all denied
                </LimitExcept>
        </Directory>
</IfModule>
</code>```

And file /etc/apache2/mods-enabled/php5.conf

```<code><FilesMatch ".+\.ph(p[345]?|t|tml)$">
    SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch ".+\.phps$">
    SetHandler application/x-httpd-php-source
    # Deny access to raw php sources by default
    # To re-enable it's recommended to enable access to the files
    # only in specific virtual host or directory
   Require all denied
</FilesMatch>
# Deny access to files without filename (e.g. '.php')
<FilesMatch "^\.ph(p[345]?|t|tml|ps)$">
    Require all denied
</FilesMatch>

# Running PHP scripts in user directories is disabled by default
#
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.

#<IfModule mod_userdir.c>
#    <Directory /var/zpanel/hostdata/*/public_html/*>
#        php_admin_value engine On
#    </Directory>
#</IfModule>
</code>```

But php not working when in accessing web site via userdir.
www.example.com/~admin
When i access via domain then it works. I have zPanel installed

Server version: Apache/2.4.18 (Ubuntu)

答:
Try the following actions:

Make sure mod_userdir is enabled (a2enmod userdir).

The $HOME and public_html dirs have the right read permissions.

```<code>sudo -Hu SOMEUSER sh -c 'chmod 755 $HOME $HOME/public_html'
</code>```

Make sure php_admin_value engine is On.

```<code>sudo vim /etc/apache2/mods-enabled/php*.conf
</code>```

Then find the line containing php_admin_flag and change it to:

```<code>php_admin_flag engine On
</code>```

This is due that PHP is disabled by default for user dirs for Apache 2.

In your particular case, you've to uncomment the following lines:

```<code><IfModule mod_userdir.c>
    <Directory /var/zpanel/hostdata/*/public_html/*>
        php_admin_value engine On
    </Directory>
</IfModule>
</code>```

Title: PHP in userdir not working

Body:
My /etc/apache2/mods-enabled/userdir.conf file looks like:

<IfModule mod_userdir.c>
        UserDir /var/zpanel/hostdata/*/public_html/
        UserDir disabled root

        <Directory /var/zpanel/hostdata/*/public_html/*>
                AllowOverride All
                Options MultiViews Indexes SymLinksIfOwnerMatch
                <Limit GET POST OPTIONS>
                        # Apache <= 2.2:
                        Order allow,deny
                        Allow from all

                        # Apache >= 2.4:
                        # Require all granted
                </Limit>
                <LimitExcept GET POST OPTIONS>
                        # Apache <= 2.2:
                        Order deny,allow
                        Deny from all

                        # Apache >= 2.4:
                        #Require all denied
                </LimitExcept>
        </Directory>
</IfModule>

And file /etc/apache2/mods-enabled/php5.conf

<FilesMatch ".+\.ph(p[345]?|t|tml)$">
    SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch ".+\.phps$">
    SetHandler application/x-httpd-php-source
    # Deny access to raw php sources by default
    # To re-enable it's recommended to enable access to the files
    # only in specific virtual host or directory
   Require all denied
</FilesMatch>
# Deny access to files without filename (e.g. '.php')
<FilesMatch "^\.ph(p[345]?|t|tml|ps)$">
    Require all denied
</FilesMatch>

# Running PHP scripts in user directories is disabled by default
#
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.

#<IfModule mod_userdir.c>
#    <Directory /var/zpanel/hostdata/*/public_html/*>
#        php_admin_value engine On
#    </Directory>
#</IfModule>

But php not working when in accessing web site via userdir.
www.example.com/~admin
When i access via domain then it works. I have zPanel installed

Server version: Apache/2.4.18 (Ubuntu)

Body:
Try the following actions:

Make sure mod_userdir is enabled (a2enmod userdir).

The $HOME and public_html dirs have the right read permissions.

sudo -Hu SOMEUSER sh -c 'chmod 755 $HOME $HOME/public_html'

Make sure php_admin_value engine is On.

sudo vim /etc/apache2/mods-enabled/php*.conf

Then find the line containing php_admin_flag and change it to:

php_admin_flag engine On

This is due that PHP is disabled by default for user dirs for Apache 2.

In your particular case, you've to uncomment the following lines:

<IfModule mod_userdir.c>
    <Directory /var/zpanel/hostdata/*/public_html/*>
        php_admin_value engine On
    </Directory>
</IfModule>


问:
Looping over child selectors
greetings,
I have a div wrapped around a bunch of checkboxes on my form.

```<code><div id="checker">
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
</div>
</code>```

... where "dynamic" (above) is coming from a database and I don't know the names or ids.  These would be created in a loop of php code - not shown.

Using JQuery, how do I access these checkboxes, so I can loop over them?  I'd like to do something like:

```<code>$('#checker').children('checkbox').each( function(){ .... });
</code>```

(I know that is wrong - it's just to show what I'm thinking).

Thoughts?  Thanks
JohnC

答:
Try this:</p>

```<code>$('#checker input:checkbox').each(function(){
    //do stuff
});
</code>```

Title: Looping over child selectors

Body:
greetings,
I have a div wrapped around a bunch of checkboxes on my form.

  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />

... where "dynamic" (above) is coming from a database and I don't know the names or ids.  These would be created in a loop of php code - not shown.

Using JQuery, how do I access these checkboxes, so I can loop over them?  I'd like to do something like:

$('#checker').children('checkbox').each( function(){ .... });

(I know that is wrong - it's just to show what I'm thinking).

Thoughts?  Thanks
JohnC

Body:
Try this:

$('#checker input:checkbox').each(function(){
    //do stuff
});


问:
Resolve multiple promises and send angular 2 http request
I need to fetch two things from my storage, which gives me two Promises. Next up, I need to use these two promises to compose an angular 2 HTTP request. But I cant figure out a way to correctly compose these steps. I always end up with an Observable<Observable<Response>>.

```<code>    let tokenPromise = this.getToken()
    let registrationTokenPromise = this.getRegistrationToken()

    Observable.zip(
        tokenPromise,
        registrationTokenPromise,
        (token, registrationToken) => {
            let headers = this.headers(token)
            return this.http.post(`${this.apiBase}/users/registration-token`,
                { registration_token: registrationToken },
                headers
            )
        })
</code>```

How can I correctly solve this to receive an Observable<Response>?

答:
You are getting an Observable<Observable<Response>> because Observable.zip returns an Observable and the http.post returns an Observable.  In order to unwrap one of the observables, you will need to subscribe to the Observable.zip

```<code>Observable.zip(
        tokenPromise,
        registrationTokenPromise,
        (token, registrationToken) => {
            let headers = this.headers(token)
            return this.http.post(`${this.apiBase}/users/registration-token`,
                { registration_token: registrationToken },
                headers
            )
        })
        .subscribe(response => {
           //do something with response
        })
</code>```

Body:
I need to fetch two things from my storage, which gives me two Promises. Next up, I need to use these two promises to compose an angular 2 HTTP request. But I cant figure out a way to correctly compose these steps. I always end up with an Observable<Observable<Response>>.

    let tokenPromise = this.getToken()
    let registrationTokenPromise = this.getRegistrationToken()

    Observable.zip(
        tokenPromise,
        registrationTokenPromise,
        (token, registrationToken) => {
            let headers = this.headers(token)
            return this.http.post(`${this.apiBase}/users/registration-token`,
                { registration_token: registrationToken },
                headers
            )
        })

How can I correctly solve this to receive an Observable<Response>?

Body:
You are getting an Observable<Observable<Response>> because Observable.zip returns an Observable and the http.post returns an Observable.  In order to unwrap one of the observables, you will need to subscribe to the Observable.zip

Observable.zip(
        tokenPromise,
        registrationTokenPromise,
        (token, registrationToken) => {
            let headers = this.headers(token)
            return this.http.post(`${this.apiBase}/users/registration-token`,
                { registration_token: registrationToken },
                headers
            )
        })
        .subscribe(response => {
           //do something with response
        })


问:
Named tuple and default values for optional keyword arguments
I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this:

```<code>class Node(object):
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
</code>```

After conversion to namedtuple it looks like:

```<code>from collections import namedtuple
Node = namedtuple('Node', 'val left right')
</code>```

But there is a problem here. My original class allowed me to pass in just a value and took care of the default by using default values for the named/keyword arguments. Something like:

```<code>class BinaryTree(object):
    def __init__(self, val):
        self.root = Node(val)
</code>```

But this doesn't work in the case of my refactored named tuple since it expects me to pass all the fields. I can of course replace the occurrences of Node(val) to Node(val, None, None) but it isn't to my liking.

So does there exist a good trick which can make my re-write successful without adding a lot of code complexity (metaprogramming) or should I just swallow the pill and go ahead with the "search and replace"? :)

答:
With typing.NamedTuple in Python 3.6.1+ you can provide both a default value and a type annotation to a NamedTuple field. Use typing.Any if you only need the former:

```<code>from typing import Any, NamedTuple

class Node(NamedTuple):
    val: Any
    left: 'Node' = None
    right: 'Node' = None
</code>```

Usage:

```<code>>>> Node(1)
Node(val=1, left=None, right=None)
>>> n = Node(1)
>>> Node(2, left=n)
Node(val=2, left=Node(val=1, left=None, right=None), right=None)
</code>```

Also, in case you need both default values and optional mutability, Python 3.7 is going to have data classes (PEP 557) that can in some (many?) cases replace namedtuples.

Sidenote: one quirk of the current specification of annotations (expressions after : for parameters and variables and after -> for functions) in Python is that they are evaluated at definition time*. So, since "class names become defined once the entire body of the class has been executed", the annotations for 'Node' in the class fields above must be strings to avoid NameError.

This kind of type hints is called "forward reference" ([1], [2]), and with PEP 563 Python 3.7+ is going to have a __future__ import (to be enabled by default in 4.0) that will allow to use forward references without quotes, postponing their evaluation.

* AFAICT only local variable annotations are not evaluated at runtime. (source: PEP 526)

Body:
I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this:

class Node(object):
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

After conversion to namedtuple it looks like:

from collections import namedtuple
Node = namedtuple('Node', 'val left right')

But there is a problem here. My original class allowed me to pass in just a value and took care of the default by using default values for the named/keyword arguments. Something like:

class BinaryTree(object):
    def __init__(self, val):
        self.root = Node(val)

But this doesn't work in the case of my refactored named tuple since it expects me to pass all the fields. I can of course replace the occurrences of Node(val) to Node(val, None, None) but it isn't to my liking.

So does there exist a good trick which can make my re-write successful without adding a lot of code complexity (metaprogramming) or should I just swallow the pill and go ahead with the "search and replace"? :)

Body:
With typing.NamedTuple in Python 3.6.1+ you can provide both a default value and a type annotation to a NamedTuple field. Use typing.Any if you only need the former:

from typing import Any, NamedTuple

class Node(NamedTuple):
    val: Any
    left: 'Node' = None
    right: 'Node' = None

Usage:

>>> Node(1)
Node(val=1, left=None, right=None)
>>> n = Node(1)
>>> Node(2, left=n)
Node(val=2, left=Node(val=1, left=None, right=None), right=None)

Also, in case you need both default values and optional mutability, Python 3.7 is going to have data classes (PEP 557) that can in some (many?) cases replace namedtuples.

Sidenote: one quirk of the current specification of annotations (expressions after : for parameters and variables and after -> for functions) in Python is that they are evaluated at definition time*. So, since "class names become defined once the entire body of the class has been executed", the annotations for 'Node' in the class fields above must be strings to avoid NameError.

This kind of type hints is called "forward reference" ([1], [2]), and with PEP 563 Python 3.7+ is going to have a __future__ import (to be enabled by default in 4.0) that will allow to use forward references without quotes, postponing their evaluation.

* AFAICT only local variable annotations are not evaluated at runtime. (source: PEP 526)


问:
how to redirect all users coming from all other sites when referral
hello im looking to show a message to users when they come on my page from different sites https sites or http can someone help me to redirect users coming from all sites example if they have referral different sites with https or http referrals, this is working only from http referrals</p>

```<code><?php
$pos = (strpos($_SERVER['HTTP_REFERER'], 'http'));
if($pos===false)
  die('<h1>Restricted access</h1>');
else
{echo '<h1>It Works</h1>';}

?>
</code>```

答:
You can use this to detect whether the referral URL was http://

```<code><?php

if(strstr($_SERVER['HTTP_REFERER'], 'http://')) {
  die('<h1>Restricted access</h1>');
} else {
    echo '<h1>It Works</h1>';
}

?>
</code>```

If you just want to check whether the user clicked a link from another site to arrive at yours then you can check whether $_SERVER['HTTP_REFERER'] exists:

You can use this to detect whether the referral URL was http://

```<code><?php

if($_SERVER['HTTP_REFERER']) {
  die('<h1>Restricted access</h1>');
} else {
    echo '<h1>It Works</h1>';
}

?>
</code>```

Body:
hello im looking to show a message to users when they come on my page from different sites https sites or http can someone help me to redirect users coming from all sites example if they have referral different sites with https or http referrals, this is working only from http referrals

<?php
$pos = (strpos($_SERVER['HTTP_REFERER'], 'http'));
if($pos===false)
  die('
Restricted access
');
else
{echo '
It Works
';}

?>

Body:
You can use this to detect whether the referral URL was http://

<?php

if(strstr($_SERVER['HTTP_REFERER'], 'http://')) {
  die('<h1>Restricted access</h1>');
} else {
    echo '<h1>It Works</h1>';
}

?>

If you just want to check whether the user clicked a link from another site to arrive at yours then you can check whether $_SERVER['HTTP_REFERER'] exists:

You can use this to detect whether the referral URL was http://

<?php

if($_SERVER['HTTP_REFERER']) {
  die('<h1>Restricted access</h1>');
} else {
    echo '<h1>It Works</h1>';
}

?>


问:
Test single linked list for cycle
Is there a way to check if a single-linked list contains cycles for linear time without copying and modifying the list?

I thought we could try to sort this list topologically. If cannot there is somr cycle... But it seems it's not gonna work.

答:
As suggested in the comment, you can use fast and slow iterator solution.

Key insight:

The key insight in the algorithm is that, for any integers i ≥ μ and k
  ≥ 0, x(i) = x(i + kλ), where λ is the length of the loop to be found
  and μ is the index of the first element of the cycle. In particular, i
  = kλ ≥ μ, if and only if x(i) = x(2i). Thus, the algorithm only needs to check for repeated values of this special form, one twice as far
  from the start of the sequence as the other, to find a period ν of a
  repetition that is a multiple of λ. Once ν is found, the algorithm
  retraces the sequence from its start to find the first repeated value
  xμ in the sequence, using the fact that λ divides ν and therefore that
  x(μ) = x(μ + v). Finally, once the value of μ is known it is trivial
  to find the length λ of the shortest repeating cycle, by searching for
  the first position μ + λ for which x(μ + λ) = x(μ).

Reference Link :
Floyd's Tortoise and Hare

Title: Test single linked list for cycle


问:
How To Check If A Combination Of Foreign Keys Exists Multiple Times
So I have a database where there's the tables: Song, Artist and Producer. I want to check if an artist has produced more than 1 song at the same producer. The Song-Table already has the foreign keys of the artistID and producerID but how do I see in the song table if there's multiple combinations from those same ID's which would mean that the artist has producer more than 1 song at the same producer. This is what I have now, but I've been really stuck after this: </p>

```<code>query = "select Name from Artist where 1 < (Select count(*) from Song where....";
</code>```

答:
This sounds like a basic aggregation:

```<code>select artistId, producerId, count(*) as numsongs
from song
group by artistId, producerId
having count(*) > 1;
</code>```

You can join back to Artist and/or Producer if you want names instead of ids.

Body:
So I have a database where there's the tables: Song, Artist and Producer. I want to check if an artist has produced more than 1 song at the same producer. The Song-Table already has the foreign keys of the artistID and producerID but how do I see in the song table if there's multiple combinations from those same ID's which would mean that the artist has producer more than 1 song at the same producer. This is what I have now, but I've been really stuck after this:

query = "select Name from Artist where 1 < (Select count(*) from Song where....";

Body:
This sounds like a basic aggregation:

select artistId, producerId, count(*) as numsongs
from song
group by artistId, producerId
having count(*) > 1;

You can join back to Artist and/or Producer if you want names instead of ids.