text:
Q: A noun adjunct / the possessive case Sometimes it's possible to use either a noun adjunct or the possessive case.

the shop door
the shop's door

However, in certain phrases it's not OK to do so.

the ship's crew (the ship crew is wrong)

The questions are:

*

*How can one find out what to use in such cases as "the shop('s) door" when a noun adjunct option and the possessive case option are available?

*How can one know which option is wrong in order to avoid the construction "ship crew"?

*Is there a difference in meaning between (a) the shop door (b) the shop's door?

A: These are nice and subtle questions.
Beginning with (3), there is a semantic difference between shop door and shop's door.  If I tell you I'll wait by the shop door, then I generally mean at the front of the store (or maybe by the door for deliveries), but not, for instance, at a door that separates the shop from the living quarters.  The same goes for shop window (usually, not just any window in the shop, but the display window at the front) and shop floor (usually, not the floor out the back where goods are stored, but the parts accessible to the public).  By contrast, shop's door/window/floor can refer to more widely.  For instance, Today, I'm going to fix the shop's floor might well refer to parts out back; and in a related vein, the shop's side-window is fine, the shop side-window is odd.
Hence, in answer to (1), you use the possessive for a more generic meaning, and the compound to pick out some more idiomatic, conventionally salient door of the shop, etc.
With regard to (2), I'm not sure that ship crew is, in fact, unacceptable.  If, in a hotel, we're trying to stop sailors and pilots from fraternising, I might tell you: Put ship crews on the even floors and plane crews on the odd floors. If there's a fight, I might ask: Was a ship crew that started it?  When ship crew becomes odd is when we have a specific, known ship in mind—in the same way that it's odd to say the dog owner, rather than the dog's owner, when the dog in question is known and salient.

A: The situation couldn't be simpler.
"shop door" is a:  type of door.
That would be because, you know, shop is an adjective?  :)
Shop door, cheap door, expensive door, pink door, last door, aircraft door, submarine door, waterproof door ... shop door.
Adjective-noun.  Couldn't be simpler.
Whereas,
the shop 's door is:  the door of the shop you are referring to.

shop door, pink door, cheap door:  type of door
Adjective.

John's door, the shop's door, the barn's door:  doors belonging to John and others
Possessive "S".

Again, couldn't be simpler.
Consider say "castle gate". That's the highly decorated, large, baroque, type of gate. (Note, type of gate.)
It would be completely normal to say:
"This castle's castle gate has gold accents, but this castle's castle gate is rusty."
You could also say:
"Here's the castle's castle gate - and over there is the castle's small gate, and over there is the castle's emergency gate."
One point of confusion: "shop door" (i.e. adjective-noun) is an extremely common term.  So when you say "The shop's door" it just, happens, to sound similar to that extremely common phrase.  No big mystery.

A: I guess my confusion comes when we use Employee Details and Employee's Details.
I would say: Enter an employee name, but I would say Enter the employee's name. The former being far more abstract, whilst the latter is very specific to the employee I have in mind.
Would it be wrong to say Enter an employee's name?
In my head I see details more like this:
Employee Details - an abstract idea that doesn't specify details about any particular employee. If anything, it highlights/emphasises the details element of the phrase.
Employee's Details - relates specifically to the details of one employee.
Employees' Details - relates specifically to the details of more than one employee. For example, this could be a group/department of employees within a business.
Would this be correct? What are the views?


text:
Q: In Leibniz notation, how do you write the second derivative of y with respect to the square of x? I know how to write in Leibniz notation for more plain-vanilla expressions like the the second derivative of y with respect to x. But I am not sure how to write, in Leibniz notation, the second derivative of y with respect to expressions more complex than a single variable. In, for example, the second derivative of y with respect to the square of x, would I just use parentheses and write $dy^2/d(x^2)^2$?

A: Indeed, if $z=x^2$ and you need
$$
\frac{d^2y}{dz^2} = \frac{d^2 y}{d\left(x^2\right)^2}
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the syntax to define functions under objects So if I access name, age the output is correct but if I try to access bmi the function doesn't get executed. In chrome debugging console the function definition appears instead of name.

var john = {
  name: 'john ',
  age: '19',
  bmi: function() {
    console.log(this.name);
  }
}
console.log(john.bmi);

A: You should call function with func() syntax:
console.log(john.bmi());


text:
Q: Sharepoint 2010 List Settings I am Using a List in which i created Approval Required Column as Choice(Drop Down) with values Yes or No. Also i have a People Picker Column. The objective is the people picker must be disabled or hide if the value No is being selected and people picker must be available when the value Yes is selected from the choice(Drop Down). Any ideas?

A: Since you have tagged SharePoint Designer, I would recommend adding some Javascript or jQuery to your form that will enable/disable/hide/show the People Picker based on changes to Approval Required.
For more information and other options, see Dynamic columns based on rows.


text:
Q: Why this type action is giving me error in typescript? I got this action
export const getTodos =
  (url: string): ThunkAction<void, Store, unknown, Action<string>> =>
  async (dispatch) => {
    const response = await fetch(url);
    const data: Todo[] = await response.json();
    dispatch(setTodos(data));
  };

When I try to use it in my component like this.
dispatch(getTodos('https://gettodo.com'));

There is an error indication like this .
Argument of type 'ThunkAction<void, Store<any, AnyAction>, unknown, Action>' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type 'ThunkAction<void, Store<any, AnyAction>, unknown, Action>' but required in type 'AnyAction'.ts(2345)
What am I doing wrong?


text:
Q: Javascript/jQuery - is it possible to encapsulate and return the result of an asynchronously executed function? I know this question has been asked many times in many different ways, but I am still having trouble identifying a good solution to the following problem.
How can I wait for the callback of this asynchronously-executed inner function to complete prior to returning from the outer function?
function outer() {
    var result = false;
    var innerAsynch = function() {
        result = true;
    }
    setTimeout(innerAsynch, 1000);
    waitForInnerAsynch(); //blocking
    return result;  //true
}

1) I am well aware that this is bad practice for 99.999% of use cases, so please don't tell me that it shouldn't be done!
2) Please feel free to completely restructure this code... my only requirement is that outer() returns something which blocks the browser until innerAsynch() is done and passes the following test:
 if(outer()) {
    //1 second later.... yippee!
 }

Also I am using jQuery, but I would prefer not to use a plugin unless it really makes sense to do so. Thanks!
Update
I want to reiterate that my goal is to fully encapsulate the asynchronous execution within the synchronous call to outer() without arguments.
In other words, this should work:
A very slow link

Perhaps this is not actually possible, in which case I am fine using callbacks, but I want to develop a better understanding of why that is the case.

A: Standard js pattern. You just need to use callbacks:
function outer(callback)
{
    var innerAsynch = function(innerCallback) {
        var result = true;
        innerCallback(result);
    }

    setTimeout(function()
    {
      innerAsynch(function(result)
      {
        callback(result);
      });

    }, 1000);
}

Usage:
outer(function(result)
{
  if ( result )
    //true
  else
    //false
});

A:
I want to reiterate that my goal is to fully encapsulate the asynchronous execution within the synchronous call to outer() without arguments.

Asynchronous execution and callbacks exist for the sole reason of not blocking. If you really want to block, don't use async code. If you do depend on async functions, re-structure your code to use callbacks. It's simple as that.
JavaScript is single-threaded, so, if you block, the browser will seem to freeze until your code unblocks. When you block, you can't even update the UI to notify the user that some long-running operation is being performed. That's why it's bad. Keep in mind that the language was designed around an event loop and a queue of asynchronous events; trying to go against that will just lead to a big headache.


text:
Q: multiple clicks on Bootstrap Dropdown I have a problem with my dropdown.When I am clicking the dropdown menu button it got opened but when I click on it again the menu gonna moving down and sometimes it is also not able to close my drop down
here goes my html code:

Vegetables

                        <button style="font-size:24px" class="btn btn-light btn-secondary" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>

                                <input type="checkbox" name="brinjal" value="brinjal"/>Brinjal

                                <input type="checkbox" name="potato" value="potato"/>Potato

                                <input type="checkbox" name="tomato" value="tomato"/>Tomato

                                <input type="checkbox" name="capsicum" value="capsicum"/>Capsicum

                                <input type="checkbox" name="onion" value="onion"/>Onion

Here is my css code:
       .btn{
          margin-left:30px;
          background: white;
          border-color:white;
          width:300px;
          }

        .btn:hover{
          background: white;
          border-color:white;
          /*border-bottom-color: gray;*/
         }

        .dropdown {
                position: relative;
                display: inline-block;
                }
        .dropdown-menu{
            width:100%;
        }

        .force-scroll{
          overflow-y: scroll;
          width:300px;
         }

         .dropdown-menu{
            transform: translate3d(0px, 85px, 0px)!important;
            }

Here is the result:

So now I wanted my dropdown should get closed when I double click on the button and get opened when I click once.Is that possible.If?Will anybody help me out?

A: Your HTML code is invalid and there are multiple dead rules in your CSS to start with. Additionally there are some bad practices, for example you wouldn't use Bootstrap button like you did when implementing an icon as a button.
Attached is a jsfiddle with working and cleaned up code. click here

Vegetables

<button class="btn btn-light" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

</button>

    <input type="checkbox" name="brinjal" value="brinjal" />Brinjal

    <input type="checkbox" name="potato" value="potato" />Potato

    <input type="checkbox" name="tomato" value="tomato" />Tomato

    <input type="checkbox" name="capsicum" value="capsicum" />Capsicum

    <input type="checkbox" name="onion" value="onion" />Onion

Using double click in web is something i would not recommend, since double-clicking is usually used to select text/paragraphs. If you want to implement it either way there is a solution here.


text:
Q: Distinct item with latest timestamp and multiple (or all) columns returned I have a table delivery_history which is populated by a trigger:
id(guid)  order_number  delivery_number  haulier    timestamp(getdate())

          1             1234             haulier1   2009-10-08 8:34:00
          2             1235             haulier1   2009-10-09 9:15:00
          1             1234             haulier2   2009-10-10 9:20:00

I would like to return all the columns, but I only want to see the unique delivery_number with the latest timestamp, so the data I'd want returned would be:
          1             1234             haulier2   2009-10-10 9:20:00
          2             1235             haulier1   2009-10-09 9:15:00

So far I've tried every single possibility and combination of responses posted on this site and they either don't give me the results I require, they expect that I've been sensible and used an incremental id rather than the guid I used (there's now a weeks worth of data from the trigger and I don't really want to dump it), or they expect Sql Server 2005 or higher.
This will be run on Sql Server 2000.
Thanks in advance,
Mark

A: I don't like the potential for duplicates here. Two rows with the same delivery_number could have the same timestamp. It may be unlikely, given the frequency of deliveries and the behavior of your application, but I wouldn't want to rely on that for correctness.
This version uses TOP 1 and allows an arbitrary number of tie-breakers:
select * from delivery_history a
where id = (
  select top 1 id
  from delivery_history b
  where a.delivery_number = b.delivery_number
  order by b.timestamp desc [, tie breaking col1, col2, ... colN]
  )

A: SELECT order_number, delivery_number, haulier, timestamp
  FROM delivery_history dh1
 WHERE timestamp = (SELECT max(dh2.timestamp)
                      FROM delivery_history dh2
                     WHERE dh2.delivery_number = dh1.delivery_number)


text:
Q: "error" : "MismatchSendedId" when trying to send a Web Push notification I'm following this guide to learn about web push implementation. I've followed the guide until I encountered a problem when using curl to send a notification:
curl --header "Authorization: key=<PUBLIC_API_KEY>" --header "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"<SUBSCRIPTION_ID>\"]}"

I changed the API Key and Subscription Id with my Firebase Cloud Messaging key and the Subscription ID generated when the notifications are accepted on the browser.
Still I get this error when executing curl:

{"multicast_id":8346257587601342490,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

I found this error related to android push notifications but not about web push so the other answers were not useful with my issue.
Has anyone experienced this issue? What am I missing?

A: I was also experiencing the same thing. Even after recheking a dozen of times that the manifest was properly written out and set and that the API_KEY and registration_ids are correct.
But I have now noticed that the problem was that I wasn't copying the whole url link.
Example if your endpoint url is:
endpoint: https://android.googleapis.com/gcm/send/c_hMYQ0IJEg:APA91bHugFROB5EKLlwFKPjc7lRs_YZ7nBV655oftqdKPtzsmoz149d1BLVntgMpRnLHGqTVn6W7n7je4SoezFhfbUMdwxAot
Then the subsctionID will be "c_hMYQ0IJEg:APA91bHugFROB5EKLlwFKPjc7lRs_YZ7nBV655oftqdKPtzsmoz149d1BLVntgMpRnLHGqTVn6W7n7je4SoezFhfbUMdwxAot".
I had been using only the last part as in "APA91bHugFROB5EKLlwFKPjc7lRs_YZ7nBV655oftqdKPtzsmoz149d1BLVntgMpRnLHGqTVn6W7n7je4SoezFhfbUMdwxAot" and I guess that's why I had been getting the errors.

A: It means that the service worker installation is associated to a GCM sender that is different from the GCM sender that generated the API key.
From Pushpad troubleshooting:

*

*Make sure that you have created and linked the manifest.json

*Check that you have entered correctly the gcm_sender_id in the manifest.json

*Check that you have entered correctly the GCM API key

If everything is correct you can also try to unsubscribe and resubscribe after you have set the correct gcm_sender_id.


text:
Q: Logical operators or assignment in Perl cannot work? I want to check my variable $id is equal 497 or equal 200 ,
if $id not equal 497 or $id not equal 200 then mail,
but when i run the example as below, I set $id =497 by hand , but run the code ,it's print "not equal\n";
my $id = 497;
if($id != 497 || $id != 200)
   {
      print "not equal\n";
   }
else
  {
      print "equal , not to mail\n";
   }

A: It says not equal because $id != 200 is true.  || returns true if either operand is true.
You want to say:
if ($id != 497 && $id != 200)

so not equal is printed only when $id is neither 497 or 200.


text:
Q: ADB installed apk not showing or launchable I've installed 5 APKs using the abd install command. Three of the packages install and function as expected but the other 2 (including Brave browser) don't. If I try to access the 2 apps in question via swiping up from the bottom of the screen to reveal the app list (app drawer) but they are not shown. If I go to 'setting > apps' they are viewable but cant be opened. The output of adb dumpsys package packages show that the the apps are installed. Some forums suggest that this may occur if there are more than on account on the device but this isnt the case for me.
Does anyone have any idea why this is happening and how I can get the apps to work as normal.
Thanks


text:
Q: Some questions about posts that I've edited I have some questions about posts that I've edited.

*

*How can I get a list of all posts that I've edited?

*Can I get the count of all posts that I've edited?

*How can I discard my edited post?

A: *

*You'll find these on your activity tab in your profile.

*Click 'Users' at the top, then 'Editors' on the right, then select 'All' just below that, then filter by your own name on that page.

*You can't, unless you mean 'delete the post', which you can only do in certain circumstances (always your own answers, only your own questions if there are no upvoted answers).
You can 'undo' an edit by using the 'rollback' link, which copies the previous version of a post back on top as a new edit.

A: *

*Your user page > Activity > revisions.

*It tells you the number of Revisions to the left of "Revisions" on the same page.

*You can Rollback to a previous version of an edit by clicking on the link that is the relative time that you edited the post when you view the post.

If you are referring to Suggested Edits, exchange "suggestions" for "revisions" above, except for (3) where I don't recall if you can recall a suggested edit when you don't have the rep to edit the question directly.

A: Your Profile contains all these details.
1. How can I get posts that edited by me already ?

Go to your profile, select Activity tab, select "suggestions" option. It will show you the edit suggestion you did. you can choose any particular from there.
 2. Can I get number of edited post by me until now ?

You have edited only 1 post till now. In the "suggestion" option when you click on the "suggested edit" link it will show you the suggestion history, where you can find the total number of edits you done at the botton, along with the user who approved/reject your suggest edit.
 3. How can I discard my edited post ?

There is a roll back link with every edit you made. Just click on it to discard the modification you did.


text:
Q: Modelling time varying volatility when GARCH(1,1) coefficients sum to value greater one First of all I have to admit that I am not a time-series expert so any help is highly appreciated. I have a financial time-series (a fixed income total return index measured on a weekly basis) for which I would like to fit an AR model. However, I would like to take into account the time varying volatility of the series. In particular, the volatility of the series is very low at the beginning of the series, increases sharply at the end of 2008 and shrinks again:

The log returns exhibit this even more clearly:

I decided upon the order of the AR model by using different information criteria which lead me to an AR(1) model for the log return time-series. After that I tested for ARCH effects using a Lagrange-Multiplier-Test. It turned out that ARCH effects are significant for all tested 12 lags. Considering the high order of the lags I considered a GARCH(1,1) for the conditional volatility. The problem is that the estimated coefficients sum to a value greater than one ($\alpha_1+\beta_1=0.97+0.56=1.53)$ implying that volatility is growing without bounds which is clearly undesirable and also is contradictory to the graph. So my questions are:

*

*Which alternative model could I use to model this behavior of the     volatility of the series considering that my primarily interest is in the coefficient values for the AR(1)?

*When modelling the conditional mean of the series the classic approach would be to integrate the series. Is there a similar approach considerable for the volatility?

*As the series has only 534 observations how likely is this to be the reason for the sum of the mentioned coefficients to be greater than 1?

I would be also very happy about any hint to a particular Stata or R command that seem promising to model the volatility of this time series. However, I think this is primarily an econometrics question. Thanks for your time and effort!

A: First, you have not told us what this series represents. Subject-matter knowledge is generally useful when trying to model the data.

the volatility of the series is increasing <...> The log returns exhibit this even more clearly

It would be more accurate to say that volatility has been very low in the beginning, high for a while and then quite low again. There is no linear trend in the magnitude of volatility -- see your second figure.

*

*Which alternative model could I use to model this behavior of the volatility of the series <...> ?

You may want to reconsider the model for the conditional mean first. Perhaps you could model the apparent trend in the original series and the dip during approx. 2009 by including some other explanatory variables and turning the AR model into an ARX model. Also, you could consider ARCH-in-mean specification, as the volatility seems to have been the highest when the series was going down.
Now to answer the question, there is a great variety of GARCH models suited for different features of the data. One survey (not necessarily the best) can be found here: Terasvirta "An introduction to univariate GARCH models" (2009). You could take a look at the stylized facts and the characteristics of the different models and see if there is one that suits you.
You could also have a GARCH model with exogenous variables. E.g. a GARCH model with a time trend could suit a case where conditional variance is increasing linearly (which does not seem to be the case here, though). Or you could have an IGARCH model where the conditional variance is an integrated process. That also answers your second question:

*When modelling the conditional mean of the series the classic approach would be to integrate the series. Is there a similar approach considerable for the volatility?

Sorry for being a bit vague about the choice of the model, but I think it would be careless to recommend a particular model just by having seen a graph of the data.

I would be also very happy about any hint to a particular Stata or R command that seem promising to model the volatility of this time series.

In R I may recommend using "rugarch" package with main functions ugarchspec (for specifying a GARCH model) and ugarchfit (for estimating the specified model for a given data series). There is a nice vignette to consult.
P.S.

the estimated coefficients sum to a value greater than one <...> implying that volatility is growing without bounds which is clearly undesirable

It is not only undesirable, but it also does not seem to fit the data -- I do not see gradually exploding volatility in the second figure.


text:
Q: ArrayIndexOutOfBoundsException in doInBackground method Please help me with this error. Even after passing value in execute() method I'm still unable to fix this issue.

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
          at com.iamsharzil.constraintlayoutproject.DownloadNews.doInBackground(DownloadNews.java:54)
          at com.iamsharzil.constraintlayoutproject.DownloadNews.doInBackground(DownloadNews.java:22)

DownloadNews.java
String NEWS_SOURCE = "bbc-news";
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();

private Activity mContext;

String API_KEY = "4f5f4fbf57f7476ba41c276b28379a6b";
ListView listNews;

static final String KEY_AUTHOR = "author";
static final String KEY_TITLE = "title";
static final String KEY_DESCRIPTION = "description";
static final String KEY_URL = "url";
static final String KEY_URLTOIMAGE = "urlToImage";
static final String KEY_PUBLISHEDAT = "publishedAt";

public DownloadNews(BaseDrawerActivity mContext) {
    this.mContext = mContext;
    Log.i("Constructor", "Download News called");
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

protected String doInBackground(String... args) {

    String xml = "";

       String url = args[0];
        Log.i("URL", url);

        xml = Function.executeGet(url);
        return xml;

}

@Override
protected void onPostExecute(String xml) {

    if(null != xml && xml.length()>10) {
        try {
            JSONObject jsonResponse = new JSONObject(xml);
            JSONArray jsonArray = jsonResponse.optJSONArray("articles");

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(KEY_AUTHOR, jsonObject.optString(KEY_AUTHOR).toString());
                map.put(KEY_TITLE, jsonObject.optString(KEY_TITLE).toString());
                map.put(KEY_DESCRIPTION, jsonObject.optString(KEY_DESCRIPTION).toString());
                map.put(KEY_URL, jsonObject.optString(KEY_URL).toString());
                map.put(KEY_URLTOIMAGE, jsonObject.optString(KEY_URLTOIMAGE).toString());
                map.put(KEY_PUBLISHEDAT, jsonObject.optString(KEY_PUBLISHEDAT).toString());
                dataList.add(map);
            }
        } catch (JSONException e) {
            Toast.makeText(mContext, "Unexpected error", Toast.LENGTH_SHORT).show();
        }

        listNews = (ListView) mContext.findViewById(R.id.listNews);
        ListNewsAdapter adapter = new ListNewsAdapter((Activity) mContext, dataList);
        listNews.setAdapter(adapter);

        listNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent i = new Intent(mContext, DetailsActivity.class);
                i.putExtra("url", dataList.get(+position).get(KEY_URL));
                mContext.startActivity(i);
            }
        });

    }else{
        Toast.makeText(mContext, "No news found", Toast.LENGTH_SHORT).show();
    }
}

}
BaseDrawerActivity.java
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_base_drawer);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    toolbar.setTitle("NEWS");

    listNews = (ListView) findViewById(R.id.listNews);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

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

    if(Function.isNetworkAvailable(getApplicationContext()))
    {
        DownloadNews newsTask = new DownloadNews(this);
        newsTask.execute();
    }else{
        Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
    }
}

public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment = null;

    if (id == R.id.nav_general) {
      String general =  "https://newsapi.org/v2/top-headlines?country=in&apiKey=" + API_KEY;
        new DownloadNews(this).execute(general);

    } else if (id == R.id.nav_sports) {
        String sports =  "https://newsapi.org/v2/top-headlines?categoty=sports&country=in&apiKey=" + API_KEY;

        new DownloadNews(this).execute(sports);
    } else if (id == R.id.nav_business) {
        String business =  "https://newsapi.org/v2/top-headlines?categoty=business&country=in&apiKey=" + API_KEY;

        new DownloadNews(this).execute(business);
    } else if (id == R.id.nav_technology) {
        String technology =  "https://newsapi.org/v2/top-headlines?categoty=technology&country=in&apiKey=" + API_KEY;
        new DownloadNews(this).execute(technology);

    } else if (id == R.id.nav_entertainment) {
        String entertainment =  "https://newsapi.org/v2/top-headlines?categoty=entertainment&country=in&apiKey=" + API_KEY;
        new DownloadNews(this).execute(entertainment);

    } else if (id == R.id.nav_health) {
        String health =  "https://newsapi.org/v2/top-headlines?categoty=health&country=in&apiKey=" + API_KEY;
        new DownloadNews(this).execute(health);

    } else if (id == R.id.nav_science) {
        String science =  "https://newsapi.org/v2/top-headlines?categoty=science&country=in&apiKey=" + API_KEY;
        new DownloadNews(this).execute(science);

    }

    if(fragment!=null) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.screen_area, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

When a user click on any of the Menu item I want the url to be change.
Function.java
public class Function {

    public static boolean isNetworkAvailable(Context context) {
        return ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)).
                getActiveNetworkInfo()!=null;
    }

    public static String executeGet(String targetURL) {
        URL url;
        HttpURLConnection connection = null;

        try {
            //Create connection
            url = new URL(targetURL);
            connection = (HttpURLConnection)url.openConnection();

            //connection.setRequestMethod("POST");
            //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.setRequestProperty("content-type", "application/json;  charset=utf-8");
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches (false);
            connection.setDoInput(true);
            connection.setDoOutput(false);

            InputStream is;

            int status = connection.getResponseCode();

            if (status != HttpURLConnection.HTTP_OK)
                is = connection.getErrorStream();
            else
                is = connection.getInputStream();

            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();

            while((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (Exception e) {
           return null;
        } finally {
            if(connection != null) {
                connection.disconnect();
            }
        }
    }

}

A: You are calling execute here:
if(Function.isNetworkAvailable(getApplicationContext()))
{
    DownloadNews newsTask = new DownloadNews(this);
    newsTask.execute(); // <-
}else{
    Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
}

But are not passing an argument. That will cause your method to fail because you cannot access the zeroth item of a zero length array. You either need to ensure you are always passing data to it, or you need to do something like this:
protected String doInBackground(String... args) {
  String xml = "";

  if (args.length > 0) {
   String url = args[0];
    Log.i("URL", url);
    xml = Function.executeGet(url);
  }

   return xml;
}

This way, if args is empty, you return an empty string and can then handle for that where you need to.

A: Based on how to call async task with different url and @Justin-Pearce answer, I was able to solve the error.
BaseDrawerActivity.java
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment = null;

    String general = null, health = null, sports = null, business = null, technology = null, science = null, entertainment = null;

    if (id == R.id.nav_general) {
        general = "https://newsapi.org/v2/top-headlines?country=in&pageSize=100&apiKey=" + API_KEY;

    } else if (id == R.id.nav_sports) {
        sports =  "https://newsapi.org/v2/top-headlines?country=in&category=sports&pageSize=100&apiKey=" + API_KEY;

    } else if (id == R.id.nav_business) {
        business =  "https://newsapi.org/v2/top-headlines?country=in&category=business&pageSize=100&apiKey=" + API_KEY;

    } else if (id == R.id.nav_technology) {
        technology =  "https://newsapi.org/v2/top-headlines?country=in&category=technology&pageSize=100&apiKey=" + API_KEY;

    } else if (id == R.id.nav_entertainment) {
        entertainment =  "https://newsapi.org/v2/top-headlines?country=in&category=entertainment&pageSize=100&apiKey=" + API_KEY;

    } else if (id == R.id.nav_health) {
        health =  "https://newsapi.org/v2/top-headlines?country=in&category=health&pageSize=100&apiKey=" + API_KEY;

    } else if (id == R.id.nav_science) {
        science =  "https://newsapi.org/v2/top-headlines?country=in&category=science&pageSize=100&apiKey=" + API_KEY;

    }

    new DownloadNews(this).execute(
            general,
            sports,
            business,
            technology,
            entertainment,
            health,
            science);

    if(fragment!=null) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.screen_area, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

DownloadNews.java
@Override
protected void onPreExecute() {
    super.onPreExecute();
}

protected String doInBackground(String... args) {

    String xml = "";
    for(String urls: args) {
        try {
            String u = new String(urls);
            xml = Function.executeGet(u);
            Log.i("args length", String.valueOf(args.length));
            Log.i("URL", u);

        } catch (Exception e) {}
    }

    return xml;
}


text:
Q: High res display: will it upscale from my low res laptop video? My 4 year old Vaio/windows 7 has an hdmi port, and I regularly use it with a Dell UltraSharp U2410 x 1920 x 1080. This is a "regular" dpi display (92 dpi or so)
I want to use it with a 4k or 5k display (such as an ASUS PB279Q 27" 4K/ UHD 3840x2160).
But I am worried that everything will be small.
Do high res displays smartly resample to get it right in this situation?
Or ?

A: Answer:
The Vaio laptop in question has a built in display of 1920x1080, and the external hdmi supports a max res of 1920x1080.
When we plug the ASUS PB279Q (which is 3840 x 2160) in to the hdmi port, the monitor automatically upscales the output.
Some output is a tad blurred, but overall it looks very good.
(Yes, we actually purchased the ASUS PB279Q... and got lucky. This thread was attempt to reduce the luck factor...)


text:
Q: Question about keeping a reference to a unique_ptr in another class Recently, I decided that it was time that I should dig into smart pointers. I read about the different kinds (unique, shared, weak), but I'm not sure about one thing.
Let say that I have a class Player and a GameMap class. The content of those classes are irrelevant for the next part. I also have an Engine class, that represents the object that will hold the main components of my game, like this:
class Engine {
public:
    Engine();
    ~Engine();
private:
    std::unique_ptr<Player> m_player;
    std::unique_ptr>GameMap> m_gamemap;
};

These are the only instances of the player and game map that will be created, and the Engine owns them, and should be responsible for their allocation and deletion. So, a unique_ptr seems to be the good choice here.
Now, I would like to keep a simple reference to m_player in my GameMap class, since it would be easier for me than passing the m_player to each function that need it.
My question is: is using a raw pointer (obtained through the get() method) in the GameMap class the best way to keep a reference to the original unique_ptr located in the Engine class? I think that I can't use another unique_ptr pointing to the original one, since it would not be logical regarding to the use case of unique_ptr.

A: I think that using of raw pointer isn't the best way. For example, better way is use shared_ptr for player and gamemap. And adds weak_ptr of player into gamemap.


text:
Q: Can I run a custom phase generating an initial solution several times to generate a pool of starting solutions? I'm using Optaplanner 8.15.0 to solve a variant of the redistricting problem: Geographic areas with an expected revenue are assembled to sales districts that must be contiguous and should be balanced and compact.
The initial solution is generated by a custom phase using a greedy heuristic. Afterwards a local search hill climbing phase makes big and obvious improvements to that using custom moves. Only then, the "real" optimization starts with a tabu search.
The configuration of the first two phases:
<customPhase>
    <customPhaseCommandClass>project.solver.SeedGrowthInitialSolution</customPhaseCommandClass>
</customPhase>
<localSearch>
    <localSearchType>HILL_CLIMBING</localSearchType>
    <moveListFactory>
        <moveListFactoryClass>project.move.SplitAndJoinMoveFactory</moveListFactoryClass>
    </moveListFactory>
    <termination>
        <unimprovedSecondsSpentLimit>60</unimprovedSecondsSpentLimit>
    </termination>
</localSearch>

It turned out that the quality (=score) of the overall solution depends very much on the quality of the initial solution after the second phase. I.e. the tabu search will improve the solution substantially, but it's not able to "fix" a bad initial solution.
Is there a way to run the first two phases repeatedly to generate several candidate solutions and then continue with the best of them?
My current workaround is to start several instances manually, watch the logs for the achieved scores after the first two phases and restart all instances where the initial scores are not promising.

A: The answer is no, when the problem is specified like this. However, we could maybe change the problem statement a bit. If you run multiple independent solvers and, at the end, pick the best result, you can then pass that to a new solver which will start from there. This would be a variant of multi-bet solving. It is not supported out of the box, but would be relatively easy to code yourself, using either the Solver or SolverManager APIs.
That said, your entire approach is very unconventional. Custom construction heuristic is understandable, as are custom moves. But the fact that you feel the need to separate the moves into different phases makes me curious. Have you benchmarked this to be the best possible approach?
I would think that using the default local search (late acceptance), with your custom moves and our generic moves all thrown into the mix, would yield decent results already. If that fails to happen, then generally either your constraints need to be faster, or the solver needs to run for longer. For large problems, multi-threaded solving can help, too.


text:
Q: How to return a table of values from a function in oracle I have tried some of the answers and could not make my code work:
Here is what I want and here is what I did:
I have a table which is two column type and I want to query that table using a function to return exactly the same table to be routed to VB.NET so that I can display it in a DatagridView control.
I am a novice to PL/SQL which is the problem for me.
The first problem I intended to solve is to create the function.
-- DECLARE A RECORD TYPE
create or replace type shipper_type AS OBJECT
(
shipper_id number,  shipper_name varchar2(7)
);
/

CREATE TYPE t_shipper as table of shipper_type;
/

    create or replace function get_shipper return t_shipper is
    temp_list t_shipper:= t_shipper();
    is
     --  shipper_record shipper_type;
    begin
      for i in (  (select shipper.shipper_id, shipper.shipper_name) list from shipper)
      loop
        temp_list.extend;
      temp_list(temp_list.last):= t_shipper(list);
    end loop;

    return(temp_list);
   end get_shipper;
   /

When I try to compile this code I am getting the following errors:
Errors for FUNCTION GET_SHIPPER:
LINE/COL ERROR
-------- -----------------------------------------------------------------
3/1      PLS-00103: Encountered the symbol "IS" when expecting one of the
         following:
         begin function pragma procedure subtype type <an identifier>
         <a double-quoted delimited-identifier> current cursor delete
         exists prior

6/63     PLS-00103: Encountered the symbol ")" when expecting one of the
         following:
         . ( , * @ % & - + / at mod remainder rem <an identifier>
         <a double-quoted delimited-identifier> <an exponent (**)> as
         from || multiset

A: You get those compilation messages because you have several syntax errors in your code.  Two instances of IS, missing the type in the select, those unnecessary brackets in the return.    You can correct those but you should simplify your code too.
The easiest way to populate a nested table is with a bulk collect.
create or replace function get_shipper return t_shipper is
    temp_list t_shipper:= t_shipper();
begin
    select shipper_type(shipper.shipper_id, shipper.shipper_name)
    bulk collect into temp_list
    from shipper;

    return temp_list ;
end get_shipper;
/

A: Try it without () in the return statement and add an end; at the end.
return temp_list;

end;

Also you might want to take a look at so called pipelined functions:
http://www.oracle-base.com/articles/misc/pipelined-table-functions.php


text:
Q: Should there be a comma before "though" when it occurs at the end of a sentence? Consider

I don't know how outdated it is though.

Should there be a comma before though, as in the following?

I don't know how outdated it is, though.

A: I'd use the comma, but modern style would probably omit it.  There is a general tendency towards less punctuation.  Look at Victorian novels, and then compare with modern prose - there is much less punctuation now.  Or look at the King James Bible; that is rife with colons and semi-colons that would not appear nowadays, often not even 'demoted' to commas.  Punctuation style has changed over time.

A: I strongly prefer the second form, with the comma.
Say out loud, without a pause

I don't know how outdated it is-though

Nonsense-speak to me.

A: Though is used as an adverb in this case, applied to the verb is, therefore no comma is strictly necessary.
Saying this, I can easily imagine a brief pauses between is and though when speaking the sentence, hence a vocative comma is acceptable.
In other words, take your pick. If I can avoid a comma (as in this case), I usually will. It's not wrong either way though.

A: I believe both are correct. In general, you would use the comma if you would pause at that point if you spoke it aloud.


text:
Q: Why does an error occur when Angular 2 is switched to Angular 5? Help Wanted.
When switching from Angular 2 to Angular 5, an error occurred:
ERROR TypeError: Cannot read property 'name' of undefined
    at checkBindingNoChanges (core.js:9902)
    at checkNoChangesNodeInline (core.js:13951)
    at checkNoChangesNode (core.js:13925)
    at debugCheckNoChangesNode (core.js:14754)
    at debugCheckDirectivesFn (core.js:14656)
    at Object.eval [as updateDirectives] (GeneralFormComponent.html:4)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14638)
    at checkNoChangesView (core.js:13763)
    at callViewAction (core.js:14116)
    at execComponentViewsAction (core.js:14068)

The console references an error on the line in the GeneralFormComponent:
<input type="hidden" class="form-control" [(ngModel)]="model.guid" name="guid">

After debugging, I realized that the component was called 2 times. At the first time, the model was only initialized and the model in fact was empty, and at the second time in the model came data from the database.
I assume that this error stems from the fact that some data came and they were abruptly replaced by new ones.
Help solve the problem.

A: Building on Richards' suggestion
Perhaps this would help?
<ng-container *ngIf="model != null && model.guid!=null">
    <input type="hidden" class="form-control" [(ngModel)]="model.guid" name="guid">
</ng-container>


text:
Q: why does typescript function parameter type infer failed? class Base<T> {
    public state = {} as T;
    public getState(): T {
        return this.state
    }
    public setState(v: T) {
        this.state = v
    }
}

interface DogProps {
    name: 'hello';
    age: 123;
}

class Dog extends Base<DogProps> {
    public sayName() {
        console.log('name: ', this.state.name);
    }
    public sayAge() {
        console.log('age: ', this.state.age);
    }
}

function test<U, T extends Base<U>>(Cor: new () => T): [U, T] {
    const dog = new Cor();
    const state = dog.getState();
    return [state, dog];
}

const [state1, dog1] = test(Dog); // state1 is unknow

const [state2, dog2] = test<DogProps, Dog>(Dog); // verbose but right

demo playground
I am newbe in typescript.
I thought the code I wrote was right. But it does not work as expected.
Why state1's type is unknow?
Can I get the right type without test<DogProps, Dog>(Dog)?
much thanks!!!

A: This is a side effect of how generic resolution works, typescript sees that T is referred to in the arguments so it tries to resolve it, but the constraint is based on U so it tries to resolve that first.  Because U doesn't appear anywhere in the argument list, it can't resolve it so it ends up unknown
If you ensure that U is present in the arguments list you can ensure that typescript will be able to resolve it from just looking at the input without having to figure out T first:
function test<U, T extends Base<U>>(Cor: new()=>(T & Base<U>)): [U, T] {
                                                 // ^here^
}

This should fix the issue :)


text:
Q: Creating news module : part ADD At the moment, Im trying to create "news module" on my website, starting with adding news to mysql database but its not working - after hitting button submit nothing happens - no new data in db.
    <?php
          $servername = "localhost";
          $username = "u296093122_admin";
          $password = ".";
          $dbname = "u296093122_datab";

        if(isset($add_n)){
            $conn = new mysqli($servername, $username, $password, $dbname);

          if ($conn->connect_error) {
           die("->Pripojenie neúspešné: " . $conn->connect_error);
                                    }

           $sql = "INSERT INTO Akcie(nadpis, obsah, timestamp)VALUES('$nadpis', '$obsah', NOW())";
           $result = $conn->query($sql);

        if(!$result){
            echo('Error ' . $mysql_error());
            exit();
        }else{
        mysql_close($conn);
        echo('Success!');
            }
    }else{
    ?>
    <form name="form1" method="post" action="<?php echo $PHP_SELF; ?>">

                Nadpis:
                <input name="nadpis" type="text" id="nadpis">

                Obsah novinky:
                <textarea name="obsah" id="obsah"></textarea>

                <input name="hiddenField" type="hidden" value="add_n">
                <input name="add" type="submit" id="add" value="Submit">

    </form>
<? } ?>

A: You should use isset($_POST['hiddenField']) instead of isset($add_n). Best way use
if (isset($_POST['hiddenField']) && $_POST['hiddenField'] == 'add_n')


text:
Q: what is regex for repeating same number 5 or more times for example 11111, 22222, 33333, 44444 what is regex for repeating same number 5 or more times for example 11111, 22222, 33333, 44444. I am using SQL server Like query

A: You can try this:
(\d)\1{4,}

This is how it works:

This is the explanation from regex101.com
1st Capturing Group (\d)
\d matches a digit (equal to [0-9])
\1{4,} matches the same text as most recently matched by the 1st capturing group
{4,} Quantifier — Matches between 4 and unlimited times, as many times as
possible, giving back as needed (greedy)
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line
(not only begin/end of string)

A: There won't be a Regex in SQL Server to accomplish what you are after.  You can reference this article that gives a great overview on using regular expressions in T-SQL with LIKE:  https://www.mssqltips.com/sqlservertutorial/9106/using-regular-expressions-with-tsql-from-beginner-to-advanced/
For repeating characters with SQL Server, 2008+, you can use REPLICATE.

REPLICATE:  Repeats a string value a specified number of times.

Base on previous comments you might be doing some sort of phone number evaluation.  Here's an example that might assist with what you are trying to accomplish:
DECLARE @PhoneNumbers TABLE
    (
        [HomePhone] NVARCHAR(500)
    );

INSERT INTO @PhoneNumbers (
                              [HomePhone]
                          )
VALUES ( N'123546789' )
     , ( N'111111111' )
     , ( N'555555555' )
     , ( N'222222222' )
     , ( N'231111123' )
     , ( N'897777712' )
     , ( N'010101010' )
     , ( N'333344444' )
     , ( N'123546789' );

SELECT *
FROM   @PhoneNumbers
WHERE  [HomePhone] LIKE '%' + REPLICATE('1', 5) + '%'
       OR [HomePhone] LIKE '%' + REPLICATE('2', 5) + '%'
       OR [HomePhone] LIKE '%' + REPLICATE('3', 5) + '%'
       OR [HomePhone] LIKE '%' + REPLICATE('4', 5) + '%'
       OR [HomePhone] LIKE '%' + REPLICATE('5', 5) + '%'
       OR [HomePhone] LIKE '%' + REPLICATE('6', 5) + '%'
       OR [HomePhone] LIKE '%' + REPLICATE('7', 5) + '%';

Thinking about this using REPLICATE in this situation probably won't gain you anything because there wouldn't be much difference between typing REPLICATE('1',5) as opposed to just typing it out '11111'.  But should give you an idea on functionality on repeating characters.
You had mentioned having the repeating items in the where clause isn't an option.  If ultimately all you're trying to evaluate is if the entire value of HomePhone is repeating, you can do that as follows:
    SELECT *
    FROM   @PhoneNumbers
    WHERE [HomePhone] = REPLICATE(LEFT([HomePhone],1), LEN([HomePhone]))

All that's happening here is it's taking the left most character HomehPhone, replicating for the length of the value and seeing if it matches.


text:
Q: its or his in this context? Which one is correct:

*

*A child born today
inherits a world vastly different from that of its parent's generation.

*A child born today
inherits a world vastly different from that of his parent's generation.

I found the first version of the sentence in a book. But my humble knowledge of English language says it must be written his instead of its.
What do you think and why?
EDIT:
The posts given on Is referring to people as "it" considered rude? do not answer my question because all the answers refer to rudeness and anger such as in the accepted one: this is something that would be said only in the heat of anger. But the author of the book is not trying to offend anybody.

A: Grammatically you can use either, but you may want to choose to just use his, her, or his/her.
If you are referring to any child in general then you can reasonably use the word its, although you may prefer to use the child's or even better (for political correctness), his/her.

*

*A child born today inherits a world vastly different from that of the child's parent's generation.

*A child born today inherits a world vastly different from that of his/her parent's generation.

However, if you are referring to a specific baby and you know its sex, for the reasons @Robusto gave in this answer, it may be more politically correct to use the word his or her.

A: As the other answer said, "his," "his or her" and "its" are all correct. There are also writers who alternate between "his" and "her" throughout a text.
I'd like to mention another possibility: "their parents' generation."
This use of "their" is controversial. It is claimed by its opponents to be incorrect. However, it is widely used by well-educated people who are good writers, at all levels of formality.


text:
Q: Find files containing keyword and show only the file path and the line number I'd like to find all the Java files containing keyword File.createTempFile with the line number. Here's what I did:
$ find . -name "*.java" | xargs grep -n "File.createTempFile"
./nuxeo-studio-test/src/test/java/com/nuxeo/studio/web/StudioServletTest.java:162:            File tmpFile = File.createTempFile(jarEntryName, null, Environment.getDefault().getTemp());
./nuxeo-studio-ui/src/main/java/com/nuxeo/studio/core/builders/WorkflowFeatureBuilder.java:421:            tmp = File.createTempFile(".workflow-to-zip", ".tmp", workspace.getRoot());
./nuxeo-studio-ui/src/test/java/com/nuxeo/studio/core/backup/TestS3Backup.java:101:        File tempFile = File.createTempFile(RandomStringUtils.randomAlphabetic(5), ".tmp");
./nuxeo-studio-ui/target/classes/com/nuxeo/studio/core/builders/WorkflowFeatureBuilder.java:421:            tmp = File.createTempFile(".workflow-to-zip", ".tmp", workspace.getRoot());
./nuxeo-studio-web/src/main/java/com/nuxeo/studio/web/v1/ProjectResource.java:191:            File zip = File.createTempFile(filename + "-", ".zip", tempRepo);

However, I found this result too long to read. I'd like to keep only the file path and the line number. Here's expected result:
./nuxeo-studio-test/src/test/java/com/nuxeo/studio/web/StudioServletTest.java:162
./nuxeo-studio-ui/src/main/java/com/nuxeo/studio/core/builders/WorkflowFeatureBuilder.java:421
./nuxeo-studio-ui/src/test/java/com/nuxeo/studio/core/backup/TestS3Backup.java:101
./nuxeo-studio-ui/target/classes/com/nuxeo/studio/core/builders/WorkflowFeatureBuilder.java:421
./nuxeo-studio-web/src/main/java/com/nuxeo/studio/web/v1/ProjectResource.java:191

Could somebody teach me how to do so?

A: With pcregrep, you could do:
pcregrep --include='\.java$' -rHno1 '()File\.createTempFile' .

The output will be looking like:
./path/to/file.java:12:

If the pattern appears more than once on a line, there will be as many lines output. If you don't want that, you could change it to:
pcregrep --include='\.java$' -rHno1 '^().*?File\.createTempFile' .

A: Here's one way with awk:
find . -name '*.java' -exec awk '/PATTERN/{print FILENAME,FNR}' {} +

or, if you wanted to emulate grep's output:
find . -name '*.java' -exec awk '/PATTERN/{printf("%s:%s\n", FILENAME, FNR)}' {} +

A: keyW='File.createTempFile'
find . -type f -name '*.java' -exec perl -slne '
  print "$ARGV:$." if /\Q$k\E/; $. = 0 if eof;
' -- -k="$keyW" -- {} +

A: esport keyW='File.createTempFile'
find . -name '*.java' -type f -exec sh -c '
   grep -hn "$keyW" "$1" | cut -d":" -f1 |
   while IFS=: read -r n x; do
      printf "%s:%s\n" "$1" "$n"
   done
' {} {} \;

Notes:
grep has to be run 1/per file is the limiation for this method.

A: Just filter out the part you don't want:
grep -n … | cut -d : -f 1,2

(This assumes that your file names don't contain colons or newlines.)


text:
Q: set https for tomcat I want to use HTTPS for tomcat. so i make .keystore and uncomment connector in server.xml and restart tomcat service , and port 8443 is opened but when insert my address :
https://my_ip:8443
in address bar of my browser , page just working and search and try and nothing shows up and page never stop and ....
 i could not see the tomcat page .
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
        maxThreads="200" scheme="https" secure="true" SSLEnabled="true"
       keystoreFile="/root/.keystore" keystorePass="password"
       clientAuth="false" sslProtocol="TLS" />


text:
Q: Omnioutliner random sort Is there a way to sort my OmniOutliner columns by a random value for something like picking students in your class at random for groups?

A: To get a random number, use rand() (as seen here). Then sort by the random numbers.


text:
Q: A step function, \$u(t)=1\$, for \$t \gt 0\$. What is the value of \$u(0)\$? What is the value of \$u(t)\$ for \$t=0\$?
we know,
\$u(t)=1\$, for \$t \gt 0\$
\$u(t)=0\$, for \$t \lt 0\$

A: It's all a matter of convention.
In mathematics they often define \$u(0) = \frac{1}{2}\$, which is called the half-maximum convention:

If you only want values of 0 and 1 (and not the \$\frac{1}{2}\$) then they usually define \$u(0) = 1\$, which is called the discrete form:
\$u(t)=\begin{cases} 0, & n < 0, \\ 1, & n \ge 0 \end{cases}\$
More information about this function is here: http://en.wikipedia.org/wiki/Heaviside_step_function

A: It doesn't matter.  Arguing about it is pointless.  Pick whatever is convenient from 0 to 1 and move on.
Note that I'm saying this within the context of the being a engineering site.  The condition only exists for a infinitely short time, so as long as the value is not infinite, it will have no effect on any answer.
If you had asked about a discrete function, such as we get by periodic sampling or producing periodic outputs, then this does matter since the value will persist for the time of one sample and therefore will effect the answer.  However, you asked a theoretical and more pointless question, so there is no reason to get into this further.


text:
Q: Send two different emails after form submission When a user submits a form, I want one email to come to me with the form fields and a separate email to be sent to the user confirming their submission (two separate emails with different content).
I tried the following form, but only the first email is generated. The second email is never received.
<?php
$url = "http://www.example.com";

$to = 'info@example.com';
$subject = 'Subject';
$headers .= "From: info@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message .= "Content of Message 1";
mail($to, $subject, $message, $headers);

$message = "";

$to = $_POST['email'];
$subject = 'Subject';
$headers .= "From: info@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message .= "Content of Message 2";
mail($to, $subject, $message, $headers);

$message = "";

echo '<META HTTP-EQUIV=Refresh CONTENT="1; URL='.$url.'">';

?>

What would prevent the second message from sending?

A: Change the variable names,while $to and $subject are overwritten for the second email the concatenating variables..keep concatenating into a double mess.

A: Just do
$to = "info@example.com;$_POST[email]"


text:
Q: Terraform cannot read from remote state Terraform version
v0.12.1
AWS provider version
v2.16.0
I've Terraform workspace configured, as for now my workspace is pointing to dev where I've a tfstate file for my VPCs and Subnets and a different one for my security groups, however when I'm trying to refer vpc_id from my vpc remote tfstate into my security group then I get below error message
No stored state was found for the given workspace in the given backend.

My s3 bucket looks like below
nonprod-us-east-1
  |-- env
         |-- dev
                |-- vpc_subnet/tfstate
                |-- security_group/tfstate

Terraform Configuration Files

Security-Group tf config

terraform {
    backend "s3"{
        # Configuration will be injected by environment variables.
    }
}

provider "aws" {
  region = "${var.region}"
}

data "terraform_remote_state" "vpc_subnet" {
  backend = "s3"

  config = {
    bucket  = "nonprod-us-east-1"
    key     = "vpc_subnet/tfstate"
    region  = "us-east-1"
  }
}

 vpc_id = "${data.terraform_remote_state.vpc_subnet.outputs.vpc_id}"

And I've verified that my vpc_subnet/tfstate  oputputs has vpc_id
Outputs from VPC subnet tf state
outputs": {
    "private_subnet_cidr_blocks": {
      "value": [
        "10.0.3.0/24",
        "10.0.4.0/24",
        "10.0.5.0/24"
      ],
      "type": [
        "tuple",
        [
          "string",
          "string",
          "string"
        ]
      ]
    },
    "private_subnet_ids": {
      "value": [
        "subnet-042a16dd291e90add",
        "subnet-02e8322d996968a3f",
        "subnet-078f525c24015b364"
      ],
      "type": [
        "tuple",
        [
          "string",
          "string",
          "string"
        ]
      ]
    },
    "public_subnet_cidr_blocks": {
      "value": [
        "10.0.0.0/24",
        "10.0.1.0/24",
        "10.0.2.0/24"
      ],
      "type": [
        "tuple",
        [
          "string",
          "string",
          "string"
        ]
      ]
    },
    "public_subnet_ids": {
      "value": [
        "subnet-0ba92a28f6e8ddd95",
        "subnet-08efcb80bed22f4e2",
        "subnet-0b641797bfe207a0b"
      ],
      "type": [
        "tuple",
        [
          "string",
          "string",
          "string"
        ]
      ]
    },
    "vpc_id": {
      "value": "vpc-0bb7595ff05fed581",
      "type": "string"
    }
  }

Expected Behavior
It should be able to read vpc_id from remote tf state location.
Actual Behavior
Failing to read output from remote tf state

A: Finally sorted it out, it comes out to be an issue with bucket key, since I'm using Terraform workspace so the tfstate files are created under folder env:/dev/vpc_subnet/tfstate, after correcting bucket key, it's able to resolve the tfstate files.


text:
Q: php | reverse hebrew string, but without reverse english letters I'd like to print a string on image with imagettftext function, but I've got one problem - the text is hebrew and shown as reverse.
I tried using strrev function (and others) to reverse the string, and it works - but if its has english letters in it - I get reversed english letters as well.
There is a way to reverse the hebrew letters, but saving the english words as they are?

A: I wrote following solution:
function reverseHebrew($text)
{
    $words = array_reverse(explode(' ', $text));
    foreach ($words as $index => $word) {
        if (isHebrew($word)) {
            $words[$index] = mbStrRev($word);
        }
    }
    return join(' ', $words);
}

function isHebrew($text)
{
    for ($i = 0, $cnt = strlen($text); $i < $cnt; ++$i) {
        if (ord($text[$i]) > 127) {
            return true;
        }
    }
    return false;
}

function mbStrRev($string, $encoding = null)
{
    if ($encoding === null) {
        $encoding = mb_detect_encoding($string);
    }

    $length   = mb_strlen($string, $encoding);
    $reversed = '';
    while ($length-- > 0) {
        $reversed .= mb_substr($string, $length, 1, $encoding);
    }

    return $reversed;
}

Usage:
echo reverseHebrew("שלום user");


text:
Q: Annotations for custom graphs in dask How can I specify resources per task in a custom graph like you can achieve with the dask.annotate context manager for dask collections?

A: You can convert the custom graph to a High Level Graph object to add annotations.
Taking the example from the custom graph docs that you linked to:
import dask
from dask.highlevelgraph import HighLevelGraph

def load(filename):
    ...

def clean(data):
    ...

def analyze(sequence_of_data):
    ...

def store(result):
    with open(..., 'w') as f:
        f.write(result)

dsk = {'load-1': (load, 'myfile.a.data'),
       'load-2': (load, 'myfile.b.data'),
       'load-3': (load, 'myfile.c.data'),
       'clean-1': (clean, 'load-1'),
       'clean-2': (clean, 'load-2'),
       'clean-3': (clean, 'load-3'),
       'analyze': (analyze, ['clean-%d' % i for i in [1, 2, 3]]),
       'store': (store, 'analyze')}

with dask.annotate(test="value"):
    dsk = HighLevelGraph.from_collections("test", dsk)


text:
Q: Source Editor Tab order in Netbeans 6.5 I recently switched to Netbeans from Eclipse, and the one thing that I liked about Eclipse I'd like to get in Netbeans:
The order of the tabs at the top of the Source Editor in Eclipse seems to be related to most recently used, so if I have a group of 5 files I'm working on at one time, they are all likely to be visible in the tab list, no matter how many tabs I have open.
In Netbeans, this isn't the case - I don't know what the order is, but it isn't useful for switching between my active files quickly - its usually faster to re-open the file to switch to the correct tab than to actually use the tab system.
Is there an option setting or a plugin that can change this behavior to something more like Eclipse?

A: By default the tabs in NetBeans are ordered acording to when they were opened. I don't think there's a way how to change it right in NetBeans and don't know about any plugin neither. I think this behaviour is just a matter of taste - I was used to NetBeans behaviour and when I'm using Eclipse, I always get confused about shuffled tabs. But as Kevin said you can drag the tabs to change their order.
When you press CTRL + TAB, the documents in the popup window are ordered acording to last used. This might be usefull for you.
Another (partial) solution might be docking a documents window (Window -> Documents) which contains opened documents and where documents are ordered alphabetically. It's better than re-openenig the files (as you wrote) especially if youre files are spread in different packages and you can't see them in projects/files view on one screen.

A: I don't think it does. However, you can drag the tabs to the positions you want them in. I would suggest just ordering by your liking manually.


text:
Q: Bootstrap index download failing in sonarQube job from jenkins When I am running sonarQube job in jenkins, it shows console output as in image. While downloading boot strap index, it shows an error as sonarQube server cannot be reached, but I am able to connect to that server from my local PC using that URL. Can anyone give me solution for this.

A: The above problem has resolved by doing two things
1) Installed java in sonarqube server that is accessible from jenkins
2) Installed right certificates


text:
Q: How to generate a diagram as below? I am a (La)TeX newbie and I have found the following graphic in a document:

I am quite sure it was generated by LaTeX code since you can select every bit of text in the original file.
I am not asking for complete code (though it would be nice), but some starters e.g. what packages to use and what features of such packages. My initial searches indicate TikZ may be appropriate.


text:
Q: DataGridView in C# WinForm I have datagridview on my winform. I have data from some other processes coming frequently that need to be printed on datagridview. Which datagridview event fires frquently where I can print my data? Is it possible by some event or some other approach is required?

A: You can create a methode which is called everytime you need to print the datagridview.
dt2.Rows.Clear(); //clear datagridview
//dt2 is a datatable
//here u can load your data into a datatable or what every you want
dataGridView2.DataSource = dt2;

Put this code into a methode a call it everytime you need it. (e.g. timer every 5 sec)


text:
Q: Blinking cursor in TextView via Thread I want to create a blinking cursor in a TextView.. So far i got this:
    myTv = (TextView)findViewById(R.id.myTv);

    //blinking Cursors Thread
    class CursorThread extends Thread
    {
        public void run()
        {
            while (true)
            {
                myTv.setText("|");

                try
                {
                    sleep(1000);
                }
                catch (InterruptedException e)
                {}

                myTv.setText(" ");

                try
                {
                    sleep(1000);
                }
                catch (InterruptedException e)
                {}
            }
        }
    }
    CursorThread cThread = new CursorThread();
    cThread.start();

If i ran this app i get a crash. What m i doing wrong ?
Im dont know many things about Threads...
Oh and this Thread is an inner class in my MainActivity of course.
Anybody can help ?

A: You must access the UI thread from another thread with the runOnUI method like shown here
runOnUiThread(new Runnable() {
    public void run() {
        keresetTv.setText(" ");
    }
});

or by using a handler.post(new Runnable...);

A: An alternative: subclass TextView and have its onDraw call postInvalidateDelayed() , effecting an invalidate of itself after a number of milliseconds.  Track time between calls in onDraw, and flash the cursor appropriately.

A: You are trying to modify a view from another thread(that is not the main UI thread). You could use a Handler to modify your TextView from CursorThread.


text:
Q: spring boot timing of output @Requestbody and @Responsebody @Before("within(control..*)")
public void before(JoinPoint joinPoint) {
    // Set Process Start Time
    startTime = System.currentTimeMillis();
    Object[] arguments = joinPoint.getArgs();
    if (arguments != null && arguments.length > 0) {
        System.out.println("data:" + arguments[0]);
    }
}

I tried to use @aspect to output tht request body, but if the parameter is wrong when using @valid, spring boot will throw MethodArgumentNotValidException, and @aspect logs will not be output.
How can I output the json request body at the time when server receives a http request even there is an exceptinon happened?

A: I fixed the problem by using @AfterThrowing.
@AfterThrowing(pointcut = "controllerInvocation()", throwing = "exception")
public void afterThrowing(JoinPoint joinPoint, Exception exception) {
    this.outputResponseLog(joinPoint, exception);
}


text:
Q: Show that holomorphic function $f$ is constant if $\Re f$ or $\Im f$ or $|f|$ is constant without using Cauchy Riemann equations Show that if $f$ is holomorphic in a domain $D$ and if one of the functions $|f|$,
$\Re f$, or $\Im f$ is constant on an open subset of $D$, then $f$ is constant on $D$.
(without Cauchy Riemann equations, preferably using Open Mapping Principle).

A: The Open Mapping Theorem states that every non-constant holomorphic function in a domain sends open sets to open sets. Since every domain is open, if $f$ were not constant then $f(D)$ should be open but this cannot be the case if
$\bullet$  $\Re f$ is constant, since in this case $f(D)$ would be included in the vertical line $\{z:\Re z=\Re f\}$ of the complex plane so it couldn't be open.
$\bullet$  $\Im f$ is constant, since in this case $f(D)$ would be included in the horizontal line $\{z:\Im z=\Im f\}$ of the complex plane so it couldn't be open.
$\bullet$  $|f|$ is constant, since in this case $f(D)$ would be included in the circle $\{z:|z|=|f|\}$ of the complex plane so it couldn't be open.


text:
Q: How to reset CRM 2011 form data after an exception thrown in plugin Folks,
Sometime  when a plugin is triggered and during execution an exception has occured, the CRM 2011 form which is going to be updated showing raw data in various fields. Some fields showing data before I modified them and some showing other but not the data that I have entered. Because after save()  the form reload, Is there any way to cancel the save() operation from whithin plugin or somehwere from JS  to avoid the form showing raw data.
Currently when this happens I compare the server side data with the client side data and reset the form again. Is there any other way around??

A: When Plugin was thrown errr all of operations will be rollback. You just need to refresh your form(use F5 to refresh browser).


text:
Q: about jpa sequence generation Hello every body I have used following code in my jpa project for working of sequence
generation,its giving exception that pre-allocation size is not set correctly,but
I have been set it correctly,interesting fact is its runing successfully and working
correctly when I am trying to run it second time and so on.please tell me the problem
why its not working first time.
 @Id
      @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="studentgen")
      @SequenceGenerator(name="studentgen", sequenceName="myseq", allocationSize=100)
      private int id;

A: Are you sure you have the same sequence in your DB (sequenceName="myseq") ?
Also, you have set the allocated size to 100, which means you have to have the step size in your sequence to be 100 as well.
Example:
Create Sequence myseq start with 1 maxvalue 99999999 increment by 100


text:
Q: Adding and transitioning animations in SceneKit I looked at Banana game from WWDC which is written in Objective-C was trying to convert the code to Swift for importing animation and transitioning between them but I am having problems running the animations in swift from DAE files.
I have exporter DAE files in both AutoDesk format from 3dsMax and in openCollada format. The Autodesk format the animation is for each bone so I am unable to call an animation by name so I just import the scene and do the following for the animation to start as soon as the file loads.
scene = SCNScene(named: "monster.scnassets/monsterScene.DAE")
scene2 = SCNScene(named:"monster.scnassets/monster.DAE")

var heroNode = SCNNode()
heroNode = scene.rootNode.childNodeWithName("heroNode", recursively: false)!

var nodeArray = scene2.rootNode.childNodes

for childNode in nodeArray {
    heroNode.addChildNode(childNode as SCNNode)
}

Although the animation plays as soon as the scene starts I done know how to store the animation.
If I export the collada file using openCollada. I can use the following to run the get and run the animation as there is just one animation for the whole object instead of each bone in case of AutoDesk collada format. By this way I can store the animation also using CAAnimation.
var anim = scene2.rootNode.animationForKey("monster-1")
childNode.addAnimation(anim, forKey: "monster-1")

But then the character runs at an angle and also runs back and forth instead of running at the same spot.
Also the lighting is better using openCollada. I just would like to use openCollada instead of autodesk collada export. Right now I am using openCollada format for exporting the scene and autodesk for exporting character.
How do store animations in SceneKit/Swift and transition between them? Thanks.

A: If you don't change the default options when loading a scene from a file, all animations in the scene immediately and automatically attach to their target nodes and play. (See the Animation Import Options in the SceneKit API reference.)
If you want to load the animations from a scene file and hold on to them for attaching to nodes (that is, playing) later, you're better off loading them with the SCNSceneSource class. In addition, you can (but don't have to) store your base model in one file and animations in other files.

Just look at this Bananas animation loading code. Just look at it.*
// In AAPLGameLevel.m:
SCNNode *monkeyNode = [AAPLGameSimulation loadNodeWithName:nil fromSceneNamed:@"art.scnassets/characters/monkey/monkey_skinned.dae"];
AAPLMonkeyCharacter *monkey = [[AAPLMonkeyCharacter alloc] initWithNode:monkeyNode];
[monkey createAnimations];

// In AAPLSkinnedCharacter.m (parent class of AAPLMonkeyCharacter):
+ (CAAnimation *)loadAnimationNamed:(NSString *)animationName fromSceneNamed:(NSString *)sceneName
{
    NSURL *url = [[NSBundle mainBundle] URLForResource:sceneName withExtension:@"dae"];
    SCNSceneSource *sceneSource = [SCNSceneSource sceneSourceWithURL:url options:nil ];
    CAAnimation *animation = [sceneSource entryWithIdentifier:animationName withClass:[CAAnimation class]];
    //...
}

// In AAPLMonkeyCharacter.m:
- (void)update:(NSTimeInterval)deltaTime
{
    // bunch of stuff to decide whether/when to play animation, then...
    [self.mainSkeleton addAnimation:[self cachedAnimationForKey:@"monkey_get_coconut-1"] forKey:nil];
    //...
}

What's going on here:

*

*There's a custom class managing the animated character. It owns a SCNNode containing the character model, as well as a bunch of CAAnimations for all of the things the model can do (idle/jump/throw/etc).

*That class is initialized by passing the character node loaded from one DAE file. (AAPLGameSimulation loadNodeWithName:fromSceneNamed: is a convenience wrapper around loading a SCNScene from a file and grabbing a named node out of it.) That DAE file contains only the character model, with no animations.

*Then, AAPLMonkeyCharacter loads (and stores references to) the animations it needs from the separate DAE files containing each animation. This is where SCNSceneSource comes in — it lets you grab animations out of the file without playing them.

*When it's time to play, the monkey class calls addAnimation:forKey: to run the animation on its main node.

Translating to Swift and applying to your problem — where you seem to have all animations in the same file — I'd do something like this (vague outline of a hypothetical class):
class Monster {
    let node: SCNNode
    let attackAnimation: CAAnimation

    init() {
        let url = NSBundle.mainBundle().URLForResource(/* dae file */)
        let sceneSource = SCNSceneSource(URL: url, options: [
            SCNSceneSourceAnimationImportPolicyKey : SCNSceneSourceAnimationImportPolicyDoNotPlay
        ])
        node = sceneSource.entryWithIdentifier("monster", withClass: SCNNode.self)
        attackAnimation = sceneSource.entryWithIdentifier("monsterIdle", withClass: CAAnimation.self)
    }

    func playAttackAnimation() {
        node.addAnimation(attackAnimation, forKey: "attack")
    }
}

The key bits:

*

*SCNSceneSourceAnimationImportPolicyDoNotPlay makes sure that nodes loaded from the scene source don't start with animations attached/playing.

*You have to load the animations separately with entryWithIdentifier:withClass:. Be sure to configure them how you like (repeating, fade duration etc) before attaching to the nodes.

A: 2022 code fragment.
In terms of the swift sample in @rickster 's answer.
It seems the code is now more like:
let p = Bundle.main.url(forResource: "File Name", withExtension: "dae")!
source = SCNSceneSource(url: p, options: nil)!

let geom = source.entryWithIdentifier("geometry316",
   withClass: SCNGeometry.self)!
   as SCNGeometry
yourDragonNode = SCNNode(geometry: geom)

yourAnime = source.entryWithIdentifier("unnamed_animation__0",
   withClass: CAAnimation.self)!

In terms of how to get the "mystery strings":
"geometry316" and "unnamed_animation__0" in the example.
notice: https://stackoverflow.com/a/75088130/294884
and: https://stackoverflow.com/a/56787980/294884


text:
Q: How to add dynamic filter by fields (comma separated) , sorting , pagination in rest api? Below is the simple code block of the rest API with get method.
right now I have added limit parameters but I want to add Pagination , result per page , SortByFields , SortBy *(asc or desc) , filter (by multiple fields)
paths:
  /pets:
    get:
     description: Returns all pets
     produces:
     - application/json
     parameters:
     - name: limit
       in: query
       description: SET LIMIT OF THE RESULT
       type: integer
       format: int32
       required: false

How can I do this?

A: OpenStack have published an specification that

serves to provide guidance on how to handle the pagination of large
  result sets and the best ways to provide filtering and sorting
  capabilities in a project's public REST API.

If using the swagger-editor, The included example twitter.yaml has some basic filtering and pagination.
See also Pagination in a REST web application
Spring Data REST - Reference Documentation also explains these concepts well in Chapter 6, Paging and Sorting.


text:
Q: dynamic defaultValue on input type not working I have a input type
<input defaultValue={this.getValue(labelName)} type="text" name={labelName} className="form-control" id={labelCateg+':'+labelName}  onChange={(e)=>{this.handleChange(e,labelName)}}/>

If i specify the defaultValue="something" , it works
when i make it dynamic , on dev tools , it shows the value under value attribute but not on the view.

A: Changed it to controlled component . onChange changes the value at the source which indirectly changes the value on the dom on rerender


text:
Q: How to add custom image on native map in Titanium? currently i am working on native map in Titanium for android and iOS.
you might have seen native maps on which a custom image layer or layout is being displayed, which will rotate and zoom according to the user input (currently i am not talking about annotations)
i have tried using annotation map tile too but it doesn't seems to work as the native map app i have seen
if you have any question or are not able to understand my question please let me know so i could clarify and get solution for one of you
Update:
Can you give a better explanation of what you've tried?
you might already know about mapbox.com and leafletjs.com, by using their library we could make customize maps and offline map in webview but i am looking for some Titanium module which could help me use native map of iOS and android for performing similar functionalities(i am avoiding commercial library and plugins as my app is not commercial app). i want to create map tiles which could be used for offline purpose as the user would have downloaded with the app.
what i have tried yet!!
1: http://i.stack.imgur.com/CLiNh.jpg
2: http://i.stack.imgur.com/QOLO7.jpg
in first image link i have given image in which i showing screenshot of map with rotation (if you notice compass) and the map tile moved accordingly to it
in 2nd image ... i had put a map tile using createAnnontation function, but unable to fix its layout remains same and it doesn't resize when i do zoom in/out too

A: I assume you are talking about custom tiles on top of a MapView.
There is an example module for iOS at https://github.com/benbahrenburg/benCoding.Map which used the Titanium map module as a base. It is a bit dated, but see the TileOverlay example and code and it will get you on the right track.
The best tutorial I've found on how to create the tiles is at http://www.ericbinnion.com/creating-custom-overlays-for-ios-mapkit-framework/
I've tried to create a similar TileOverlay functionality by forking the Android map module with limited success.  I never got it to work as well as the native maps.
You could also check out using Mapbox with Titanium.  There are great tutorials and tools for creating your own tiles layers and manipulating existing layers.  Adam Paxton gave a great demo of it at TiConf in New York this year.


text:
Q: node.js and jsdom - no way to detect that an http 500 error was returned? I'm using jsdom with node.js and I'm trying to get it to provide me with some indication that an http error has occurred. I've set up a test server that simply returns an http 500 header for all requests, but when I attempt to load it with jsdom, jsdom doesn't throw any error and doesn't seem to provide me with any information that would identify that an http 500 error was returned. What's the best way to detect an http 500 error?

A: I looks like jsdom doesn't check status codes. 500 status codes are not considered errors by Node's HTTP module, so they're considered a correct response by jsdom.
I suggest you test the status code yourself before using jsdom and pass jsdom the body of your response, ie:
var jsdom = require('jsdom').jsdom;
var request = require('request');  //jsdom already uses request*

request("http://www.google.com/", function (err, response, body) {
  if (!err && response.statusCode == 200) {
    jsdom.env(body, function (errors, window) {
      // your code
    });
  }
});

[*] Request module: https://github.com/mikeal/request


text:
Q: Foreach every Subitem in a MenuStrip I want to get all the SubItems of my MenuStrip, So I can change them all at once.
I'am trying things like the following, but they aren't working:
foreach (ToolStripMenuItem toolItem in menuStrip1.DropDownItems)
{
      //Do something with toolItem here
}

Can someone help me out coding a good foreach loop for getting all the SubMenuItems(DropDownItems) from the MenuStrip?
EDIT now trying to work with the following Recursive method:
private void SetToolStripItems(ToolStripItemCollection dropDownItems)
        {
            try
            {
                foreach (object obj in dropDownItems)
                {
                    if (obj.GetType().Equals(typeof(ToolStripMenuItem)))
                    {
                        ToolStripMenuItem subMenu = (ToolStripMenuItem)obj;

                        if (subMenu.HasDropDownItems)
                        {
                            SetToolStripItems(subMenu.DropDownItems);
                        }
                        else
                        {

                        }
                    }
                }
            }
            catch
            {

            }
        }

A: Try this:
List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem toolItem in menuStrip.Items)
{
    allItems.Add(toolItem);
    //add sub items
    allItems.AddRange(GetItems(toolItem));
}
private IEnumerable<ToolStripMenuItem> GetItems(ToolStripMenuItem item)
{
    foreach (ToolStripMenuItem dropDownItem in item.DropDownItems)
    {
        if (dropDownItem.HasDropDownItems)
        {
            foreach (ToolStripMenuItem subItem in GetItems(dropDownItem))
                yield return subItem;
        }
        yield return dropDownItem;
    }
}

A: Modification of Vale's answer. Separators will not crash this version and they will also be returned ( menuStripItems is a ToolStripItemCollection. ie: this.MainMenuStrip.Items ):
    /// <summary>
    /// Recursively get SubMenu Items. Includes Separators.
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    private IEnumerable<ToolStripItem> GetItems(ToolStripItem item)
    {
        if (item is ToolStripMenuItem)
        {
            foreach (ToolStripItem tsi in (item as ToolStripMenuItem).DropDownItems)
            {
                if (tsi is ToolStripMenuItem)
                {
                    if ((tsi as ToolStripMenuItem).HasDropDownItems)
                    {
                        foreach (ToolStripItem subItem in GetItems((tsi as ToolStripMenuItem)))
                            yield return subItem;
                    }
                    yield return (tsi as ToolStripMenuItem);
                }
                else if (tsi is ToolStripSeparator)
                {
                    yield return (tsi as ToolStripSeparator);
                }
            }
        }
        else if (item is ToolStripSeparator)
        {
            yield return (item as ToolStripSeparator);
        }
    }

Populate a list:
    List<ToolStripItem> allItems = new List<ToolStripItem>();
    foreach (ToolStripItem toolItem in menuStripItems)
    {
       allItems.Add(toolItem);
       //add sub items
       allItems.AddRange(GetItems(toolItem));
    }

Loop the list:
     foreach(ToolStripItem toolItem in allItems)
     {
          if(toolItem is ToolStripMenuItem)
          {
             ToolStripMenuItem tsmi = (toolItem as ToolStripMenuItem);
             //Do something with it
          }
          else if(toolItem is ToolStripSeparator)
          {
             ToolStripSeparator tss = (toolItem as ToolStripSeparator);
             //Do something with it
          }
     }

A: It seems you cannot do it with direct 'foreach' approach. I think I figured it out.
List<ToolStripMenuItem> l = new List<ToolStripMenuItem> { };
        l.Add(menuItem1);
        l.Add(menuItem2);

        foreach (ToolStripMenuItem m in l)
        {
            m.Text = "YourTextHere";
        }

Adding menu items manually to a list is a bit barbarian, but using 'foreach' or 'for' or other cycles gave me the same error. something about enumeration. It seems like they cannot count all the menu items by themselves :P On the other hand, if you have items like seperators and other stuff, that is not quite like a simple menu item, putting them all in one list and trying to rename would raise another problem.
This is for changing the text displayed on menu items, but you can do absolutely anything you want with them using this method.

A: You've actually got the type wrong, DropDownItems contains a collection of ToolStripItem not a collection of ToolStripMenuItem.
Try this instead:
foreach (ToolStripItem toolItem in menuStrip1.DropDownItems)
{
    //do your stuff
}

Or in your function:
private void SetToolStripItems(ToolStripItemCollection dropDownItems)
{
    foreach (ToolStripItem item in dropDownItems)
    {
        if (item.HasDropDownItems)
        {
            SetToolStripItems(item.DropDownItems);
        }
    }
}

A: For .net 4.5 and above I've used this to get dropdownitems for a specific toolstripmenuitem.
foreach (var genreDropDownItem in this.toolStripMenuItem_AddNewShowGenre.DropDownItems)
    {
        if (genreDropDownItem is ToolStripMenuItem) //not a ToolStripSeparator
        {
            ToolStripDropDownItem genreItem = (genreDropDownItem as ToolStripDropDownItem);

            genreItem.Click += toolStripMenuItem_Genre_Click; //add the same click eventhandler to all dropdownitems of parent item this.toolStripMenuItem_AddNewShowGenre
        }
    }

A: Below is an extension class to get all ToolStripMenuItems.  The advantage here is that all code is in one recursive method.  One can easily convert this to a generic method if other menu item types are needed.
public static class ToolStripItemCollectionExt
{
    /// <summary>
    /// Recusively retrieves all menu items from the input collection
    /// </summary>
    public static IEnumerable<ToolStripMenuItem> GetAllMenuItems(this ToolStripItemCollection items)
    {
        var allItems = new List<ToolStripMenuItem>();
        foreach (var item in items.OfType<ToolStripMenuItem>())
        {
            allItems.Add(item);
            allItems.AddRange(GetAllMenuItems(item.DropDownItems));
        }
        return allItems;
    }
}

A: Please note that "aren't working" is a very inefficient description. You should post the error message or behaviour.
foreach(var item in menuStrip1.Items)
{
 // do something with item... maybe recursively
}

There is a nice explanation of it here

A: Here is a very simple solution
foreach (Control Maincontralls in MDIParent1.ActiveForm.Controls) //start it from the form - in this example i started with MDI form
{
    if (Maincontralls.GetType() == typeof(MenuStrip)) // focus only for menu strip
    {
        MenuStrip ms = (MenuStrip)Maincontralls; //convert controller to the menue strip contraller type to access its unique properties

        foreach (ToolStripMenuItem subitem in ms.Items ) // access each items
        {

            if (subitem.Name == "loginToolStripMenuItem") subitem.Text = "Change text in loginToolStripMenuItem";
            //focus controller by its name and access its properties or whatever you wants
        }
        break; //break out the loop of controller of the form coz u don't need to go through other controllers
    }

}


text:
Q: Cleanly overriding parts of a theme locally in Flutter I have a widget which has two TextFields as descendants. I would like to apply the same styling to these TextFields. My understanding is that the right way to do this is to apply a localized theme to my widget tree. The following is my attempt. This is a code snippet from my root widget's build function. Is there not a cleaner way to do this?
final ThemeData _themeData = Theme.of(context);
return Theme( // HACK
  data: _themeData.copyWith(
    inputDecorationTheme: InputDecorationTheme(
      border: OutlineInputBorder(),
    ),
    textTheme: _themeData.textTheme.copyWith(
      subhead: _themeData.textTheme.subhead.copyWith(
        fontSize: 30.0,
      ),
    ),
  ),
  child: _buildTheRestOfMyWidgetTree(context),
);

The thing that I am annoyed by is that to override a single property (_themeData.textTheme.subhead.fontSize), I have to explicitly and manually make copies of three intermediate data structures (_themeData, then _themeData.textTheme, then _themeData.textTheme.subhead).

A: It would help if you packaged that part of the code up and made it a widget so that your tree is cleaner. That's how it's done in this example.
class TextFieldOverride extends StatelessWidget {
  const TextFieldOverride({this.child});
  final Widget child;
  @override
  Widget build(BuildContext context) {
    final themeData = Theme.of(context);
    return Theme(
      child: child,
      data: themeData.copyWith(
        inputDecorationTheme: InputDecorationTheme(
          border: OutlineInputBorder()),
      textTheme: themeData.textTheme.copyWith(
        subhead: themeData.textTheme.subhead.copyWith(
          fontSize: 30.0))));
  }
}

...

TextFieldOverride(
  child: TextField(...)
)

Or if there are few places the code will be duplicated, you can just make the changes directly:
...
child: TextField(
  style: Theme.of(context).textTheme.subhead.copyWith(fontSize: 30.0),
  decoration: InputDecoration(border: OutlineInputBorder(),
    ...
  )
)

Or perhaps the best choice is to create a function that does the above for you.
TextField buildTextField(BuildContext context) => TextField(
  style: Theme.of(context).textTheme.subhead.copyWith(fontSize: 30.0),
  decoration: InputDecoration(border: OutlineInputBorder(),
    ...
  )
)

A: While I can understand the frustration of having to "copy" everything, this is how you should do it.
Data are immutable in Flutter. You cannot mutate them, you are forced to clone them with different properties.
Therefore your assumption is correct: If you want to modify a nested property, you have to clone all of its parents too. Which leads to:
final ThemeData theme = Theme.of(context);
theme.copyWith(
  textTheme: theme.textTheme.copyWith(
    subhead: theme.textTheme.subhead.copyWith(
      fontSize: 30.0,
    ),
  ),
);

Again: you cannot avoid it.


text:
Q: How to decompress and compress files in SSIS I have a script that generates all the zip files. I want to decompress it to .csv files and then again compress it to .gz files. Is it possible with the cozyroc zip task?

A: You can use any command line utility like 7 zip .
Execute the command using Execute process task .
Please go throw below link it is describing step by .
step.https://dataintegrity.wordpress.com/2009/10/13/dynamically-zipping-files-in-ssis/


text:
Q: iMac (21.5-inch, Late 2013), I need to disable the camera completely I've been looking around for a solution to disable the camera on these iMac's but coming up empty. One popular solution was going into the Quicktime folder and removing the "QuickTimeUSBVDCDigitizer.component" but none of these machines have that file anyway. I'm in a correctional environment and these cameras needs to be removed or disabled. Since removing the physical camera ain't a option what else can I do?  Already someone figured out a work around the parental control and so that's why im here lol...  Thanks for reading...

A: Temporary - tape over the lens.  More permanent - black nail polish over the lens or spike the lens (nail or icepick).  If you have the chops, you could try and disassemble and get to the CCD.  Not sure if this was a separate board on onboard the mobo.


text:
Q: How would you process an image puzzle webapp on either the server side or the client side? I am building a web app game which simply takes an image file as an input from the filesystem, divides the image into blocks, then puts the image blocks randomly so that the client-side user can relocate the blocks to restore the original image.
The platform I will be using is Elixir/Phoenix language/framework on the backend and VueJS on the front end. When I tried to manipulate image with Erlang, I had some difficulty to find libraries for pixel manipulation. But then I thought, if every user's puzzle image will have to be created on the server, it will cost a lot of resources anyway.
Do you think it's better to send the image from the server's filesystem to a client-side and create the image blocks on the client-side with Javascript or you would do it with Erlang/Elixir on the server side?
What would be your preferred method on a scientific basis, pros and cons?

A: I would go with ImageMagick command line wrapper.
As by cropping documentation, somewhat like below would do:

convert my_image: -repage 60x40-5-3 \
 -crop 30x20 +repage my_image_tiles_%d.png`

Although there is an Elixir wrapper for IM, called Mogrify, it implements a limited set of operations, so I usually go with System.cmd/3.
For each input file you might create tiles and next time the file is being accessed, you might start with a check. If the file was already cropped, just serve the tiles, otherwise crop it before serving tiles. This would be basically a clean server-side one-liner, prone to reverse engineering, unlike client-side solutions.

A: This is how i am doing it.
# Args Explantion :
    # -resize 72x72! - Resizes the passed Image, `!` means don't care about aspect ratio
    # -crop 24x24 - Crops the image
    # -scene 1 - Start naming the cropped images starting with index 1
    # -%02d - produces output such as 00, 01, 02, 03
    # image_size - Actual image size
    # seg_size - Size of small segments/cropped images
    list = [
      "#{img_path}",
      "-resize",
      "#{image_size} x #{image_size}!",
      "-crop",
      "#{seg_size} x #{seg_size}",
      "-scene",
      "1",
      "#{new_tmp}/%02d.png"
    ]

    System.cmd("convert", list)