text:
Q: Remove period then email extension after '@' into new column to extract first and last name information I have a list of emails that are in the format firstname.lastname@email.com. I would like to create a new column with only the first and last name extracted from the email address.
I am using PySpark. This is an example of the desired output:
data = [{"Email": "john.doe@email.com", "Role": "manager"},
{"Email": "jane.doe@email.com", "Role": "vp"}]

df = spark.createDataFrame(data)

type(df)

# original data set
+------------------+-------+
|Email             |Role   |
+------------------+-------+
|john.doe@email.com|manager|
|jane.doe@email.com|vp     |
+------------------|-------+

# what I want the output to look like
+------------------+-------+--------+
|Email             |Role   |Name    |
+------------------+-------+--------+
|john.doe@email.com|manager|john doe|
|jane.doe@email.com|vp     |jane doe|
+------------------|-------|--------+

How can I remove the period, replace it with a space, then drop everything after the @ into a new column to get the names like the example above?

A: It will replace the . and @... with a space   which we'll have to trim from the end.
from pyspark.sql import functions as F

df.withColumn('Name', F.trim(F.regexp_replace('Email', '\.|@.*', ' '))).show()
# +------------------+-------+--------+
# |             Email|   Role|    Name|
# +------------------+-------+--------+
# |john.doe@email.com|manager|john doe|
# |jane.doe@email.com|     vp|jane doe|
# +------------------+-------+--------+

A: You can use Python's .split method for strings and a loop to add a "Name" field to each record in your list.
for d in data:
    d["Name] = " ".join(d["Email"].split("@")[0].split("."))

In the above loop we split the "Email" field at the "@" character, creating a list of two elements, of which we take the first one, and then split that on the character ".", which gives us the first and last name.  Then we join them with a space (" ") in between.

A: You can use regex_extract and regex_replace.
from pyspark.sql import functions as F
df = df.withColumn('Name', F.regexp_extract(
        F.regexp_replace('Email', '\.', ' '),
        '(.*)@',
        1)
     )

First, regexp_replace('Email', '\.', ' ') will replace . to space in Email column.
Then, regexp_extract(..., '(.*)@', 1) will extract the 1st capture group.
Regex explanation
(.*) => .* is any characters with any length. Wrap with () to make a capture group.
@ => match @ mark.

(.*)@ => 1st Capture group will capture any characters before @.


text:
Q: Get set-cookie header from redirect php Okay, I haven't been able to find a solution to this as of yet, and I need to start asking questions on SO so I can get my reputation up and hopefully help out others.
I am making a wordpress plugin that retrieves a json list of items from a remote site. Recently, the site added a redirecting check for a cookie.
Upon first request without the cookie, 302 headers are provided, pointing to a second page which also returns a 302 redirect pointing to the homepage. On this second page, however, the set-cookie headers are also provided, which prevents the homepage from redirecting yet again.
When I make a cURL request to a url on the site, however, it fails in a redirect loop.
Now, obviously the easiest solution would be to fix this on the remote server. It should not be implementing that redirect for api routes. But that at the moment is not an option for me.
I have found how to retrieve the set-cookie header value from a 2** code response, however I cannot seem to figure out how to access that value when 302 headers are provided, and cURL returns nothing but an error.
Is there a way to access the headers even when it reaches the maximum (20) redirects?
Is it possible to stop the execution after a set number of redirects?
How can I get this cookie's value so I can provide it in a final request?

A: You already had problems before you started trying to add cookies into the mix. Doing a single redirect is bad for performance. Using a 302 response as a means of dissociating data presentation from data retrieval under HTTP/1,1 or later is bad (it works, but is a violation of the protocol - you should be using a 303 if you really must redirect).
Trying to set a cookie in a 3xx response will not work consistently across browsers. Setting a cookie in an Ajax response will not work consistently across browsers.

It should not be implementing that redirect for api routes

Maybe the people at the remote site are trying to prevent you leeching their content?
Fetch the homepage first in an iframe to populate the cookie and record a flag in your domain on the browser.

A: I actually found another SO question, of course after I posted, that lead me in the right direction to make this possible, HERE
I used the WebGet class to make the curl request. It has not been maintained for three years, but it still works fine.
It has a function that makes the curl request without following through on the redirect loop.
There are a lot of curl options set in that function, and curl is not returning an error in it, so I'm sure the exact solution could be simpler. HERE is a list of curl options for anyone who would like to delve deeper.
Here is how I handle each of the responses to get the final response
        $w = new WebGet();

        $cookie_file = 'cookie.txt';

        if (!file_exists($cookie_file)) {
            $cookie_file_inter = fopen($cookie_file, "w");
            fclose($cookie_file_inter);
        }

        $w->cookieFile = $cookie_file; // must exist and be writable
        $w->requestContent($url);

        $headers = $w->responseHeaders;

        if ($w->responseStatusCode == 302 && isset($headers['LOCATION'])) {
            $w->requestContent($headers['LOCATION']);
        }

        if ($w->responseStatusCode == 302 && isset($headers['LOCATION'])) {
            $w->requestContent($headers['LOCATION']);
        }

        $response = $w->cachedContent;

Of course, this is all extremely bad practice, and has severe performance implications, but there may be some rare use cases that find themselves needing to do this.

A: If you use the cURL option CURLOPT_HEADER the data you get back from curl_exec will include the headers from each response, including the 302.
If you enable cookie handling in cURL, it should pick up the cookie set by the 302 response just fine unless you prefer to handle it manually.
I often do something like this when there could be multiple redirects:
$ch = curl_init($some_url_that_302_redirects);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, ''); // enable curl cookie handling

$result = curl_exec($ch);
// $result contains the headers from each response, plus the body of the last response

$info   = curl_getinfo($ch); // info will tell us how many redirects were followed

for ($i = 0; $i < intval($info['redirect_count']); ++$i) {
    // get headers from each response
    list($headers, $response) = explode("\r\n\r\n", $response, 2);

    // DO SOMETHING WITH $headers HERE
    // If there was a redirect, headers will be all headers from that response,
    // including Set-Cookie headers
}

list($headers, $body) = explode("\r\n\r\n", $response, 2);

// Now $headers are the headers from the final response
// $body is the content from the final response

redpajama_set_name: RedPajamaStackExchange


text:
Q: AIrtel js files loading while connecting to most websites I am not using airtel internet. When I am trying to open few websites, they show up like they are blocked. If I see inspect and there are 2 javascript files injected somehow. One is http://www.airtel.in/dot/js/jquery-1.11.1.min.js and other is common.js. Eventhough I am not using airtel for internet, I don't understand how it is connecting and injecting these files. I have even tried deleting cookies and cache but it doesn't help. I also tried disabling all addons.
Let me know if there's a solution for this or if it's possible to delete and block those js files from getting loaded.


text:
Q: Is there an analogue to Bertrand's Postulate for primes for perfect powers? Is there an analogue to Bertrand's Postulate for primes for perfect powers?
Bertrand's Postulate: $\forall x \gt 1 \in \mathbb{Z}, \exists p \in \mathbb{P}$ such that $x < p < 2x$.
For perfect powers, could we say something like $\exists k,m,\lambda \in \mathbb{Z}, m \gt 2$ such that $\forall x \in \mathbb{Z}, x \gt 2$, $x \lt k^m \le \lambda x$? Obviously if $\lambda \ge x^2$, we have $(k,m) = (x, 3)$ as a satisficatory perfect power in the range.
This question came up while thinking about this other MSE question I had posted and received an answer. I am interested in knowing how close to $x$ are we likely to find a perfect power $k^m \gt x$ with an exponent $m\gt2$?


text:
Q: IronPython Requests Error: expected  I'm new in python, I'm trying to post to https API with  JSON I use IronPython 2.7 and requests, python 2.7
here is my code
import requests
import json

def PostData(uri, Timestamp, ProxyIP, ProxyPort, username, password, UserAgent, Joson):

   payload = {"Timestamp": Timestamp}
   headers = {"user-agent": UserAgent,
              "ContentType" :"application/json"}

   r = requests.post(uri,params=payload,json=json.dumps(Joson))

   return r.text

but I always get error :
IronPython Requests Error: expected <type 'bytes'>

even if I just use
requests.post(uri)
how to fix this problem? Thanks for help

A: Have you tried passing bytes as uri:
requests.post(bytes(str(uri).encode("utf-8")))


text:
Q: Why doesn't boost::serialization check for tag names in XML archives? I'm starting to use boost::serialization on XML archives. I can produce and read data, but when I hand-modify the XML and interchange two tags, it "fails to fail" (i.e. it proceeds happily).
Here's a small, self-complete example showing what I see:
#include <iostream>
#include <fstream>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_member.hpp>
using namespace std;

int main (void)
{
  boost::archive::xml_oarchive oa (cout);
  static const string producer = "XXX", version  = "0.0.1";
  oa << boost::serialization::make_nvp ("producer", producer);
  oa << boost::serialization::make_nvp ("producer_version", version);
}

This writes XML to standard output, which contains:
<producer>XXX</producer>
<producer_version>0.0.1</producer_version>

Now, I replace all the code in the main function with a reader:
  boost::archive::xml_iarchive ia (cin);
  string producer, version;
  ia >> boost::serialization::make_nvp ("producer", producer);
  ia >> boost::serialization::make_nvp ("producer_version", version);
  cout << producer << "  " << version << endl;

which works as expected when fed the previous output (outputs "XXX  0.0.1"). If, however, I  feed it XML in which I changed the order of the two lines "producer" and "producer_version", it still runs and outputs "0.0.1  XXX".
Thus, it fails to recognize that the tags don't have the expected names, and just proceed. I would have expected it to thrown a xml_archive_parsing_error exception, as indicated in the doc.
Does someone here have experience with that? What I am doing wrong?

A: Just changing the order of the two lines won't cause an xml_archive_parsing_error exception. The doc you've linked says that itself:

(...)This might be possible if only the data is changed and not the XML attributes and nesting structure is left unaltered.(...)

You haven't changed attributes and the order change has kept the structure (still two fields on the first level of your XML). No exception will ever be thrown this way.
Also, when reading a XML using the make_nvp function, the name parameter won't put any restriction on what is being read. It will just tell arbitrarily the name to be used with the new name-value pair.
So, you can change the name of your XML tags on your input, as long you don't change your expected order i.e. you could rename producer and producer_version on your XML to foo and bar and still would read the serialized data correctly i.e.:

<foo>XXX</foo>
<bar>0.0.1</bar>

And your printed answer would still be "XXX 0.0.1".
Since this only formatting your serialized data as a XML, there is no interest in checking the tag names. They are only used for making your serialized output more readable.


text:
Q: Change value in QueryUtils for each fragment How could I change the index value of a json object existing in my QueryUtils file from inside a Fragment?
This part right here: JSONObject currentDay = dayArray.getJSONObject(0);
I want the index value to change for each fragment but couldn't wrap my head around it. I have tried with intents and creating a constructor but failed.
As is right now, the app is 'working' with all fragments displaying the schedule for Monday (JSONObject index 0).
QueryUtils.java
import android.text.TextUtils;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public final class QueryUtils {

    private static final String LOG_TAG = QueryUtils.class.getSimpleName();

    //makeHttpRequest constants
    private static final int READ_TIMEOUT = 10000 /* milliseconds */;
    private static final int CONNECT_TIMEOUT = 15000 /* milliseconds */;
    private static final int RESPONSE_CODE = 200 /*everything is OK*/;

    public QueryUtils() {
    }

    public static List<Day> fetchDayData(String requestUrl) {

        URL url = createUrl(requestUrl);

        String jsonResponse = null;
        try {
            jsonResponse = makeHttpRequest(url);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem making the HTTP request.", e);
        }

        List<Day> days = extractFeatureFromJson(jsonResponse);

        return days;
    }

    private static URL createUrl(String stringUrl) {
        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Problem building the URL ", e);
        }
        return url;
    }
    private static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";

        if (url == null) {
            return jsonResponse;
        }

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;

        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(READ_TIMEOUT);
            urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            if (urlConnection.getResponseCode() == RESPONSE_CODE) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } else {
                Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving Berceni JSON results.", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }

    private static List<Day> extractFeatureFromJson(String dayJSON) {

        if (TextUtils.isEmpty(dayJSON)) {
            return null;
        }

        List<Day> days = new ArrayList<>();

        //Try to parse
        try {

            JSONObject baseJsonResponse = new JSONObject(dayJSON);

            JSONArray dayArray = baseJsonResponse.getJSONObject("schedule").getJSONArray("day");

            JSONObject currentDay = dayArray.getJSONObject(0);
            JSONArray getClasses = currentDay.getJSONArray("classes");

                for (int j = 0; j < getClasses.length(); j++) {
                    JSONObject currentClass = getClasses.getJSONObject(j);

                     String retrieveCourseTitle = currentClass.getString("class");
                     String retrieveCourseTime = currentClass.getString("time");
                     String retrieveCourseTrainer = currentClass.getString("trainer");
                     String retrieveCourseCancelState = currentClass.getString("canceled");

                     Day day = new Day(retrieveCourseTitle, retrieveCourseTime, retrieveCourseTrainer, retrieveCourseCancelState);
                     days.add(day);
                }

        } catch (JSONException e) {
            // If an error is thrown when executing any of the above statements in the "try" block,
            // catch the exception here, so the app doesn't crash. Print a log message
            // with the message from the exception.
            Log.e("QueryUtils", "Problem parsing JSON results", e);
        }

        return days;
    }

}

And my FragmentAdapter.java
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class FragmentAdapter extends FragmentPagerAdapter {

    private Context mContext;

    public FragmentAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new MondayFragment();
        } else if (position == 1) {
            return new ThursdayFragment();
        } else if (position == 2) {
            return new WednesdayFragment();
        } else if (position == 3) {
            return new ThursdayFragment();
        } else if (position == 4) {
            return new FridayFragment();
        } else if (position == 5) {
            return new SaturdayFragment();
        } else {
            return new SundayFragment();
        }
    }

    /**
     * Return the total number of pages.
     */
    @Override
    public int getCount() {
        return 7;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (position == 0) {
            return mContext.getString(R.string.monday);
        } else if (position == 1) {
            return mContext.getString(R.string.tuesday);
        } else if (position == 2) {
            return mContext.getString(R.string.wednesday);
        } else if (position == 3) {
            return mContext.getString(R.string.thursday);
        } else if (position == 4) {
            return mContext.getString(R.string.friday);
        } else if (position == 5) {
            return mContext.getString(R.string.saturday);
        }   else {
            return mContext.getString(R.string.sunday);
        }
    }

}

JSON Sample Response
{
   "schedule":{
      "day":[
         {
            "id":"Monday",
            "classes":[
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                },
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                }
            ]
         },
         {
            "id":"Tuesday",
            "classes":[
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                },
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                }
            ]
         },
         {
            "id":"Wednesday",
            "classes":[
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                },
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                }
            ]
         },
         {
            "id":"Thursday",
            "classes":[
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                },
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                }
            ]
         },
         {
            "id":"Friday",
            "classes":[
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                },
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                }
            ]
         },
         {
            "id":"Saturday",
            "classes":[
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                },
                {
                    "class" : "Class",
                    "time" : "00:00",
                    "trainer" : "Teacher",
                    "canceled" : ""
                }
            ]
         },
         {
            "id":"Sunday",
            "classes":[]
         }
      ]
   }
}

A: Looking at your POJO this isn't explicitly equal to your JSON.
A Day should be declared as:
class Day {
    String id;
    List<ClassDetail> classes;
}

class ClassDetail {
    //all the details
}

I think you are missconcepting your functions, the follow signature isn't too explicit.
List<Day> extractFeatureFromJson(String dayJSON)

In order to make it become more readable, I propose to change it for:
(You can use a Hashmap as recommended for @ρяσѕρєя):
HashMap<String, ClassDetail> parseScheduleJson(String scheduleJSON)

And the add each ClassDetail to the result
@Nullable
private static Map<String, List<ClassDetail>> parseScheduleJson(String scheduleJSON) {

    if (TextUtils.isEmpty(scheduleJSON)) {
        return null;
    }

    HashMap<String, List<ClassDetail>> result = new HashMap<>();

    try {
        JSONObject baseJsonResponse = new JSONObject(scheduleJSON);
        JSONArray dayArray = baseJsonResponse.getJSONObject("schedule").getJSONArray("day");

        for (int i = 0; i < dayArray.length(); i++) {
            ArrayList<ClassDetail> classes = new ArrayList<>();
            JSONObject currentDay = dayArray.getJSONObject(i);
            for (int j = 0; j < currentDay.getJSONArray("classes").length(); j++) {
                JSONObject currentClass = currentDay.getJSONArray("classes").getJSONObject(j);

                String retrieveCourseTitle = currentClass.getString("class");
                String retrieveCourseTime = currentClass.getString("time");
                String retrieveCourseTrainer = currentClass.getString("trainer");
                String retrieveCourseCancelState = currentClass.getString("canceled");

                classes.add(new ClassDetail(retrieveCourseTitle, retrieveCourseTime, retrieveCourseTrainer, retrieveCourseCancelState));
            }
            result.put(currentDay.getString("id"), classes);
        }

    } catch (JSONException e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("QueryUtils", "Problem parsing JSON results", e);
        return null;
    }

    return result;
}

After this, you can access to your list of classes of the day using:
mymap.get("Monday");
mymap.get("Tuesday");
...
mymap.get("Sunday");

Edit:
IMHO, you have to call your dayloader in your activity, and inject the map result to your FragmentPagerAdapter:
public FragmentAdapter(Context context, FragmentManager fm, Map<String, List<ClassDetail> schedule) {
    super(fm);
    mContext = context;
    mSchedule = schedule;
}

@Override
public Fragment getItem(int position) {
    if (position == 0) {
        return MondayFragment.newInstance(mSchedule.get("Monday"));
    //...
    //same for all conditions
    //...
    } else {
        return SundayFragment.newInstance(mSchedule.get("Sunday"));
    }
}

After that when using newIntance pattern you can declare your fragments as:
private List<ClassDetail> mClasses;

public static MondayClassDetailFragment newInstance(ArrayList<ClassDetail> classes){
    MondayClassDetailFragment myFragment = new MondayClassDetailFragment();

    Bundle args = new Bundle();
    args.putParcelableArrayList("classes", classes);
    myFragment.setArguments(args);

    return myFragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mClasses = getArguments().getParcelableArrayList("classes");
}

PS: Making http request and parsing a json manually at these days is a waste of energy. I recommend you to take a look to libraries to do this, in particulary to retrofit who is widely used and very well documented.

A: I'm not sure of this because I've never used FragmentPagerAdapter, but I suppose it works as any Adapter, conceptually.
What I am noticing in your code is that in your code (see comment)
private static List<Day> extractFeatureFromJson(String dayJSON) {

    if (TextUtils.isEmpty(dayJSON)) {
        return null;
    }

    List<Day> days = new ArrayList<>();

    //Try to parse
    try {

        JSONObject baseJsonResponse = new JSONObject(dayJSON);

        JSONArray dayArray = baseJsonResponse.getJSONObject("schedule").getJSONArray("day");

        JSONObject currentDay = dayArray.getJSONObject(0); //<<<<<<HERE
        JSONArray getClasses = currentDay.getJSONArray("classes");

            for (int j = 0; j < getClasses.length(); j++) {
                JSONObject currentClass = getClasses.getJSONObject(j);

                 String retrieveCourseTitle = currentClass.getString("class");
                 String retrieveCourseTime = currentClass.getString("time");
                 String retrieveCourseTrainer = currentClass.getString("trainer");
                 String retrieveCourseCancelState = currentClass.getString("canceled");

                 Day day = new Day(retrieveCourseTitle, retrieveCourseTime, retrieveCourseTrainer, retrieveCourseCancelState);
                 days.add(day);
            }

    } catch (JSONException e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("QueryUtils", "Problem parsing JSON results", e);
    }

    return days;
}

You are doing the "extraction" only for JSONObject currentDay = dayArray.getJSONObject(0);
This means your List<Day> days will have only one Day in it, that is current day. Supposing you're feeding this List to your adapter, only a Day is found, hence nothing is changing.
I suggest you iterate through ALL the days, appending each day to the List with something like this:
try{
    JSONObject baseJsonResponse = new JSONObject(dayJSON);
    JSONArray dayArray = baseJsonResponse.getJSONObject("schedule").getJSONArray("day");
    for (int i = 0; i<dayArray.length();i++){
        JSONObject currentDay = dayArray.getJSONObject(i);
        //the rest
    }
}catch(JSONException e){
    //etc
}

A: While @crgarridos 's answer would work, I kept thinking of a faster and easier way of achieving my goal with minimum code modifications so:
I ended up modifying my JSON API and creating query url's for the id key so that I could query like this:
 URL?id=monday.
Next up I simply needed to add a URI builder and appendQueryParameter(key, value); for each of my fragments.


text:
Q: How to set $SERVER variable value from C# while submitting post to php page I am trying to submit a post request to a php webpage from C#. php query looks like this:
    $result = mysql_query ("INSERT INTO SomeTable (ID, NAME, PERIOD, INFO, REQUESTED_BY,
DATE) " ." values (" . $id . ", '" . $_POST['Name'] . "', '" . $_POST['Period'] ."', '" .
$_POST['Info'] . "', '" . $_SERVER['HTTP_MYCOMPANY_EMAIL'] . "', '".date( 'Y-m-d
H:i:s')."')");

As you can see one of the variable is $_SERVER['HTTP_MYCOMPANY_EMAIL'] which i want to pass. I cannot impersonate the identity as this code will be executed from the workflow.
This is my C# code looks like:
        WebClient objWebClient = new WebClient();
        NameValueCollection objNameValueCollection = new NameValueCollection();
        objNameValueCollection.Add("Name", "test123");
        objNameValueCollection.Add("Period", "30 Days");
        objNameValueCollection.Add("Info", "someinfo");
        objNameValueCollection.Add("HTTP_MYCOMPANY_EMAIL", "fname_lname");

        objWebClient.UseDefaultCredentials = true;

        try
        {
            byte[] bytes = objWebClient.UploadValues("https://www.someweb.com/phpPage.php", "POST", objNameValueCollection);
            Console.Write(Encoding.ASCII.GetString(bytes));
            Console.WriteLine();
            Console.WriteLine("Press any key to exit");

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            throw;
        }

I am able to set the values of $POST variable but not the $SERVER variable. Is there a way to do so?

A: objWebClient.Headers.Add("Company-Name", value);

A: $_SERVER is a superglobal array which returns information about the operating environment. You cannot change its values dynamically. What exactly are you trying to accomplish?


text:
Q: Parsing Rails JSON Response in Android I'm having some trouble parsing some JSON returned by my rails server in a basic survey Android app.
Essentially I want to first POST a response. Then save the ID it gets in response.
I'm getting the ID returned, however it seems to be null when I log it out while the other "survey_id" and "appuser_id" paramaters do get set.
Because my Controller is set with the params like this:
        def response_params
          params.require(:response).permit(:survey_id, :completed, :appuser_id)
        end

It expects my JSON post to be in the format of '{"response": {"survey_id":"1", "appuser_id":"1"}}'
Thus why I create a ResponseDetail to house those details in each response.
Here's the JSON I'm receiving back from my Rails server after the successful POST:
{"id":162,"survey_id":1,"completed":false,"created_at":"2015-03-17T13:31:10.403Z","updated_at":"2015-03-17T13:31:10.403Z"}

How I'm Posting it:
public static Response postResponse(Response r) {
        Gson g = new Gson();
        String json = g.toJson(r);
        String responsesUrl = Uri.parse(RESPONSE_ENDPOINT).buildUpon().build().toString();
        Response resp = null;
        try {
            HttpResponse response = makeRequest(responsesUrl, json);
            String jsonResponse = EntityUtils.toString(response.getEntity());
            int status = response.getStatusLine().getStatusCode();
            if (status == 201) {
                JSONObject object = new JSONObject(jsonResponse);
                Log.d(TAG, "Object is: " + object.toString());

                resp = new Response(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resp;
        }

Here's how I parse it:
public class Response {
    private ResponseDetail response;

    public Response(ResponseDetail responseDetail) {
        response = responseDetail;
    }

    public Response(JSONObject json) throws JSONException {
        String surveyId = json.getInt("survey_id") + "";
        String appuserId = json.getInt("appuser_id") + "";
        String id = json.getInt("id") + "";

        ResponseDetail detail = new ResponseDetail(surveyId, appuserId, id);

        this.response = detail;
    }
    //getters/setters removed
}

class ResponseDetail {
    private String id;
    private String survey_id;
    private boolean completed;
    private String appuser_id;

    public ResponseDetail(String surveyId, String appuserId) {
        super();
        this.survey_id = surveyId;
        this.appuser_id = appuserId;
    }

    public ResponseDetail(String surveyId, String appuserId, String id) {
        super();
        this.id = id;
        this.survey_id = surveyId;
        this.appuser_id = appuserId;
    }
    //getters and setters removed
}

Finally the Async where I post it. Where it logs out the appuser_id and survey_id appropriately but shows the ID as null.
private class PostResponse extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... params) {

            try {
                ResponseDetail detail = new ResponseDetail("1", "344");
                Response response = new Response(detail);
                new SurveyConnection().postResponse(response);
                Log.d("SurveyConnection", "Appuser: " + response.getResponse().getAppuser_id());
                Log.d("SurveyConnection", "Survey: " + response.getResponse().getSurvey_id());
                Log.d("SurveyConnection", "ID: " + response.getResponse().getId());

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Toast.makeText(getActivity(), "It worked!", Toast.LENGTH_SHORT).show();
        }
    }

Log:
03-17 08:40:52.225    3217-3233/getrewards.example.com.getrewards D/SurveyConnection﹕ Appuser: 344
03-17 08:40:52.225    3217-3233/getrewards.example.com.getrewards D/SurveyConnection﹕ Survey: 1
03-17 08:40:52.225    3217-3233/getrewards.example.com.getrewards D/SurveyConnection﹕ ID: null

Any ideas what I need to do to get the ID to be set? I tried both json.getInt("id") and json.getString("id") but they both seem to return null despite the fact that I see ID in the returned JSON.

A: you´ve got ResponseDetail detail = new ResponseDetail("1", "344"); and id goes null in there...
you see? it´s hardcoded, nothing to do with your networking
you should get the return value of this line new SurveyConnection().postResponse(response);
(By the way it´s crazy to read your code, everything is called postResponse or Response, even the request is called response! ^g^


text:
Q: Inserting text into a text file Alright, this maybe the simplest (or the stupidest) question, but I just got to know...
Suppose I have a text file containing account no. and balance. I am writing a program to search the file using entered account no. and update the balance field in the same text file with a new balance.
I am finding it surprisingly difficult to do so using file streams. The problem is that I am trying to overwrite the balance string in the said text file with a new balance string.
So, if the balance is 1000 (4 digits), I can overwrite it with another 4 digit string. But, if the new balance string is more than 4 digits, it is overwriting the data after the balance field (it is a simple text file mind you...).
For example, if the text file contains
Acc. No.         balance
123456           100
123567           2500

The fields are separated by TAB '\t' character, and next record is separated by  a newline '\n'. If I enter new deposit of 200000 for account 123456, the fwrite() function overwrites the data in the text file as...
Acc. No          Balance
123456           2001003567         2500

You can notice that the '\n' after the balance field, and 2 digits from the next accounts' acc. no. is overwritten.
Of course, no-one wants that to happen :)
What I need is a way to insert text in that file, not just overwrite it. There are many results of doing this using Java, python or even SED, but nothing using FILE streams.
Please share your thoughts... thanks.

A: You'll have to move all data after the insertion point a few bytes up first. That's what Java, sed or python do as well, if they aren't writing a temporary file to begin with.

A: If you really want to manage your data in a plain text file:
While you are reading the file in, write a modified version of your data into a temporary file, then delete the original file and rename the temp file to the original filename. But be carefull that no other process accesses the same file concurrently.
Database systems were invented for such purposes. So I recommend to manage your data in a database table and dynamically create a text report when needed.


text:
Q: TestNG - How to force end the entire test suite from the BeforeSuite annotation if a condition is met Is there a way to quit the entire test suite if a condition is met in the @BeforeSuite annotation? Maybe a way to call the @AfterSuite and bypass the entire test?
I make a database call in the @BeforeSuite. If the query returns any results, I send an email and now am wanting to kill the entire test suite.
I have tried System.exit(1); and org.testng.Assert.fail("There are unpaid invoices");, but neither of those terminate the entire suite. My scripts are setup to run classes in parallel and when I run the test from the test.xml file, each class tries to start and opens a window and then immediately closes it.
FYI, the drivers do not get created until the @BeforeClass or @BeforeMethod (depending on the switch I created for parallel methods or classes). So in all reality, there should never even be an attempt to open a browser window.

A: try new SkipException("message"); this will skip the tests if the provided condition is not true.

A: Try the below code in beforesuite annotation method , check if the run mode of your suite is Y/N. if that's N Then throw an Exception

throw new skipException("desired Message")

Please keep it in mind don't catch the skip exception in try and catch block. otherwise it will  go for the execution of testcases in that suite after throwing skip Exception
package com.qtpselenium.suiteA;

import org.testng.SkipException;
import org.testng.annotations.BeforeSuite;

import com.qtpselenium.base.TestBase;
import com.qtpselenium.util.TestUtil;

public class TestSuiteBase extends TestBase{

    @BeforeSuite
    public void checksuiteskip(){

            //Initialize method of Test BASE Class to Initialize the logs and all the excel files
            try {
                Initialize();
            } catch (Exception e) {
                e.printStackTrace();
            }
             App_Logs.debug("checking run mode of SuiteA");
            if( !TestUtil.isSuiterunnable(suitexlsx, "suiteA")){

               App_Logs.debug("Run mode for SuiteA is N");
               throw new SkipException("Run mode for suiiteA is N");

           }else

               App_Logs.debug("Run mode for SuiteA is Y");

        }

    }


text:
Q: Access form does not display records on click event I have a form (Vendor_Update) that works perfectly. The form is simple - an unbound combo box (cbo_Vendor) is used to filter 4 textboxs for editing. The form is bound to tbl_Vendors. A macro is used on the OnChange event for cbo_Vendor to search for the selected record in tbl_Vendors. I can edit the textboxes and they save to the table, as intended.
I want to open the Vendor_Update form by clicking a button on another form (Form_Start) in my database. I added Cmd_Vendor_Data to the start form with this code in VBA:
Private Sub Cmd_Vendor_Data_Click()
  DoCmd.OpenForm "Vendor_Update", acNormal, "", "", acFormAdd
End Sub

The form opens, and I can select a vendor from the combo box, but the text boxes do not populate with the information from tbl_Vendors.
Why does the Vendor_Update form work when I open it exclusively, but not when it is opened by a click event?
One additional note for the Vendor_Update form - this code is in the On Load event:
Private Sub Form_Load()
  If Not Me.NewRecord Then RunCommand acCmdRecordsGoToNew
  Me.Cbo_Vendor.Requery
End Sub

I am not well-versed in VBA, so any help is much appreciated!

A: Thank you @HansUp for the assistance!  Code corrected and form works as intended.
Private Sub Cmd_Vendor_Data_Click()
  DoCmd.OpenForm "Vendor_Update", acNormal, "", "", acFormEdit
End Sub


text:
Q: How to write something in between two ".col-md-*"? I am trying to write an "or" in between 2 ".col-md-1".
For example:
Green or Blue
This is my code:

      <button class="btn">Green</button>

      <button class="btn">Blue</button>

What should I write inside the code or should I try another technique?

A: You could add another col-md-1 between the 2 elements (or whatever column size suits your needs):

      <button class="btn">Green</button>

or

      <button class="btn">Blue</button>

A: Depends on how the result should look like. You can do something like this for example:

  <button class="btn"> Green </button> or <button class="btn"> Blue </button>

A: give them an ID & do the if else in Javaascript

      <button class="btn">Green</button>

      <button class="btn">Blue</button>

in js

A: Give them and ID.

  <button class="btn">Green</button>

  <button class="btn">Blue</button>

and then you can select the first one and append an element after it
$("$green").after('
OR
')


text:
Q: Parse error: syntax error, unexpected '(' in D:\xampp3\xampp\htdocs\contact.php on line 10 I have a problem with my code here.
I'm making a simple "Contact us" via html / PHP.
But i'm new to all this, and learning it from step to step. So thats why i've come here.
I get this error: Parse error: syntax error, unexpected '(' in D:\xampp3\xampp\htdocs\contact.php on line 10 and here is the code:
<?php
include 'core/init.php';
include 'includes/overall/header.php';
if (empty($_POST) === false) {

    $name     = $_POST ['name'];
    $email    = $_POST ['email'];
    $message  = $_POST ['message'];

    if (empty($name) === true || (empty( ($email) === true || (empty($message === true)  {
       $errors[] = 'Name, email and message are required!';
    } else {

}
?>

A: Try this:
<?php
include 'core/init.php';
include 'includes/overall/header.php';
if (empty($_POST) === false) {

    $name     = $_POST ['name'];
    $email    = $_POST ['email'];
    $message  = $_POST ['message'];

    if (empty($name) === true || empty($email) === true || empty($message) === true)  {
       $errors[] = 'Name, email and message are required!';
    } else {
    }
    // The else above is actually not needed thus you could remove it.

}
?>


text:
Q: K2 workflow -Unable to view SmartObjects in K2 designer, I have created new categories for K2 Learning projects as shown below

However When I create a new Workflow Item, give in the form, smart objects and folio details, and then navigate to Smart Objects tab in the designer, I do not see my project listed here. Only some of the existing projects seem to be listed. Could you help?

I am doing a test project as suggested in K2 website
LeaveRequestApp

A: Edit your Smartobject, there's an option to check to allow it to be used in workflow.
This option allow you to view the Smartobject from the web-based workflow designer.

A: After creating the smartobject in the k2 studio ( or if you are using visual studio) you should deploy the project from k2 studio.
If your creating the smartobject using k2 tester utility then you have to select the destination folder where you have to store the smartobject

A: Once you create a Smart Object, view and form, make sure you deploy the solution before creating the workflow. Project will be visible for selection after deploying.


text:
Q: MacBook Pro 13' Power cord I use a 6 outlet adapter on my wall outlet. Since it's on the wall, it gets loose sometimes. This morning I pushed it in, while my power cord was plugged into it and the the power cord was plugged into my computer. There was a 'short' where I blew a fuse, and it sparked. I immediately unplugged my computer. My computer is working fine, but I'm afraid to use the power cord now. Is it still good? Can I hurt my computer?

A: If the computer's working fine, then the electrical event that occurred either didn't damage the computer, or only damaged the charging circuitry.
I wouldn't try using the adapter again. If you do, there's a high likelihood that it will trip another circuit breaker/blow a fuse, or it may not do anything at all. I think it's very unlikely in either case that it will charge your computer again.
If the adapter is an Apple adapter, take it back to an Apple Store, they'll most likely replace it on the spot. If it's an aftermarket adapter, get an Apple adapter, I've never had an Apple one malfunction.
I'm not a licensed electrician, but I do know my way around electricity/electrics. I strongly recommend you discard the charger if it's an aftermarket adapter, or have it replaced if it's an Apple one.


text:
Q: Dynamic navigation shows incorrect result count When we filter result by Duplicate Snippet filter (filter=p) we receive incorrect result count in dynamic navigation.
E.g.
Picture with issue
Actual result count = 5
Result are shown for end-user = 3 (Two pages was filtered)
Dynamic navigation by content format(Web Pages) = 5
As I know GSA has some problems with determinating actual count for a large number of results.
Is it possible to set filtered result count in dynamic navigation (Web Pages)?
GSA System Version: 7.2.0.G.252


text:
Q: Adding RAM to Tomcat Which environment variable should I use to add more RAM to Tomcat?
JAVA_OPTS="-Xmx1024m -Xms256m"
or
CATALINA_OPTS="-Xmx1024m -Xms256m"?

A: Either will work.  However, from skill-guru...

Note that CATALINA_OPTS is a better place than JAVA_OPTS. The former
  is only used when actually starting the Tomcat instance. JAVA_OPTS is
  also used to start JVMs that only interact with Tomcat (for example
  the JVM instance that is used to send the shutdown-message to a
  running Tomcat instance).

A: CATALINA_OPTS is used to control Tomcat environment options, whereas JAVA_OPTS controls the environment options at a higher level ie. for any Java library.
Windows: set CATALINA_OPTS=-Xms(min heap)m -Xmx(max heap)m
Linux: export CATALINA_OPTS="-Xms(min heap)m -Xmx(max heap)m"

A: When you'll use CATALINA_OPTS then it's clear that this option is related to Tomcat server. Also when you'll use JAVA_OPTS then any other application could use this settings, and that isn't something that you probably intentionally want to achieve.

A: JAVA_OPTS. You are providing options to the java command, not the catalina one (which is a shell script).


text:
Q: How to install postman in windows server 2007 SP2 (windows vista) I need to install postman on an old windows 2007 SP2.
I am not even sure if it is actually 2007, but here is the screenshot of system properties

Why I need postman?
Because there is another web service that is only accessible through this old windows, and the support team of the mentioned service do not want to cooperate through other means such as pure http requests/responses, and they want me to use postman.
I am really stuck at this for a long time.
I tried to search for a port-forwarding software but couldn't find one :(
Edit: after a simple search, I found that the version is 6.0.6002 (Windows Vista)

A: Postman did not work for me too on a Windows Server 2007 SP2. As an option you can install SoapUI 5.5.0 on your server. SoapUI supports SOAP and REST services.


text:
Q: Debugging Test functions in Golang i am new in go and want to debug some test functions.
Ubuntu:
21.10
Go:
1.18.3 linux/amd64
VsCode:
1.69.0
Go Plugin:
0.34.1
Delve Debugger:
1.9.0
Tools environment: GOPATH=/home/fred/go
Installing 7 tools at /home/fred/go/bin in module mode.
gotests
gomodifytags
impl
goplay
dlv
staticcheck
gopls
All tools successfully installed. You are ready to Go. :)
I would like to debug test functions.

*

*I have installed go with the following instruction: https://go.dev/doc/install.

*I have installed the golang plugin for vscode.

*then via ctrl+shift+p Go:updates/tools installed the tools.
I tried the same thing on a WIndows PC. There everything works fine. above the test functions there are two buttons displayed "test run" and "test debug". These work! buttons
-> Now to my problem. These buttons are not displayed in vscode on Ubuntu. And if I use the plugin function "Go: Debug test at curor" it always shows me "no function at cursor".
Does anyone know why the buttons are not displayed?
How can I still debug the test function without these buttons?
I have googled but I can't get it to work.


text:
Q: Access global variable in runtime-linked dll I need to access some legacy dll's global variable at run time. I do have the header file for the global variable definition
struct CmpSys
   {
    public:
       static const int NAME_LEN = 21;
       char szNam[NAME_LEN]  ;         // user defined system name
   }

The global variable is packed in a c++.dll as
CmpSys** gapCmpSys

In my cpp file I use
hDEWModelDll = LoadLibrary(L"DEWModel.dll");

(CmpSys**) ptrCmpSys = (CmpSys**)GetProcAddress(hDEWModelDll, "gapCmpSys");

The debugger shows that the ptrCmpSys has a valid address (not null), but the content is all wrong.
if I write
ptrCmpSys[0]->szNam

I will get strange charater string.
what should I do?


text:
Q: how to insert a value and fetch data from disabled text and several checkbox and store in database in laravel? I am facing an error.
so the thing is that. I have column name role_permission, where I have to store the roles to each role, here is the UI of form -
As you can see here, I have selected options where users can select roles like -admin, users, editor, and three disabled textboxes which are items whose permission will be set in the database, and the checkbox where users can select the permissions.
Now the main thing is, when the user submit on the button, the data should be saved like this
  id    roll_id   item    permission
  1        1      post     add
  2        1      post     view
  3        1      comment   add

As, if the user selects the permission to add, edit, view to post(item), the individual data should be like I showed above, not like an array or something .. each permission should be saved individually pointing to its item.
here is the migration file of this :
public function up() {
    Schema::create('role_permission', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('role_id');
        $table->string('Item');
        $table->string('Permission');
        $table->foreign('role_id')->references('id')->on('roles');
        $table->timestamps();
    });
}

Here is the form of it  :
<form method="post" action="{{ route('Admin.AssignPermission.save')}}" enctype="multipart/form-data">
    @csrf
    @if ($errors->any())

              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

                  @foreach ($errors->all() as $error)

{{ $error }}

                  @endforeach

        @endif

             Assign Roles
            <select style="margin-left: 10px;" class="form-select" aria-label="Default Select Role" name="Roles">
                    <option selected disabled>Roles</option>
                    @foreach ($roles as $role)
                        <option value="{{$role->id}}">{{$role->name}}</option>
                    @endforeach
                </select>

                #
                Add
                View
                Edit
                Delete

                        <input class="form-control" type="text" name="Items[]"  value="Post" readonly>
                        <input type="hidden" name="selected[]" value="post">

                            <input class="form-check-input" type="checkbox" value="Add" name="Permissions[]">

                            <input class="form-check-input" type="checkbox" value="View" name="Permissions[]">

                            <input class="form-check-input" type="checkbox" value="Edit" name="Permissions[]">

                            <input class="form-check-input" type="checkbox" value="Delete" name="Permissions[]">

                    <input class="form-control" type="text" name="Items[]"  value="Comments" readonly>

                        <input class="form-check-input" type="checkbox" value="Add" name="Permissions[]">

                        <input class="form-check-input" type="checkbox" value="View" name="Permissions[]">

                    <input class="form-check-input" type="checkbox" value="Edit" name="Permissions[]">

                    <input class="form-check-input" type="checkbox" value="Delete" name="Permissions[]">

                    <input class="form-control" type="text" name="Items[]"  value="User" readonly>

                        <input class="form-check-input" type="checkbox" value="Add" name="Permissions[]">

                        <input class="form-check-input" type="checkbox" value="View" name="Permissions[]">

                        <input class="form-check-input" type="checkbox" value="Edit" name="Permissions[]">

                        <input class="form-check-input" type="checkbox" value="Delete" name="Permissions[]">

              <input type="submit" class="btn btn-primary" value="Submit">

    </form>

and here is the store method of it :
public function store(Request $request) {

    $data = $request->all();
    $rules = array(
       'Roles' => 'required' ,
       'Items.*' =>'required',
    );

    $validate=Validator::make($data,$rules);

    if ($validate->fails()) {
        return redirect()->back()->withInput()->withErrors($validate);
    } else {
       foreach($request->Items as $key=>$Items){
           foreach ($request->Permissions as $key => $Permissions) {
                $form_data = array(
                    'role_id'    => $data['Roles'],
                    'Item'       => $data['Items'],
                    'Permission' => $data['Permissions'],
                );
           }
       }
       $RolePermission = RolePermission::create($form_data);
       $Message = "successfully added";
       return redirect('/Admin/users')->with('success',$Message);
    }
}

, using this method but getting error ??? or how to do this any other method will be helpful
???
Here is the error of that.
here is my structure of the table:

A: You are making things more complicated than it needs to be. First change you view to be similar to this.
// name field having [post] for post
<input class="form-check-input" type="checkbox" value="Delete" name="Permissions[post]">
// name field having [comment] for comment
<input class="form-check-input" type="checkbox" value="Delete" name="Permissions[comment]">

The above code when submitted through form will result in something like this
dd($request->all());
// below is output of this
[
   "Permissions" => [
      "post" => ["Add", "Delete"],
      "comment" => ["Delete"]
   ]
]

Then in controller you will just sort through those and perform operation as you want
  // Looping though permissions
  foreach ($request->Permissions as $itemName => $permissions) {
      // $permissions will be an array ["Add", "Delete"]
      // $itemName will "post"
      // We loop again in permissions to output single data permission
      foreach($permissions as $permission) {
          $form_data = [
             'role_id'    => $data['Roles'],
             'Item'       => $itemName, // post
             'Permission' => $permission, // Add
          ];

          // Perform action here as you suit. Create/Delete based on requirement
          if(!RolePermission::where($form_data)->exists()){
              RolePermission::create($form_data);
          }
      }
 }


text:
Q: How to specify a editor to open crontab file? "export EDITOR=vi" does not work I'm using Red Hat Enterprise Linux 5, and I want to set the vim editor to edit the crontab file.
If I run echo $EDITOR, I get vim. But when I run  crontab -e, I get different editor.

A: To quote the man:

The -e option is used to edit the current crontab using the editor specified by the VISUAL or  EDITOR  environment  variables

Most often if you run crontab -e from X, you have VISUAL set; that's what is used. Try this:
VISUAL=vi crontab -e
It just worked for me :)

A: You can use below command to open it in VIM editor.
export VISUAL=vim; crontab -e

Note: Please make sure VIM editor is installed on your server.

A: I think you might need to use the full path:
export EDITOR=/usr/bin/vim

A: If the above methods don't work (as they didn't work on my Ubuntu 13.04 installation) try:
There are a number of alternative ways:
1) Run select-editor
select-editor

2) Manually edit the file: ~/.selected_editor specifying your preferred editor.  With this option you can specify editor parameters.
# Generated by /usr/bin/select-editor
SELECTED_EDITOR="/usr/bin/emacs -nw"

3) You can specify on the fly on the commandline with:
env VISUAL="emacs -nw" crontab -e

A: export EDITOR=vim worked for me

A: It wasn't working for me. I run crontab with sudo, so I switched to root, did the above suggestions, and crontab would open in vim, but it still wouldn't from my user account. Finally I ran sudo select-editor from the user account and that did the trick.

A: This worked for me :
EDITOR="/usr/bin/vim"
export EDITOR

Add this to ~/.bash_profile or ~/.bashrc to enable this for current user.

A: Very probable that your VISUAL environment variable is set to something else. Try:
export VISUAL=vi


text:
Q: Using Webcam with VLCJ not working correctly while using the same options in VLC do work: I am somewhat lost here:
I try to integrate my Webcam in a Java App using VLCJ. When i open VLC and use the settings shown in the screenshot below everything works well.

But when I then try to use the exact same settings from within my VLCJ App i get the wrong image like VLCJ is using the wrong Webcam device (System default which is a virtual cam and thus not the correct one!).
This is my testcode:
public class Camera_Demo {

      private final EmbeddedMediaPlayerComponent mediaPlayerComponent;

      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            new Camera_Demo();
          }
        });
       }

      private Camera_Demo() {

         NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:/Program Files (x86)/VideoLAN/VLC");
         Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);

         JFrame frame = new JFrame("vlcj Tutorial");
         mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
         frame.setContentPane(mediaPlayerComponent);
         frame.setLocation(100, 100);
         frame.setSize(1280, 720);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);

         String [] options =  {" :dshow-vdev=HP HD Webcam [Fixed]"
                             + " :dshow-adev=none"
                             + " :dshow-size=1280x720"
                             + " :dshow-aspect-ratio=16\\:9"
                             + " :live-caching=200"};
         mediaPlayerComponent.getMediaPlayer().startMedia("dshow://", options);
      }
    }

Using the quoted code i get a JFrame showing a blue Cyberlink "please start your webcam" logo. This happens in VLC, too, when i use the Virtual Webcam device ("CyberLink Webcam Sharing Manager"). That is why I use "dshow-vdev=HP HD Webcam [Fixed]".
That is the excat name of the physical device (see screenshot above).
So i have NO idea at all why this is working in VLC but not in VLCJ....
Any ideas?

A: The options need to be split, not concatenated.
You need to convert this:
String [] options =  {" :dshow-vdev=HP HD Webcam [Fixed]"
                         + " :dshow-adev=none"
                         + " :dshow-size=1280x720"
                         + " :dshow-aspect-ratio=16\\:9"
                         + " :live-caching=200"};

Into an actual array of strings like this:
String[] options =  {":dshow-vdev=HP HD Webcam [Fixed]",
                     ":dshow-adev=none",
                     ":dshow-size=1280x720",
                     ":dshow-aspect-ratio=16\\:9",
                     ":live-caching=200"};

The examples in the vlcj test sources do similar things.


text:
Q: Dynamic module loading using __import__ I want to make a function that loads all the .py files in a directory, and imports them using
__import__(), but I keep getting an ImportError: No module named toolboxtool1.
This is file structure:
project/dirreader.py
project/tools/toolboxtool1.py
project/tools/toolboxtool2.py
project/tools/toolboxtool3.py

What am I doing wrong?
import os
os.chdir(os.getcwd()+"/tools/")
stuff = os.listdir(os.getcwd())
for i in range(0,len(stuff)):
    if stuff[i][-3:] == ".py":
        stuff[i] = stuff[i][:-3]
    else:
        pass
modules = map(__import__, stuff)

A: Try prefixing the module names with "tools."
stuff[i] = 'tools.' + stuff[i][:-3]

because the modules you are trying to import are inside tools module package.


text:
Q: ERROR CONSULTA SQL EN DATAGRIDVIEW C# estoy utilizando la siguiente query para llenar un datagridview con el resultado, pero el resultado que obtengo al ejecutar la consulta es que el datagridView se me llena con todos los datos y no filtra por fechas, alguien sabe donde está el error?
 void buscarDatosDiarios()
    {

        string query = "SELECT * FROM diarios WHERE FechaHora BETWEEN '" + dateTimePickerDesde.Text + "' AND '" + dateTimePickerHasta.Text + "' ";
        SqlConnection cn = new SqlConnection(conexion);
        SqlDataAdapter da = new SqlDataAdapter( query, cn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        dataGridDiarios.DataSource = ds.Tables[0];
    }

También he probado lo siguiente con el mismo resultado.Gracias.
        string query = "SELECT * FROM diarios WHERE FechaHora >= '" + dateTimePicker1.Text + "' AND FechaHora <'" + dateTimePicker2.Text + "' ";

A: A SQL Server, si le pasas una fecha como string, se la debes pasar en formato ISO, por ejemplo "Año-Mes-Dia".
string fechaDesde = dateTimePickerDesde.Value.ToString("yyyy-MM-dd");
string fechaHasta = dateTimePickerHasta.Value.ToString("yyyy-MM-dd");
string query = "SELECT * FROM diarios WHERE FechaHora BETWEEN '" + fechaDesde  + "' AND '" + fechaHasta  + "' ";

A: No le pases al sql server las fechas en formato string. Para esto utiliza parámetros, para que el framework y el motor hablen entre ellos, y así no tendrás problemas con la configuración regional o el idioma asociado a la conexión, etc...., además de realizarlo de un modo quizá, más adecuado.
   string query = "SELECT * FROM diarios WHERE FechaHora BETWEEN @paramFechaDesde AND @paramFechaHasta";
        DataTable dt = new DataTable();
        using (SqlConnection cn = new SqlConnection(conexion))
        {
            //Inicializa el comando que se va a ejecutar
            using (SqlCommand cmd = new SqlCommand(query,cn))
            {
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    cmd.Connection.Open();
                    cmd.Parameters.AddWithValue("@paramFechaDesde",   dateTimePickerDesde.Value);
                    cmd.Parameters.AddWithValue("@paramFechaHasta", dateTimePickerHasta.Value);
                    da.Fill(dt);
                    dataGridDiarios.DataSource = dt;
                }
            }
        }

Observa que si introduces los diferentes objetos dentro de sentencias Using, ya no te tienes que preocupar de ejecutar los métodos close y dispose, de los mismos, y liberar los recursos que ya no son necesarios.
Espero te ayude


text:
Q: CGAffineTransformMakeScale and Rotation at once? I want to apply scale and rotation at once.Problem is when i do this rotation is correct but scale  reduce. I test scale and rotate separately and it working perfectly. Following is my code
CGAffineTransform transformScale = CGAffineTransformMakeScale( tmp.size, tmp.size);
CGAffineTransform transformRotate = CGAffineTransformMakeRotation((CGFloat)tmp.rotation);
[iview setTransform:CGAffineTransformConcat(transformScale, transformRotate)];


text:
Q: AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'manager1' I am getting an error :

Attribute error: 'kivy.properties.ObjectProperty' object has no attribute 'manager1' when I am trying to switch to another screen using their respective id's.

This is my code:
Python file:

*

*Inside the First_Screen() class

My2App.first.manager1.current = "start"   #"start" is the name of First_Screen()

*

*This is my My2App class

class My2App(MDApp):
    manager1 = ObjectProperty(None)
    first = ObjectProperty(None)
    second = ObjectProperty(None)

    def build(self):
        self.bd = Builder.load_file("My.kv")
        return self.bd

kv file:
ScreenManager:
    manager1:manager1
    id:manager1

    First_Screen:
        first:first
        id:first
    Show_Title:
        second:second
        id:second

<First_Screen>:
    name:'start'

    # rest of the content.....

I don't understand what is missing.
Thanks for helping me in advance.

A: If I copy/paste your code, it doesn't work. I had to changes multiples before even having a working code or having the error that you are talking about.
So here is a working code.
from kivy.lang import Builder
from kivymd.app import MDApp

class My2App(MDApp):
    def build(self):
        self.bd = Builder.load_file("My.kv")
        return self.bd

My2App().run()

<First_Screen>:

ScreenManager:
    id:manager1

    Screen:
        id:first
        name:'start'

    Screen:
        id:second
        second:second

    # rest of the content.....


text:
Q: How to call a stored procedure with multiple parameters? How would I go about calling a stored procedure in PHP with several parameters?
let's say I have a stored procedures like this in mysql:
delimiter //
create procedure createInvoice (inProduct varchar(20), inCost float, inAmount integer)
begin
.....
.....
.....
end//
delimiter ;

Now in PHP I want to call this procedure and set the inProduct, inCost and inAmount variables to values that comes from a form. How would I go about doing this? I've tried setting it up like this but it's not working out.
.....
.....
.....
<?php
if(isset($_POST['invoiceform']) {
 $sp = 'call createInvoice("' . $_POST['product'] . ',' . $_POST['cost'] . ',' . $_POST['amount'] . '")';
.....
.....
.....
}
?>

So I just wanna know how to formulate the "call"-code in PHP. The rest I know (forms, what to write after the call etc).
UPDATE:
So I have it like this now:
if(isset($_POST['invoiceform']) {
 $sp = 'call createInvoice(?,?,?);

$spParameter([$_POST['product], $_POST['cost'], $_POST['amount'];

$stmt = $pdo->prepare($call);
$stmt->bindParam('inProduct', $_POST['product']);
$stmt->bindParam('inCost', $_POST['cost']);
$stmt->bindParam('inAmount', $_POST['amounnt']);
$stmt->execute();

I get this error:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in x/x/x/x/x/invoice.php on line x PDOStatement Object ( [queryString] => CALL createInvoice(?,?,?) )
UPDATE 2: SOLVED IT:
if(isset($_POST['invoiceform']) {
 $sp = 'call createInvoice(?,?,?);

$spParameter([$_POST['product], $_POST['cost'], $_POST['amount'];

$stmt = $pdo->prepare($call);
$stmt->bindParam('inProduct', $_POST['product']);
$stmt->bindParam('inCost', $_POST['cost']);
$stmt->bindParam('inAmount', $_POST['amounnt']);
$stmt->execute($spParameters);

A: By what you are currently doing you get a concatenated string like this:
call createInvoice("product, cost, amount")

Which means you are only passing one parameter, namely the first one.
But what you actually want is this to pass all three individually:
call createInvoice("product", "cost", "amount")

So you have to add in the quotes accordingly when doing the string concatenation, like so:
$sp = "call createInvoice(?, ?, ?)";
$spParameter = [$_POST["product"], $_POST["cost"], $_POST["amount"]];

Prepare $sp then execute with parameters in $spParameter.
Side note: you are wide open to SQLinjection.


text:
Q: division by zero in calculating TF-IDF algorithm for keyword-extraction I wrote a code based on the TF-IDF algorithm to extract keywords from a very large text.
The problem is that I keep getting the division by zero error. When I debug my code, everything is working perfectly. As soon as I make the text shorter to contains the word that causes the problem, it works. So, I assume that it's a memory problem.
I thought maybe I could read the big text file in chunks (1KB) instead of reading the whole document in the first place. Unfortunately, it does not work. what should I do?
(I am using pycharm on windows)
I am a beginner in programming, python, and NLP domain. Therefore, I really appreciate it if you could help me here.
if __name__ == "__main__":
 with open('spli.txt') as f:
    for piece in read_in_chunks(f):
        #print(piece)
        piece = piece.lower()
        no_punc_words, all_words = text_split(piece)
        no_punc_words, all_words = rm_stop_word(no_punc_words, all_words)
        no_punc_words_freq, all_words_freq = calc_freq(no_punc_words, all_words)
        tf_score = calc_tf_score(no_punc_words_freq)
        idf_score = calc_idf_score(no_punc_words_freq, all_words_freq, piece)
        tf_idf_score = {}
        for k in tf_score:
           tf_idf_score[k] = tf_score[k] * idf_score[k]
           #print(final_score)
    final_tf_idf = {}
    for scores in tf_idf_score:
        final_tf_idf += tf_idf_score
        print(final_tf_idf)


text:
Q: Giving explicit map for Strong Deformation Retraction One of the exercise says that $\mathbb{S^1}×1 \cup 1×\mathbb{S^1}$ is strong deformation retraction of $\mathbb{S^1} × \mathbb{S^1} - (-1,-1) $. My intuitive understanding was $\mathbb{S^1} × \mathbb{S^1} - (-1,-1) $ is similar to $\mathbb{R^2}$ and $\mathbb{S^1}×1 \cup 1×\mathbb{S^1}$ is same as like union of lines x=1 and y=1. so pictorially I have got the intuition behind this. But I can't come up with explicit map. Any help. Here 1 is (1,0) and -1 is (-1,0).

A: Geometrically, $S^1\times\{1\}\cup\{1\}\times S^1\cong S^1\vee S^1$, and $S^1\times S^1\setminus\{(-1,-1)\}$ is the punctured torus ($=T^2\setminus \{p\}\cong([-1,1]^2/\sim)\setminus\{p\}$).
I think this is what you want:
Let $p=(-1,-1)$, $I=[-1,1]$ and $(s_1,s_2)\in (I^2/\sim)\setminus\{p\}$  then we construct the deformation retraction $H:(I^2/\sim)\setminus\{p\}\times[0,1]\to (s_1\times\{1\}\cup \{1\}\times s_2)/\sim$ by:
$$
H(s_1,s_2,t)=
\begin{cases}
(t(\frac{2(s_1+1)}{|s_2+1|}-1-s_1)+s_1, (1-s_2)t+s_2)& \text{if }s_2\ge s_1\\
((1-s_1)t+s_1, t(\frac{2(s_2+1)}{|s_1+1|}-1-s_2)+s_2)& \text{if }s_2\le s_1
\end{cases}
$$
The map is well-defined and continuous at both branches.
A way to visualize this map is to think about the square under the quotient $\sim$, because in this case, $\frac{s_1\times\{1\}\cup \{1\}\times s_2}{\sim}\cong S^1\times\{1\}\cup\{1\}\times S^1$. $H$ expands the hole created by $\{p\}$ (in the left corner) and maps every point in $T^2\setminus\{p\}$ to the two edges that have one point in common by sliding each point linearly through the line between $(-1,-1)$ and the two edges which is obviously equal to the space indicated in the first sentence. ("the two edges" means $\frac{s_1\times\{1\}\cup \{1\}\times s_2}{\sim}$)
The space $\frac{s_1\times\{1\}\cup \{1\}\times s_2}{\sim}$ is the same as $S^1\times\{1\}\cup\{1\}\times S^1$ because $\sim$ generates the equivalence relation which states that $(s_1,1)\sim(s_1,-1),(1,s_2)\sim(-1,s_2)\implies (-1,1)\sim (1,1)\sim (1,-1)$ which implies that the two edges are actually two circles. After identification, we see that only $(1,1)$ belongs to both circles simultaneously so this is also equivalent to the wedge sum of two circles, namely $S^1\vee S^1$. (hope this makes it clearer...)

If there is anything ambiguous, please tell me and I'll try to help you. :)

A: $S^1 \times S^1$ is homeomorphic to $\left[-1, 1\right]^2 / \sim$ where $\left(x,-1\right) \sim \left(x, 1\right), \left(-1,y\right) \sim \left(1, y\right)$. There is a deformation retract of $\left[-1,1\right]^2-\left(0,0\right)$ onto $\partial\left[-1,1\right]$ that fixes the boundary, and in particular well defined also after quotiening by $\sim$. This will give you the desired deformation retract.


text:
Q: Is the PHP Manual misguiding regarding the output of 'phpinfo()' function? I'm using Windows 10 Home Single Language Edition which is a 64-bit Operating System on my machine.
I've installed the most latest version of XAMPP which has installed PHP 7.2.6 on my machine.
I come across the following sentence from the paragraph in PHP Manual

Make a call to the phpinfo() function and you will see a lot of useful
  information about your system and setup such as available predefined
  variables, loaded PHP modules, and configuration settings.

I tried executing the below script and saw the output in my web browser :
<?php phpinfo(); ?>

I checked the entire output carefully. In the output of phpinfo() I could only see the $_SERVER predefined variable along with it's possible indexes specific to set-up on my machine.
But what about other predefined variables in PHP viz. $GLOBALS, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV, $http_response_header, $argc, $argv?
According to what the text from PHP Manual is saying all the above mentioned predefined variables along with their respective values should be displayed in the output of the script <?php phpinfo(); ?> but it's not happening. Why so?
Is the text from PHP manual misguiding the users of PHP?
Or am I getting the wrong understanding of the text from PHP Manual?
Please explain me in detail.

A: As you can see in the PHP source code for phpinfo(), it will display the variables in question:
    if (flag & PHP_INFO_VARIABLES) {
        zval *data;

        SECTION("PHP Variables");

        php_info_print_table_start();
        php_info_print_table_header(2, "Variable", "Value");
        if ((data = zend_hash_str_find(&EG(symbol_table), "PHP_SELF", sizeof("PHP_SELF")-1)) != NULL && Z_TYPE_P(data) == IS_STRING) {
            php_info_print_table_row(2, "PHP_SELF", Z_STRVAL_P(data));
        }
        if ((data = zend_hash_str_find(&EG(symbol_table), "PHP_AUTH_TYPE", sizeof("PHP_AUTH_TYPE")-1)) != NULL && Z_TYPE_P(data) == IS_STRING) {
            php_info_print_table_row(2, "PHP_AUTH_TYPE", Z_STRVAL_P(data));
        }
        if ((data = zend_hash_str_find(&EG(symbol_table), "PHP_AUTH_USER", sizeof("PHP_AUTH_USER")-1)) != NULL && Z_TYPE_P(data) == IS_STRING) {
            php_info_print_table_row(2, "PHP_AUTH_USER", Z_STRVAL_P(data));
        }
        if ((data = zend_hash_str_find(&EG(symbol_table), "PHP_AUTH_PW", sizeof("PHP_AUTH_PW")-1)) != NULL && Z_TYPE_P(data) == IS_STRING) {
            php_info_print_table_row(2, "PHP_AUTH_PW", Z_STRVAL_P(data));
        }
        php_print_gpcse_array(ZEND_STRL("_REQUEST"));
        php_print_gpcse_array(ZEND_STRL("_GET"));
        php_print_gpcse_array(ZEND_STRL("_POST"));
        php_print_gpcse_array(ZEND_STRL("_FILES"));
        php_print_gpcse_array(ZEND_STRL("_COOKIE"));
        php_print_gpcse_array(ZEND_STRL("_SERVER"));
        php_print_gpcse_array(ZEND_STRL("_ENV"));
        php_info_print_table_end();
}

However, as you can see, it uses php_print_gpcse_array to print each key/value pair in it when a) the superglobal exists (SAPI dependent) and b) it actually contains values.
TL;DR: no, the PHP manual is not misleading in that regard.


text:
Q: How can I avoid misidentification of a exponential distribution as Gamma or Weibull? I'm trying to write a piece of code in R that identifies a set of sample data as belonging to a specific distribution and pull the specific distribution parameters, by performing the K-S test and comparing the resulting p-values.
However, I've run into a bit of a logical problem. I can successfully generate gamma, weibull, logistic, normal and poisson distributions and correctly identify them, but as soon as I try to identify an exponential distribution, the resulting p-values are always lower than the p-values from trying to fit a weibull or gamma distribution. So, to put it another way, I generate a random set of values from an exponential distribtion using
rexp(1000)

but when I pass it through my code, the resulting p-values are, for instance:
[1,] "distribution" "ks pvalue"
[2,] gamma          "0.850558314129566"
[3,] weibull        "0.833929454438442"
[4,] logistic       "0"
[5,] normal         "0"
[6,] exponential    "0.704115316673917"
[7,] poisson        "0"

The section of code that performs the test on the exponential distribution, for instance, is (credited with GREAT thanks to @TinaW from StackOverflow here):
gf_shape    = "exponential"
fd_e        = fitdistr(data, "exponential")
est_rate    = fd_e$estimate[[1]]
ks          = ks.test(data, "pexp", rate=est_rate)
results[i,] = c(gf_shape, est_rate, "NA", ks$statistic, ks$p.value)

Do you guys have any idea what I'm doing wrong? I've tried increasing and decreasing the sample size, toying with the parameters, but the gamma and weibull p-values are always larger than that of the exponential fit. Any ideas?

A: Note that the exponential distribution is a special case of the Weibull distribution the Weibull's shape parameter equals $1$.  Thus, the Weibull is more flexible and would be able to better fit any exponential data despite the data's exponentiality (is that a word?). If you are not taking that into account, that may be (part of) the answer. A more flexible model (distribution, here) will always fit better than a less flexible model irrespective of the fact that the latter is correct.


text:
Q: new Class item displaying as object instead of string I'm still extremely new to Ruby. I took a class on Codecademy and I'm currently doing the "Final" where I have to make a todo list.
One of the parts of the todo list is to be able to add tasks (obviously). Another part is to be able to show all current tasks. Now, technically, both of these are working. But, when I create a new task using the class I made (Task) and then show the tasks, it displays the object ID instead of the string. If I simply use my add method without using my Task class, it will display the string like I want it too.
My goal is to get my script to display the string while using the Task class. If someone could please explain to me why it's not working and how I can fix it, I'd appreciate that.
Here's the code:
## Classes ##

#List Class - Used for anything involving the list
class List
  attr_reader :all_tasks

  def initialize
    @all_tasks = []
  end

  def add(task)
    all_tasks << task
  end

  def show
    all_tasks
  end
end

#Task Class - Used for anything involving Tasks
class Task
  attr_reader :description

  def initialize(description)
    @description = description
  end
end

## Modules ##
module Promptable
  def prompt(message = "What would you like to do?", symbol = " >: ")
    print message
    print symbol
    gets.chomp
  end

  def show
    menu
  end
end

module Menu
  def menu
    puts "
    'add' - Add a task to the list \n
    'delete' - Delete a task from the list \n
    'update' - Update a task in the list \n
    'show' - Shows current tasks in list"
  end
end

#Methods - various methods

#Program Runner
if __FILE__ == $PROGRAM_NAME
  include Menu
  include Promptable

  my_list = List.new
  puts "Please choose from the following list: "
  until ['q'].include?(user_input = prompt(show).downcase)
    case user_input
    when 'add'
      puts "What task would you like to do?"
      my_list.add(Task.new(gets.chomp))
    when 'q'
      puts "Qutting...."
    when 'show'
      puts my_list.show
    else "That is not a valid command"
    end
  end
end

A: puts my_list.show

Will display the tasks one by one. Since the Task class doesn't have a to_s method, the default one will be used. Just add one:
class Task
  # ...

  alias to_s description
end

BTW strings are objects too. Pretty much everything in Ruby is an object.


text:
Q: Removing redundant folder paths from a list I have the following list which contains a series of folder paths. Some of these are redundant so I need to remove them and the final list should only contain the bottom level folders:
Initial list:
var paths = new List<string>
{
    "Pavements/",
    "Pavements/2019_05/",
    "Pavements/2019_06/",
    "Pavements/2019_06/A/",
    "Roads/",
    "Roads/2019_06/"
};

The final List should look like:
paths =
{
    "Pavements/2019_05/",
    "Pavements/2019_06/A/",
    "Roads/2019_06/"
};

i.e. all the upper level folder paths have been removed.
Does anyone know how I can achieve this? I have a feeling I need a recursive method but am unsure how to go about it. I am using C# but answer in java or something similar is ok.
Thanks.

A: One way to do this is with a linq query that compares each item to all the other items and returns the item only if none of the others begin with it:
paths = paths.Where(path => !paths.Any(p => p != path && p.StartsWith(path))).ToList();


text:
Q: How to backup an iOS enterprise app and install on multiple devices The question is not about programming. It is related to back-up of an iOS enterprise app(not AppStore) and installing it to multiple devices.
Can we back-up an enterprise app along with its Document-Directory and then port that backed-up app to the multiple iOS devices along with the data in Document-Directory?
I can do the first part easily I guess, but when it is coupled with the second part then it seems tricky.
Please share any information regarding this. Would be very helpful.

A: Got it - Apple Configurator
The device back-up feature can be used to restore and back-up an app along-with its data.
More is here


text:
Q: use of 'leftover' Some say that the leftover is the amount of food or drink left in the container from which it was served; but some say that leftover is the amount left in the container from which it was used; e.g.

There is some drink in a jug equaling to amount of four glasses, one third has been poured in three glasses, now amount left in the jug, is 'leftover'? OR
There is some drink in a glass, half has been drunk by someone, now the half remaining in the glass is leftover?

To sum up, the amount left having eaten or drunk is leftover or the amount unused (not drunk or eaten yet) in the main container is leftover?

A: The dictionary definitions don't really make this clear one way or the other, do they?
Leftover food is (or leftovers are) food that has been set out for a meal that has been neither consumed nor served, and so can be saved and used in another meal. Leftover food is not food or drink that has been served to a person and not finished.
For example, leftover bread can be made into bread pudding. Leftover rice can be made into fried rice. I can take leftover hamburgers and vegetables and make them into a casserole, or leftover sausages and mashed potatoes and make them into a shepherd's pie. On the other hand, there isn't much you can do with leftover eggs besides throw them away.
Now here's where it can be confusing. I can say this:

I would never use leftover food from someone's plate to make leftovers.

You can indeed use leftover to speak of food that someone has left on their plate, but you have to specify it as such. You are then using the word in the broader sense of anything that has been left over: leftover furniture, leftover clothes, leftover space, etc. If you just say leftover food (when speaking of food served at a meal) or leftovers, you are speaking of food that can be repurposed and served at another meal.
Edit: As Laurel mentions in the comments, an exception to this is food that you bring home from a restaurant meal that you couldn't finish, generally for your own consumption later. My comments stand for meals made at home.


text:
Q: Fatal error: Call to a member function rowcount() on a non-object on a working query I'm running this query
try
{
$park_id = $_GET['park_id'];
$query2="SELECT `name` FROM  `tpf_rides` WHERE  `park_id` = $park_id AND

`top_ride` = 1 ORDER BY `name` ASC";
$result2 = $pdo->query($query2);
}
catch (PDOException $e)
{
$output = 'Unable to pull rides.';
include 'output.html.php';
}

$output = 'Sucessfully pulled rides';
//include 'output.html.php';//

and displaying it with
<?php foreach ($result2 as $row2): ?>

<?php echo $row2['name']; ?>

<?php endforeach; ?>

This all works fine and the list of 'top rides' displays correctly.
The issue is I'm trying to add an if statement so that if a particular 'park' has no 'top rides' that part of the page is not shown. Below is the code I'm trying to make work but I get the error "Fatal error: Call to a member function rowcount() on a non-object in /home/danville/public_html/parkindex/park.php on line 133" this bieng line 133 "if ($count2 = $query2->rowcount() < 1)" Can anybody help?
if ($count2 = $query2->rowcount() < 1)

{
    echo "No results found";
}

else

{
 echo "
Top Attractions
";

foreach ($result2 as $row2){

echo "

{$row2['name']}

";

}

}

A: I had the same Problem. It turns out that the fix was to prepare, then execute.
$result = $pdo->prepare($query2);
$result->execute();
$count = $result->rowCount();

Strangely, rowCount is a function of the object returned from $pdo->query();, It seems like an internal glitch.
Try:
var_dump(get_class_methods($result));

to see what I mean.

A: Get the rowcount of the result, not of the query string
if ($count2 = $result2->rowcount() < 1)

not
if ($count2 = $query2->rowcount() < 1)

A: there is something that is not logic in my opinion. If you already have $park_id and you match one specific row so to handle the result to appair only if top_rides = 1
so i would change query as follow
$query2="SELECT `name`, `top_rides` FROM  `tpf_rides` WHERE `park_id` = '".$park_id."'";

So now we are ready to place if condition and show only result wich has top_rides
I assume this field is set to 1 when park has top rides.
foreach ($result2 as $row2)
{
    if($row2['top_rides'] == '1')
    {
         echo '

'. $row2['name'] .'

';
    }
    else
    {
         echo "No results found";
    }
}

you will have to change yuor query to get park_top field as well so
$query2="SELECT `name` FROM  `tpf_rides` WHERE  `park_id` = $park_id AND  `top_ride` = 1 ORDER BY `name` ASC";

A: This is where all my queries run for the page. the query in question here is query2
<?php

try
{
$pdo = new PDO('mysql:host=localhost;dbname=danville_tpf', 'user',
'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server.';
include 'output.html.php';
exit();
}

$output = 'Theme Park Database initialized';
//include 'output.html.php';//

try
{
$park_id = $_GET['park_id'];
$query="SELECT * FROM tpf_parks WHERE park_id = $park_id";
$result = $pdo->query($query);
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server.';
//include 'output.html.php';//
}

$output = 'Sucessfully pulled park';
//include 'output.html.php';//

foreach ($result as $row)
{
$parkdetails[] = array(
'name' => $row['name'],
'blurb' => $row['blurb'],
'website' => $row['website'],
'address' => $row['address'],
'logo' => $row['logo']);
}

try
{
$park_id = $_GET['park_id'];
$query2="SELECT `name` FROM  `tpf_rides` WHERE  `park_id` = $park_id AND

`top_ride` = 1 ORDER BY `name` ASC";
$result2 = $pdo->query($query2);
}
catch (PDOException $e)
{
$output = 'Unable to pull rides.';
include 'output.html.php';
}

$output = 'Sucessfully pulled rides';
//include 'output.html.php';//

try
{
$park_id = $_GET['park_id'];
$query3="SELECT `url` FROM  `tpf_images` WHERE  `park_id` = $park_id ORDER

BY RAND() LIMIT 1";
$result3 = $pdo->query($query3);
}
catch (PDOException $e)
{
$output = 'Unable to pull image.';
include 'output.html.php';
}

$output = 'Sucessfully pulled image';
//include 'output.html.php';//

?>

This is where the results should show

<?php foreach ($result2 as $row2): ?>

<?php echo $row2['name']; ?>

<?php endforeach; ?>

<?php

if ($count2 = $results2->rowcount() < 1)

{
    echo "No results found";
}

else

{
 echo "
Top Attractions
";

foreach ($result2 as $row2){

echo "

{$row2['name']}

";

}

}

?>

line 133 is now if ($count2 = $results2->rowcount() < 1)


text:
Q: Unexpected singularities in an integral I am doing an indefinite integral,
$$f=\int\frac{r^2}{(r^2 + d^2 -2rd\cos{\theta})^2}dr$$
where $0\leq r< \infty$, $0\leq d< \infty$ and $0\leq \theta \leq \pi$. The integral that I am getting (I used Wolfram Alpha to calculate the integral) is as follows
$$f = \frac{1}{4 \sin^2{\theta}}\left[\frac{\tan^{-1}{\left(\frac{r-d\cos{\theta}}{d\sin{\theta}}\right)}}{d\sin{\theta}}+ \frac{2r\cos^2{\theta}-d\cos{\theta}-r}{r^2 +d^2 -2rd \cos{\theta}}\right]$$
which is singular at $\theta = 0,\pi$ and at $d=0$ whereas the integrand was only singular at $(r,\theta)=(d,0)$. I don't understand why is it so. Why am I getting singularities in the solution of the integral at places where there were no singularities in the integrand? Thanks!

A: The singularity of the expression signals you that the integral tends to diverge. A closer look confirms that the definite integral diverges whenever $\sin\theta=0$ and $r_1\le d\cos\theta\le r_2$, where $r_1 <r_2$ are the integration limits. You can however convince yourself that if $d\cos\theta $ is outside the integration range the definite integral converges:
$$
\lim_{\sin\theta\to0}f (r_2,d,\theta)-f (r_1,d,\theta)<\infty.
$$


text:
Q: Azure App Service on Linux not displaying web server logs I have a ASP.NET Core 2.2 app deployed to Azure App Service (Linux). I am unable to see web server logs (HTTP traffic) to the application.
Microsoft support advise that the HTTP traffic should be visible in the xx_default_docker.log file but it isnt. I've verified that the application can log, since my application logs are present.
The docker startup also indicates that HTTP logging is enabled. The default_docker.log is shown below.
2019-08-22 13:54:56.855 INFO  - docker run -d -p 34938:8080 --name xxxx -e WEBSITE_SITE_NAME=xxxx -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=xxxx -e WEBSITE_INSTANCE_ID=e9d7d581f74fa3aa82fed4e52ba7b581a49d7a218f02ccc2fb509536bfb3742f -e HTTP_LOGGING_ENABLED=1 appsvc/dotnetcore:2.2_1905171704

2019-08-22T13:54:59.044083569Z   _____
2019-08-22T13:54:59.044114169Z   /  _  \ __________ _________   ____
2019-08-22T13:54:59.044119569Z  /  /_\  \___   /  |  \_  __ \_/ __ \
2019-08-22T13:54:59.044123669Z /    |    \/    /|  |  /|  | \/\  ___/
2019-08-22T13:54:59.044127469Z \____|__  /_____ \____/ |__|    \___  >
2019-08-22T13:54:59.044131769Z         \/      \/                  \/
2019-08-22T13:54:59.044135569Z A P P   S E R V I C E   O N   L I N U X
2019-08-22T13:54:59.044139270Z
2019-08-22T13:54:59.044142970Z Documentation: http://aka.ms/webapp-linux
2019-08-22T13:54:59.044146470Z Dotnet quickstart: https://aka.ms/dotnet-qs
2019-08-22T13:54:59.044150070Z .NETCore runtime version: 2.2.4
2019-08-22T13:54:59.044153770Z
2019-08-22T13:54:59.271246451Z Running oryx -appPath /home/site/wwwroot -output /opt/startup/startup.sh -defaultAppFilePath /defaulthome/hostingstart/hostingstart.dll     -bindPort 8080 -userStartupCommand ''
2019-08-22T13:54:59.350208661Z Oryx Version : 0.2.20190611.2, Commit: 61c21ec7356c805d09cc5784e0d27c99f84a325f
2019-08-22T13:54:59.350768864Z
2019-08-22T13:54:59.916450806Z Writing output script to '/opt/startup/startup.sh'
2019-08-22T13:54:59.931177383Z Startup command was not provided, finding the startup file name...
2019-08-22T13:54:59.935771207Z Found the startup file 'xxxx.dll'
2019-08-22T13:54:59.936288310Z Running the command 'dotnet 'xxxx.dll''...
2019-08-22T13:55:03.945566063Z [40m[1m[33mwarn[39m[22m[49m: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
2019-08-22T13:55:03.946631868Z       No XML encryptor configured. Key {f65d0e04-cd1c-4e7f-9fe3-4d747181c8fe} may be persisted to storage in unencrypted form.
2019-08-22T13:55:09.882317543Z [40m[1m[33mwarn[39m[22m[49m: Microsoft.AspNetCore.Identity.UserManager[5]
2019-08-22T13:55:09.882363644Z       User 72d6fc3a-a134-4fd1-b3fe-8afa100d12b8 is already in role Admin.
2019-08-22T13:55:10.024079981Z Hosting environment: Production
2019-08-22T13:55:10.030438114Z Content root path: /home/site/wwwroot
2019-08-22T13:55:10.030464314Z Now listening on: http://[::]:8080
2019-08-22T13:55:10.031175518Z Application started. Press Ctrl+C to shut down.
2019-08-22T13:55:10.837009409Z [40m[1m[33mwarn[39m[22m[49m: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
2019-08-22T13:55:10.837048710Z       Failed to determine the https port for redirect.

A: Microsoft documentation indicate that it isnt possible for Linux yet. https://learn.microsoft.com/en-us/azure/app-service/troubleshoot-diagnostic-logs
Additionally this was confirmed by @AzureSupport on Twitter https://twitter.com/AveerRa/status/1174683871134330881


text:
Q: call parameterised function on dynamic button click in php I want to call a parameterised function in PHP. I am using AJAX for that.
This is my dynamic button. I need to pass $sub_id to the delet(sub_id) function and perform there some SQL.
echo "<input type='submit' name='disable' value='Disable' onClick='delet($sub_id);'/>	";

This is my script so far:

and this is PHP function:
function delet($ID){
    echo $ID;
    //do sql stuff...
}

All the code is in one file and I am doing this in wordpress default template swentysixteen. so there is no .php extension to my page.
when I click on the dynamic button, I am getting 404 error in url parameter of ajax. When I see console, the url link seems to be correct.
Please help me in this issue. Thanks.

A: First of all, dont combine in your mind JS code and PHP code into one.
Please set in your mind that JS code is executes on Browser which is provided by server through PHP. PHP code executes on Server side and provide HTML code as output to client(browser). so JS variables and PHP variable have no any relationship directly or indirectly.
For your solution,
You have passed ID parameterusing GET by ajax. so in SErver side you will get passed data in $_GET variable so ID will get by $_GET['ID']
function delete($ID){
   echo $ID;
   //do sql stuff...
}
if(isset($_GET['action']) && $_GET['action']=="delete")
{
    if(isset($_GET['ID']) && !empty($_GET['ID']))
    {
       delete($_GET['ID']);
       echo "deleted successfully";
    }
    else
    {
       echo "ID not passed for delete record";
    }
    die(); // you stop execution of PHP after delete opration here
}

Javascript Code