text:
Q: Usage of javax.faces.DEFAULT_SUFFIX results in blank page after long load With my files named to .xhtml and no redefinition  of javax.faces.DEFAULT_SUFFIX in my web.xml, everything works properly.
But I would like to use the .html extension as I write html5 and not xhtml.
Here is my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

<context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.html</param-value>
</context-param>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>

<welcome-file-list>
    <welcome-file>index.jsf</welcome-file>
</welcome-file-list>
</web-app>

When I visit  contextname/ I would expect to fall on the same page than contextname/index.jsf as it is the first of my welcome file list but instead index.html file is used and I see the template code, as I would expect by visiting contextname/index.html.
When I try to visit contextname/index.jsf there is a very long load, around 10 seconds and the page ends up blank.
Once again, without the parameter and with my file renamed to index.xhtml everything works fine.


text:
Q: Extra routes being created when assigning virtual network interfaces I'm running a Ubuntu VPS that I'm using as a squid proxy server. From my provider I've got a load of IP addresses which I'm assigning as virtual interfaces within /etc/network/interfaces.d/eth0.cfg like the following:
#Endpoint_48
auto eth0:48
iface eth0:48 inet static
address 91.xxx.xxx.xx
Netmask 255.255.255.255
Broadcast 91.xxx.xxx.xx

The issue I'm having is that upon boot, Ubuntu seems to be creating loads of extra routes, some of which will have such large subnets that I'm unable to reach any website on those subnets. E.g. This created route:
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
91.0.0.0        *               255.0.0.0       U     0      0        0 eth0

... will prevent me from reaching http://ubuntu.com which at present is on 91.189.94.40
Removing these routes with route del solves the issue, but they appear again on reboot. Any thoughts on how to prevent them from appearing entirely?
Cheers!

A: Do you really have capital N and capital B in the configuration file? if so, that is most likely the reason for the issue you are facing, since those are not recognized options in network configuration files.
The correct directives are netmask and broadcast.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to detect the length of a string? (batch) I'm trying to make a batch file to solve a puzzle. At my current moment I need a way to detect the length of a string. I don't really know where to start and did not find any related articles on a title search.

A: @echo off
 setlocal enabledelayedexpansion
 set "line=this is my string"

 for /l %%a in (0,1,8191) do (
    Set "each=!line:~%%a,1!"
    if not defined each echo length: %%a & endlocal & set length=%%a & goto :eof
 )

If you want to test the length of the string excluding special characters or whitespace you need to remove whitespace and escape special characters before setting each


text:
Q: Trouble using .indexOf() with .filter() Newbie to javascript and es6 here.  I'm building a react-native app with firebase and redux.  One of my action creators is really just a search bar function.  I'm fetching data from Firebase with this code:
export const searchResult = () => {
  const { currentUser } = firebase.auth();
  return (dispatch) => {
    firebase.database().ref(`/users/${currentUser.uid}/entries`)
      .on('value', snapshot => {
        const obj = snapshot.val();

That part of the function is working swimmingly. Then I want to turn the data into an array, instead of just some objects.
  const array1 = Object.keys(obj).map(function(key) {
    return [obj[key]];
});

And again, this executes perfectly. It's the next bit of code that I'm for certain is wrong, just don't know how to fix it.  I'm wanting to return a filter of array1 according to what goes in the search bar. Here I have search bar hard-coded to element (I'll switch that once I get the code working).
      const element = '0';
      const array2 = array1.filter(array1.indexOf(element) !== -1);

        dispatch({ type: SEARCH_RESULT_SUCCESS, payload: array2 });
      });
  };
};

As of now, I'm pretty sure this is just returning a boolean of false, instead of returning objects from the array that match element. Do I need another function in here to bridge my logic? What am I missing? Any help is much appreciated! Thanks in advance!

A: You need to provide a function callback to filter method.
  const element = '0';
  const array2 = array1.filter((arr1Elem) => array1.indexOf(element) !== -1);

    dispatch({ type: SEARCH_RESULT_SUCCESS, payload: array2 });
  });
  };
};


text:
Q: React - Mapping through response data from get request-why response data is not displayed? Im new to react and I am trying to display response data I get from an get request.I have been looking at multiple similar posts, trying to implement what worked for others, but for me nothing works. In my code below, Im not getting any errors (set state seems to work too) but nothing is being displayed and I don't know why. Any ideas? Thanks!
        class Testing extends React.Component {
            constructor(props) {
                super(props);
                this.state = {
                    name: []
                };
                this.getData = this.getData.bind(this)
            }
            componentDidMount() {
                this.getData();
            }
            getData() {
                axios.get('https://example.com)
                    .then(results => {
                        return results.data;
                    })
                    .then(res => {
                        let arr = res.items;
                        let test = [];
                        return arr.map(function(item) {
                            test.push(item);
                        })
                        this.setState({
                            name: test
                        });
                    })
                }

                render() {
                    const persons = this.state.name.map((item, i) => {
                        return

 {item.name}

                    });

                    return

                            All: {persons}

                }
            }

changed render:
 class Testing extends React.Component {
            constructor(props) {
                super(props);
                this.state = {
                    name: []
                };
                this.getData = this.getData.bind(this)
            }
            componentDidMount() {
                axios.get('https://example.com)
                    .then(results => {
                        return results.data;
                    })
                    .then(res => {
                        let arr = res.items;
                        let test = [];
                        return arr.map(function(item) {
                            test.push(item);
                        })
                        this.setState({
                            name: test
                        });

                    })
                }

                render() {

                       this.state.name ? this.state.name.map((item, i) => {
                           return (

{ item.name }

                           )
                       }) : null;

                }
            }

error here:

  this.state.name ? this.state.name.map((item, i) => {
   return (
        ^

{ item.name }

A: The problem with your code is that your setState is never called. If you look at your last then function of your api call, you have return statement right before the setState (i.e. at arr.map). Because of that your code never reaches the setState. Remove the return statement and it should work:
             getData() {
                axios.get('https://example.com)
                    .then(results => {
                        return results.data;
                    })
                    .then(res => {
                        let arr = res.items;
                        let test = [];
                        arr.map(function(item) {
                            test.push(item);
                        })
                        this.setState({
                            name: test
                        });
                    })
                }

Edit:: Ok try wrapping your render in brackets () like this
               render() {
                    const persons = this.state.name.map((item, i) => {
                        return
                           (

 {item.name}

);
                    });

                    return
                     (

                            All: {persons}

);
                }

A: it seems like you forgot to add a single quote inside the get request like this     axios.get('https://example.com')
your code:
axios.get('https://example.com')
  .then(results => {
     return results.data;
  });

A: Firstly, move your getData function or even whole request logic into componentWillMount function. Secondly, change your render function into:
render() {
   return (

      this.state.name ? this.state.name.map((item, i) => {
          return (

{ item.name }

          )
      }) : null;

   )
}


text:
Q: error after change in authentication in Spotify API After Spotify change the form to use the API for a search data, now required an access token. I added a headers with the access token, but i get an error.
$.ajax({
        url: 'https://api.spotify.com/v1/search?type=track&limit=20&query=' + query,
        headers: {
            'Content-Type: application/json',
            'Authorization: Bearer <?php echo $token; ?>'
            },
        datatype: 'json'
        success: formatArtists,
        error: function() {
            console.log('fatal error!!!')
        },

To obtained the token, used this code in PHP:
<?php
$url = 'https://accounts.spotify.com/api/token';
$method = 'POST';

$credentials = "CLIENT ID'S";

$headers = array(
    "Accept: */*",
    "Content-Type: application/x-www-form-urlencoded",
    "User-Agent: runscope/0.1",
    "Authorization: Basic " . base64_encode($credentials));
$data = 'grant_type=client_credentials';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$response = json_decode($response, true);
curl_close($ch);
$token = $response['access_token'];

I has probed the access token in the Spotify web console and works, Has anyone managed to fix this error with the Spotify API?


text:
Q: Curve fitting with known coefficients in Python I tried using Numpy, Scipy and Scikitlearn, but couldn't find what I need in any of them, basically I need to fit a curve to a dataset, but restricting some of the coefficients to known values, I found how to do it in MATLAB, using fittype, but couldn't do it in python.
In my case I have a dataset of X and Y and I need to find the best fitting curve, I know it's a polynomial of second degree (ax^2 + bx + c) and I know it's values of b and c, so I just needed it to find the value of a.
The solution I found in MATLAB was https://www.mathworks.com/matlabcentral/answers/216688-constraining-polyfit-with-known-coefficients which is the same problem as mine, but with the difference that their polynomial was of degree 5th, how could I do something similar in python?
To add some info: I need to fit a curve to a dataset, so things like scipy.optimize.curve_fit that expects a function won't work (at least as far as I tried).

A: The tools you have available usually expect functions only inputting their parameters (a being the only unknown in your case), or inputting their parameters and some data (a, x, and y in your case).
Scipy's curve-fit handles that use-case just fine, so long as we hand it a function that it understands. It expects x first and all your parameters as the remaining arguments:
from scipy.optimize import curve_fit
import numpy as np

b = 0
c = 0
def f(x, a):
    return c+x*(b+x*a)

x = np.linspace(-5, 5)
y = x**2

# params == [1.]
params, _ = curve_fit(f, x, y)

Alternatively you can reach for your favorite minimization routine. The difference here is that you manually construct the error function so that it only inputs the parameters you care about, and then you don't need to provide that data to scipy.
from scipy.optimize import minimize
import numpy as np

b = 0
c = 0

x = np.linspace(-5, 5)
y = x**2

def error(a):
    prediction = c+x*(b+x*a)
    return np.linalg.norm(prediction-y)/len(prediction)**.5

result = minimize(error, np.array([42.]))
assert result.success

# params == [1.]
params = result.x

I don't think scipy has a partially applied polynomial fit function built-in, but you could use either of the above ideas to easily build one yourself if you do that kind of thing a lot.
from scipy.optimize import curve_fit
import numpy as np

def polyfit(coefs, x, y):
    # build a mapping from null coefficient locations to locations in the function
    # coefficients we're passing to curve_fit
    #
    # idx[j]==i means that unknown_coefs[i] belongs in coefs[j]
    _tmp = [i for i,c in enumerate(coefs) if c is None]
    idx = {j:i for i,j in enumerate(_tmp)}

    def f(x, *unknown_coefs):
        # create the entire polynomial's coefficients by filling in the unknown
        # values in the right places, using the aforementioned mapping
        p = [(unknown_coefs[idx[i]] if c is None else c) for i,c in enumerate(coefs)]
        return np.polyval(p, x)

    # we're passing an initial value just so that scipy knows how many parameters
    # to use
    params, _ = curve_fit(f, x, y, np.zeros((sum(c is None for c in coefs),)))

    # return all the polynomial's coefficients, not just the few we just discovered
    return np.array([(params[idx[i]] if c is None else c) for i,c in enumerate(coefs)])

x = np.linspace(-5, 5)
y = x**2

# (unknown)x^2 + 1x + 0
# params == [1, 0, 0.]
params = fit([None, 0, 0], x, y)

Similar features exist in nearly every mainstream scientific library; you just might need to reshape your problem a bit to frame it in terms of the available primitives.


text:
Q: Android: Why Can't I Override setFrame From View? Simply trying to extend View and do some custom work, but Eclipse will complain when I attempt to override the setFrame method. Claiming there isn't a method in the parent class to override:

The method setFrame(int, int, int, int) of type Test must override or implement a supertype method

Here is the signature of the method from android SDK source.
protected boolean setFrame(int left, int top, int right, int bottom)
As you can see it's not private or package level, or even specified as final... just protected. Which should mean I am totally able to override it in a subclass. Right? Below is the bare minimum of what I'm trying to do in Eclipse. Perhaps it is just an Eclipse error, but I'm not too familiar with using Ant to check against that.
Edit: To those answering that setFrame is not defined in the View class, I can assure you it is. How else do you think I got the method signature? It is even called during layout(). Or am I seriously just crazy?
git HEAD: View.java
Cupcake (1.5r4): View.java
You can even see the method being overriden in the ImageView and TextView classes...this is why I am seriously confused as to why I cannot override it myself from View directly...
public class Test extends View {
    public Test(Context context) {
        super(context);
    }

    public Test(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public Test(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected boolean setFrame(int left, int top, int right, int bottom) {
        return super.setFrame(left, top, right, bottom);
    }
}

A: According to the documentation, setFrame is not defined in the View class (not strictly true - see edit). Surprising, each subclass, TextView and ImageView, define it themselves.  You'll have to have to extend the specific subclass for each widget you want to override this behavior.  This is based on the docs for Android 2.3 r1 - 05 Jan 2011 12:43.
See the documentation:
Classes that define setFrame
http://www.google.com/search?q=site:developer.android.com+%22boolean+setFrame%22
TextView and ImageView.
Edit:
As the OP points out in the comments, the method is clearly defined in the View.java source code. However, the documentation acts as if the method isn't defined there.
The reason for this is that the setFrame() method in View has the @hide Javadoc tag:
/**
 * Assign a size and position to this view.
 *
 * This is called from layout.
 *
 * @param left Left position, relative to parent
 * @param top Top position, relative to parent
 * @param right Right position, relative to parent
 * @param bottom Bottom position, relative to parent
 * @return true if the new size and position are different than the
 *         previous ones
 * {@hide}
 */
protected boolean setFrame(int left, int top, int right, int bottom) {

Apparently, this hides the method from the Javadoc:
http://www.androidjavadoc.com/?p=63

The especial [sic] attention is need to turn to the @hide tag which standard doclet can't interpret and which hides non-SDK source and thus this code shouldn't be used in applications.

Is it possible that the reason it can't be overridden is that the Eclipse plug-in for Android or the Android compiler is somehow enforcing the @hide tag? I don't know.

A: Because setFrame is not defined in the View class


text:
Q: create auth permission dialog in facebook basically i have integrated fb in my app and for that i have created the app in fb developer site.
I have got app id and i have authorized my app with fb using this id.
While asking permissions in fb, the auth dialog havn't appeared good. like i want to display auth dialog as below image.

but i didn't see above style of auth dialog while authorization. How will i get that style of dialog?.
Currently i am getting the below style of dialog.

Please advise in this regards.
Thanks!!!

A: Go to your facebook profile from which you have created your app,or from which you are accessing your app.
Then go to Privacy Setting -> Apps, Games and Websites
And here go to apps you use there click edit in front of your app and then remove it.
It will simply remove your permission and will ask you again as you have shown in screen.
If anything feel free to ask.


text:
Q: Subquery to show all other categories one to many relationships I am trying to create a query where I can view all the books that are in both category 1 and 2 (e.g. horror and fiction) but also show the categories that the book also belongs to. How do I go about this? I can only assume that I'm going to need a recursive subquery, however this could be inefficient.
SELECT book.bookid,
       book.author,
       book.title,
       Group_concat(DISTINCT category.categorydesc)
FROM   book,
       bookscategories,
       category
WHERE  book.bookid = bookscategories.bookid
       AND bookscategories.categoryid = category.categoryid
       AND category.categoryid = 1
       AND category.categoryid = 2
GROUP  BY book.bookid;

A: select b.bookid, b.author, b.title, group_concat(distinct c.categorydesc)
from book as b
inner join bookcategories as bc on b.bookid = bc.bookid
inner join categories as c on bc.categoryid = c.categoryid
where b.bookid in (select bc1.bookid
    from bookcategories as bc1
    inner join bookcategories as bc2 on bc1.bookid = bc2.bookid
    where bc1.categoryid = 1 and bc2.categoryid = 2)
group by b.bookid;

I am not sure about the performance of this query because it uses the bookcategories table 3 times.
Selecting b.author and b.title is not technically correct, but should work in this case because b.bookid is probably unique. Otherwise it is not possible to select something that is neither part of the group by clause nor used in an aggregate function.
I believe that the code that you posted will always return an empty result set because you are restricting category.categoryid to be both 1 and 2 at the same time.


text:
Q: Поиск столбцов, по фрагменту их названий Есть 7к признаков, многие среди которых - Id номер, соответственно их нужно удалить.
Написал код
to_drop=[]
for n in df_court.columns:
    index = n.find("id")
    if index ==-1:
        to_drop.append(n)

print(to_drop, len(to_drop))

но он выдает слишком много столбцов, в том числе таких, где фрагмент id не представлен.
   [.... 'r_data_courtPractice_dashboard_blocks_2_lastCaseLabel',
 'r_data_courtPractice_dashboard_blocks_2_selected',
'r_data_courtPractice_dashboard_blocks_2_sum',
'r_data_courtPractice_dashboard_blocks_2_title', 'r_data_courtPractice_title',
'r_data_courtPractice_total'] 6708

Как исправить код, чтобы он правильно не ловил лишние имена?

A: Метод DataFrame.filter(...) фильтрует DataFrame по названиям столбцов.
Пример:
In [370]: df
Out[370]:
   cookieDisclaimerAgree  data.id data.name  isFollowed        ...          showFollowReminder  showNps  showRequestDocsButton  showTaxRiskButton
0                   True      111     name1       False        ...                       False    False                  False              False
1                   True      112     name2       False        ...                       False    False                  False              False

[2 rows x 10 columns]

In [371]: df.columns
Out[371]:
Index(['cookieDisclaimerAgree', 'data.id', 'data.name', 'isFollowed', 'showErrorFeedbackButton', 'showFollowButton',
       'showFollowReminder', 'showNps', 'showRequestDocsButton', 'showTaxRiskButton'],
      dtype='object')

In [372]: df.filter(regex=r'^show')
Out[372]:
   showErrorFeedbackButton  showFollowButton  showFollowReminder  showNps  showRequestDocsButton  showTaxRiskButton
0                     True              True               False    False                  False              False
1                     True              True               False    False                  False              False

In [373]: df.filter(regex=r'^show.*Button$')
Out[373]:
   showErrorFeedbackButton  showFollowButton  showRequestDocsButton  showTaxRiskButton
0                     True              True                  False              False
1                     True              True                  False              False


text:
Q: Fixing or replacing Python IDLE on Mac OS I recently ran a .py file to IDLE that caused IDLE to crash (after running for some time). While it was running I tried many things including Force Quit etc.  After the crash I tried opening IDLE and got the message that the port was missing? (something to that effect).  After a day I tried IDLE and the the offending py file automatically restarted on IDLE.  I closed IDLE and deleted the offending py file and IDLE (1.24, Python 2.54) finally appeared in it's regular form.  I created a new simple py file and IDLE ran it correctly but I could not run another py file.  I also noticed that the new py file also created a .pyc copy.
Hopefully this isn;t too confusing.  Do I need to reinstall IDLE?  Is there a simpler fix?


text:
Q: importScripts returns undefined in the web workers For earlier browser versions, Promise is undefined in web workers. So I am using a polyfill Promise by importScripts('Promise.js'), if Promise is undefined. But still I get an undefined object in return.
var promise;
if(typeof Promise === undefined) {
  self.importScripts('./Promise.js').Promise;
}

promise = new Promise(function (resolve, reject) {
  var url = ajaxArgs.url || '',
      data = ajaxArgs.data || {},
      type = ajaxArgs.method || 'GET',
      isGet = type === 'GET',
      request = new XMLHttpRequest();
      ........
}

How can I make this work for web workers?

A: The importScripts function doesn't return anything. When  you access a .Promise property on the call, this will throw, and your code stops executing. Btw, typeof never returns undefined, so you were lucky and it was never exected.
if (typeof Promise !== "function") self.importScripts('./Promise.js');

var promise = new Promise(function (resolve, reject) {
    …
});


text:
Q: Android - how to delete item from a cursor? Let's say I make the following cursor to get the call log of someone:
String[] strFields = {
    android.provider.CallLog.Calls.NUMBER,
    android.provider.CallLog.Calls.TYPE,
    android.provider.CallLog.Calls.CACHED_NAME,
    android.provider.CallLog.Calls.CACHED_NUMBER_TYPE
    };

String strOrder = android.provider.CallLog.Calls.DATE + " DESC";

Cursor mCallCursor = getContentResolver().query(
        android.provider.CallLog.Calls.CONTENT_URI,
        strFields,
        null,
        null,
        strOrder
        );

Now how would I go about deleted the ith item in this cursor? This could also be a cursor getting list of music, etc. So then I must ask - is this even possible? I can understand for certain cursors that 3rd party apps wouldn't be allowed to delete from.
Thanks.

A: You can to a trick with a MatrixCursor. With this strategy, you copy the cursor, and leave out the one row you want to exclude. This is - obviously,  not very efficient for large cursors as you will keep the entire dataset in memory.
You also have to repeat the String array of column names in the constructor of the MatrixCursor. You should keep this as a Constant.
   //TODO: put the value you want to exclude
   String exclueRef = "Some id to exclude for the new";
   MatrixCursor newCursor = new MatrixCursor(new String[] {"column A", "column B");
         if (cursor.moveToFirst()) {
            do {
                // skip the copy of this one ....
                if (cursor.getString(0).equals(exclueRef))
                    continue;
                newCursor.addRow(new Object[]{cursor.getString(0), cursor.getString(1)});
            } while (cursor.moveToNext());
        }

I constantly battle with this; trying to make my apps with cursors and content providers only, keeping away from object mapping as long as I can. You should see some of my ViewBinders ... :-)

A: Sorry mate you can't delete from a cursor.
You must either use your ContentResolver or a SQL call of some sort..


text:
Q: Resetting GRBL command not working in arduino IDE serial monitor I am testing Grbl CNC Shield with my Arduino Uno. Everything is working except for the ctrl-x command. I tried on the Arduino IDE serial monitor but it appears that it dont recognize.
Does anyone how to solve this?
Any help would be appreciated.
I Tried:
Holding Ctrl with x and nothing happend.
sending ^X or ^x but the console responded "Error: Excepted command Letter"
sending 0x18 on the console and it responded "Error: Bad Number Format"
When the reset command is triggered and it's in the Alarm lock it should reset the grbl and show that message again. This would happen too if the grbl is running normally

A: cnc_ard = serial.Serial('COM11',115200)
y= "\n" #(ctrl-x)
cnc_ard.write(y.encode())

Here is what I did with Python. Open cmd from there just press ctrl + x. It will come there^X. After entering it will show there . From there copy this inside note+. It will come there "CAN" like this. Copy that and enter this in Serial monitor. Please check these pictures attached below.

A: in python the comand 0x18 is b'\x18'


text:
Q: What is the name of this font type? I like the font used in this paper, but don't know its name.
https://www.nber.org/system/files/working_papers/w25136/w25136.pdf
Can someone tell me (1) what is the name of the main font used in the paper, and (2) what is the name of the math font?
Thanks so much.
Cheers

A: Font in the top (Cover and Abstract) is Times New Roman.

and the rest is URW Palladio, check this page on Font Catalogue for details on setting it up.

A: The document seems to have been typeset with \usepackage[sc]{mathpazo} and \usepackage{eurosym}. The key to see this is to notice PazoMath and URWPalladio in the list below.
If I run pdffonts on the mentioned PDF file, I get
name                                 type              encoding         emb sub uni object ID
------------------------------------ ----------------- ---------------- --- --- --- ---------
Times-Roman                          Type 1            Custom           no  no  no     812  0
GOANIB+TimesNewRomanPSMT             CID TrueType      Identity-H       yes yes yes   1447  0
Times-Roman                          Type 1            Custom           no  no  no     814  0
Times-Bold                           Type 1            Custom           no  no  no     813  0
TIAHIJ+URWPalladioL-Roma             Type 1            Custom           yes yes no     827  0
YMHWWR+TeXPalladioL-SC               Type 1            Custom           yes yes no     833  0
TFCFSM+URWPalladioL-Ital             Type 1            Custom           yes yes no     817  0
CWFANG+URWPalladioL-Bold             Type 1            Custom           yes yes no     830  0
EZZFBZ+CMR10                         Type 1            Builtin          yes yes no     838  0
RMTBLR+CMSY10                        Type 1            Builtin          yes yes no     822  0
PZJBPW+PazoMath-Italic               Type 1            Builtin          yes yes no     840  0
YXAIJA+CMEX10                        Type 1            Builtin          yes yes no     845  0
IKXQUG+PazoMath                      Type 1            Builtin          yes yes no     847  0
SYFPBV+CMMI10                        Type 1            Builtin          yes yes no     856  0
PMAHJP+Cambria                       CID TrueType      Identity-H       yes yes yes    242  0
PMAHJP+Cambria                       CID TrueType      Identity-H       yes yes yes    246  0
PMAJIE+Cambria-Bold                  CID TrueType      Identity-H       yes yes yes    248  0
PMAJJF+Cambria-Bold                  TrueType          WinAnsi          yes yes no     249  0
PMAHJP+Cambria                       CID TrueType      Identity-H       yes yes yes    284  0
PMAHJP+Cambria                       CID TrueType      Identity-H       yes yes yes    291  0
PMAJIE+Cambria-Bold                  CID TrueType      Identity-H       yes yes yes    293  0
PMAJJF+Cambria-Bold                  TrueType          WinAnsi          yes yes no     294  0
KCXMNX+TeX-feymr10                   Type 1            Builtin          yes yes no     870  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    350  0
AOXMDY+Arial                         CID TrueType      Identity-H       yes yes yes    353  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    382  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    386  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    408  0
FASWVE+Arial                         CID TrueType      Identity-H       yes yes yes    411  0
Verdana                              TrueType          WinAnsi          no  no  yes    414  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    423  0
DXCAMN+ArialMT                       CID TrueType      Identity-H       yes yes yes    431  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    471  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    484  0
IQGWEN+Arial                         CID TrueType      Identity-H       yes yes yes    487  0
ArialMT                              TrueType          WinAnsi          no  no  yes    509  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    513  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    531  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    535  0
Helvetica                            Type 1            Custom           no  no  no     547  0
Helvetica                            Type 1            Custom           no  no  no     550  0
CHNQZQ+URWPalladioL-BoldItal         Type 1            Custom           yes yes no     885  0
HUQVCB+CMBX10                        Type 1            Builtin          yes yes no     886  0
QRESJF+CMBSY10                       Type 1            Builtin          yes yes no     887  0
TIQFNQ+PazoMath-BoldItalic           Type 1            Builtin          yes yes no     888  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    582  0
OSSDMB+Calibri-Bold                  TrueType          WinAnsi          yes yes yes    594  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    685  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    699  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    703  0
GWHDZV+CMTI10                        Type 1            Custom           yes yes no     715  0
EZZFBZ+CMR10                         Type 1            Custom           yes yes no     719  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    729  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    733  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    745  0
GJOTKG+ArialMT                       CID TrueType      Identity-H       yes yes yes    748  0
ANVQNS+Arial                         CID TrueType      Identity-H       yes yes yes    751  0
XYHASJ+Arial                         CID TrueType      Identity-H       yes yes yes    754  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    762  0
PGLCUZ+ArialMT                       CID TrueType      Identity-H       yes yes yes    765  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    769  0
YAAJCC+ArialMT                       CID TrueType      Identity-H       yes yes yes    772  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    776  0
MLAILV+ArialMT                       CID TrueType      Identity-H       yes yes yes    779  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    783  0
DVICKR+ArialMT                       CID TrueType      Identity-H       yes yes yes    786  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    792  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    798  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    806  0
HPDFAA+ArialMT                       CID TrueType      Identity-H       yes yes yes    810  0

Times, Helvetica, Calibri, Verdana, Cambria and Arial are from the embedded images and the initial pages (that has Times in some variation). There are also Computer Modern fonts, probably due to embedded images as well.
The feymr10 font is the Euro symbol from the package eurosym.


text:
Q: Почему из-за GradientFill программа не компилируется? Когда я компилирую такой примитивный код, который просто рисует градиент, компилятор выдаёт ошибку:

неразрешённых внешних элементов: 1
ссылка на неразрешённый внешний символ __imp_GradientFill

Насколько я понял, он пытается вызвать несуществующую функцию __imp_GradientFill.
Код:
#include <windows.h>

int main() {
    TRIVERTEX vrts[2];
    vrts[0].x = 0;
    vrts[0].y = 0;
    vrts[0].Red = 0x8000;
    vrts[0].Green = 0;
    vrts[0].Blue = 0;

    vrts[1].x = 100;
    vrts[0].y = 100;
    vrts[1].Red = 0x8000;
    vrts[1].Green = 0;
    vrts[1].Blue = 0;

    GRADIENT_RECT rct;
    rct.UpperLeft = 0;
    rct.LowerRight = 1;

    HWND wnd;
    HDC dc;
    wnd = GetConsoleWindow();
    dc = GetDC(wnd);

    GradientFill(dc, vrts, 2, &rct, 1, GRADIENT_FILL_RECT_H);

    ReleaseDC(wnd, dc);

    return 0;
}


text:
Q: Como provocar um erro XMLHttpRequest? Eu gostaria de entender em que casos o readyState vai ser igual a 4 e o status vai ser diferente de 200 e a diferença disso para o evento onerror:
xhr.onload = function (e) {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
        } else {
            console.error(xhr.statusText);
        }
    }
}
xhr.onerror = function (e) {
    console.error(xhr.statusText);
}

A: De acordo com a página da MDN*:

Uma requisição XHR existe um dos seguintes estados:

*

*0 - UNSENT - Um cliente foi criado. Mas o método open()  não foi chamado ainda.

*1 - OPENED - O método open() foi chamado.

*2 - HEADERS_RECEIVED - O método send() foi chamado e os cabeçalhos e status estão disponíveis.

*3 - LOADING - Baixando e responseText contém os dados parciais.

*4 - DONE - Operação concluída.

Ou seja, quando o valor é 0, a requisição do XMLHttpRequest (AJAX) ainda não começou e quando for 4 ela já acabou. Os demais estados representam passos intermediários. Como o seu código só tem interesse em saber o resultado quando este estiver pronto, você tem o if (xhr.readyState === 4).
Já o status é o status HTTP. Os mais comuns são 200 (ok), 404 (página não encontrada), 403 (acesso negado), 500 (erro interno no servidor), entre outros. No seu caso, o 200 indica que deu certo e qualquer outra coisa seria um erro.

* - Adaptado por mim para se adequar ao formato do SOpt.

A: O .onerror só será invocado caso haja erro a nível de rede, do contrário, sempre vai entrar no .onload e ignorar o onerror.
Exemplo:
Suponhamos que estou no site http://meusite.com e possuo um arquivo index.html no diretório raiz.
Se eu tentar chamar xhr.open("GET","index.html",true);:

*

*Irá entrar no onload sem erro, com xhr.status == 200, porque
achou o arquivo normalmente.

Se eu tentar chamar xhr.open("GET","indexxxxx.html",true);:

*

*Irá entrar no onload "com erro" (na verdade não é um erro, mas apenas um retorno de que o arquivo não foi encontrado), com xhr.status == 404, porque
não achou o arquivo.

Se eu tentar chamar xhr.open("GET","http://google.com",true);:

*

*Irá entrar no onerror, pois não é permitido chamar domínio
diferente do atual e a requisição sequer foi enviada.

O readyState são fases da comunicação com o servidor (de 0 a 4), enquanto o status é interpretado pelo navegador (200, 404 etc...)


text:
Q: PDF for the hypergeometric distribution I wish to plot the p.d.f. for the hypergeometric distribution, and I have been using lua combined with pgfplots. However I get an error when I use the density function with the formula for the binomial coefficient.
How can I make compatible these two declarations? (with or without Lua; cf. code below). Thansk a lot in advance!
\documentclass{article}
\usepackage[margin=1cm]{geometry} % just for this example
\usepackage{pgfplots}
\usepackage{fontspec,luacode,luatexbase}
\begin{luacode}
   -- 'mchoose' is patterned after the posting in http://stackoverflow.com/a/15302448.
   function mchoose( n, k )
     if (k == 0 or k == n) then
       return 1
     else
       return (n * mchoose(n - 1, k - 1)) / k
     end
   end

   -- print an arbitrary length integer as formatted string
   function fwrite(z)
      tex.sprint ( string.format("%.0f",z) )
   end

   -- the pdf used for the dist. in lua...
   -- hypergeometric pdf
   --   function hypergeo(n11, n1_, n_1, n)
   --       return math.exp(math.lbinom(n1_, n11) + math.lbinom(n-n1_, n_1-n11) - math.lbinom(n, n_1));
   --   end

\end{luacode}

\newcommand{\mchoose}[2]{%
    \directlua{fwrite ( mchoose (
               "\luatexluaescapestring{#1}",
               "\luatexluaescapestring{#2}" ) )
    }}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
  no markers, domain=-1:10, samples=100,
  axis lines*=left, xlabel=$x$, ylabel=$f(x)$,
  every axis y label/.style={at=(current axis.above origin),anchor=south},
  every axis x label/.style={at=(current axis.right of origin),anchor=west},
  height=5cm, width=12cm,
  enlargelimits=false, clip=false, axis on top,
  ]

\pgfmathdeclarefunction{hyper}{4}{%
  \pgfmathparse{($\mchoose{#3}{#1}$)+($\mchoose{#4-#2}{#3-#1}$)-($\mchoose{#4}{#3}$)}%
% or?
%  \pgfmathparse{(mchoose{#3}{#1})+(mchoose{#4-#2}{#3-#1})-(mchoose{#4}{#3})}%
}

\addplot [very thick,cyan!50!black] {hyper(4, 10, 42, 16)};

\end{axis}
\end{tikzpicture}

\end{document}

A: This function can be declared and evaluated directly in PGFPlots, without the need for lua.
You can declare the function for the binomial coefficient using
declare function={binomcoeff(\n,\k)=\n!/(\k!*(\n-\k)!);}

and then use that in the declaration of the hypergeometric distribution probability mass function:
declare function={
    hypergeompmf(\N,\K,\n,\k)=binomcoeff(\K,\k)*binomcoeff(\N-\K, \n-\k)/binomcoeff(\N,\n);
}

\documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}[
    declare function={binomcoeff(\n,\k)=\n!/(\k!*(\n-\k)!);},
    declare function={
        hypergeompmf(\N,\K,\n,\k)=binomcoeff(\K,\k)*binomcoeff(\N-\K, \n-\k)/binomcoeff(\N,\n);
    }
]
\begin{axis}[
    samples at={0,...,20},
    ycomb,
    yticklabel style={
        /pgf/number format/fixed,
        /pgf/number format/fixed zerofill,
        /pgf/number format/precision=2
    },
    every axis legend/.append style={at={(0.5,1.1)}, anchor=south}
]
\addplot [mark=*, cyan] {hypergeompmf(80,25,20,x)}; \addlegendentry{$N=80, K=30, n=25$}
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Chartjs barchart generate data for an array dataset I want to generate some Datasets for my Barchart but i dont know why its always displayed 'statement expected' at the round bracket before the return.
function generateDataSets() {
    const returnValue = Array.from(new Array(5){
        return {
            name: 'Land',
            people: 200,
            backgroundColor: ["#3e95cd"]
        };
    })
    return returnValue;
}

A: Not sure what data you're trying to generate but if you want to use the method Array.from(), your code could look as follows:

function generateDataSets() {
  return Array.from(new Array(5), (o, i) => ({
    name: 'Land',
    people: (i + 1) * 100,
    backgroundColor: ["#3e95cd"]
  }));
}

console.log(generateDataSets());


text:
Q: Error while running app android studio So, every time I try to run my app this error appears:

Transform output file
  C:\Users\asus\AppData\Local\Android\sdk\build-tools\27.0.3\renderscript\lib\renderscript-v8.jar
  does not exist.

And the app won't start in the android emulator. I already tried to clean my project and rebuild it too, but it doesn't seem to work


text:
Q: IIS session ends when external process run from ASP.NET I have problem during running external process from ASP.NET application.
The process is run as follows:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public static WebResult generateSomething(string language)
{
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.UseShellExecute = false;
            psi.RedirectStandardError = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.CreateNoWindow = true;
            psi.ErrorDialog = false;
            psi.WorkingDirectory = Environment.CurrentDirectory;
            psi.FileName = String.Format("\"{0}\"", Path.Combine(appDir, Properties.Settings.Default.PATH_TO_APP_TEXT));
            psi.Arguments = arguments.ToString();

            modeller.log.Info("Arguments: " + psi.Arguments);

            var outputText = new StringBuilder();
            int exitCode;

            var result = new WebResult();

            using (Process process = new Process())
            {
                process.StartInfo = psi;
                process.OutputDataReceived += (sendingProcess, args) => { outputText.Append(args.Data); };
                process.ErrorDataReceived += (sendingProcess, args) => { outputText.Append(args.Data); };
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                exitCode = process.ExitCode;
            }

            string outText = outputText.ToString();

Immediately after process finishes (succesfully or not) and the method leaves ASP.NET IIS session is ended, so any authentication context via cookie breaks.
Can anyone help with this issue?
Thanks in advance


text:
Q: What is GAFM and GAFS in intel_gpu_top? I've gone through every PDF on 01 - Intel graphics for linux. I've Googled, DuckDuckGo'ed, and I have even Binged! But I cannot find any information regarding the acronyms at all.
Is there anyone out there who knows what they mean?


text:
Q: How to identify the distribution of my data in Python? I have 20 measured data (actual test data).
And I would like to fine best distribution fitting for my data.
But I have some difficulties in python codling.
Here is my code. Please give me some advice to fix python code.
import numpy as np
from distfit import distfit
dist = distfit(todf=True)
X = [0.024683122, 0.242804512, 0.293910638, 0.298939727, 0.46083702, 1.068388009, 3.175447843, 4.165901528, 4.622206391, 5.030523381, 5.608041988, 5.672603047, 7.269741854, 7.537728098, 7.706391921, 13.64390375, 22.3135421, 25.48884842, 40.6591376, 51.45319478]
result = dist.fit_transform(X)

I am trying to find my data's best distribution fitting (ex. normal, lognormal, gamma, beta...)


text:
Q: HashTable to JTable? I have a HashTable like
HashTable<String, String> table=new HashTable<String, String>();
table.put("1","ABC");
.......continues

Now with enumeration I can get this key and values in two strings say str1 and str2.
I want to add this two string values in a JTable. Every time a new value will iterate and will add in the JTable. How to do this ?
Remember I have no option to use a HashMap.

A: You can use this:
DefaultTableModel dtm = new DefaultTableModel();
JTable table = new JTable(dtm);
for(Entry<?, ?> entry: yourHashTable.entrySet()) {
   dtm.addRow(new Object[] {entry.getKey(), entry.getValue()});
}


text:
Q: Producing wrong XML output Attached are two screen shots, and my code. I am trying to get the animation_sequence as a closing and ending bracket, I've tried my best but now I seek your help. Please help. The code I have produces it as a
Code:
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document testDoc = builder.parse(new File("./data/sprite_types/" + spriteName + "/" + spriteName + ".xml"));
        Element state = testDoc.createElement("state");
        state.setTextContent(element);
        Element animationState = testDoc.createElement("animation_state");
        Element sequence = testDoc.createElement("animation_sequence");
        testDoc.getElementsByTagName("animations_list").item(0).appendChild(animationState).appendChild(state);
        testDoc.getElementsByTagName("animation_state").item(testDoc.getElementsByTagName("state").getLength() - 1).appendChild(sequence);
        DOMSource source = new DOMSource(testDoc);
        PrintStream ps = new PrintStream("./data/sprite_types/" + spriteName + "/" + spriteName + ".xml");
        StreamResult result = new StreamResult(ps);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(source, result);

A: The reason is that you're creating the animation_sequence element but not creating any child node under it. Effectively, you are creating an empty element. Empty elements, when serialized to string, will always appear as <tag/>, rather than <tag></tag>.
To avoid this, you need to add an empty Text node as a child node of the animation_sequence element:
sequence.appendChild(testDoc.createTextNode(""));

(Or, if you use Commons Lang, replace "" with StringUtils.EMPTY)


text:
Q: Extjs3.4 Get all data from grid store which more than 1 page How to get all data from a grid which have more than 1 page?
I set only to display 50 records in a page, but my total data is up to 52 records which store into 2 pages.

May i know how to get all data from this 2 pages?
Below is the code which only can get 1 page data...
ExportButtonTestJS = Ext.extend(One.Report, {
    reportName: 'ExportButtonTestRpt',
    autoExecute: true,
    isDetailPage: false,
    listeners: {
        bbarconfig: function(report, bbarConfig) {
          bbarConfig.items.push({
            xtype: 'button',
            text: 'Export',
            disabled: false,
            onClick : function () {
                console.log(report.grid.getStore().data.items);
                }
          });
        }
    }
});

A: Default page size is 50 for Ext.data.store. So even the data in store is more than 50 records (like for example 400) only 50 records will be stored in a Ext.store at any time. Once we go to next page next records from 51 to 100 records will be stored in store.
Two solutions for your requirement:

*

*Increase pageSize as you want -- Eg: pageSize:500

*Set buffered:true in Ext.data.store

On setting buffered:true, you can get all records of store at a time by using grid.store.getRange(start, end). But in this case you need to load the store once for the first time.

A: Got accross this same problem, this is what i had to do in order to get data from all pages:
var grid = Ext.getCmp('myGrid');

//store current pageSize
var currentPageSize = grid.getBottomToolbar().pageSize;

var store = grid.getStore();     // store from grid

//reload store with total nº of records
store.reload({params:{start:0,limit:store.getTotalCount()}});

//once the grid is reloaded with all records, then do whatever you need.
store.on('load', function(store, recs, opt){

      var selected = store.getRange();  // getRange = get all records

      //this iterates over all records
      Ext.each(selected, function(item) {
           process here;
      }, this);

      //once you finished processing, reload grid with previous pageSize
      store.reload({params:{start:0,limit:currentPageSize}});
}, this, {single: true}); //single:true says this event will only trigger once

Hope this helps anyone, took me some time to get this working.

A: Don't try to access items directly. Use the store methods for that.
Try report.grid.getStore().getRange()
See http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.data.Store-method-getRange


text:
Q: Will using DYLD_INTERPOSE for a C function in one iOS static library interpose it for all other libraries in the bundle? I have a static library objective c with some C functions that I need to modify the behavior of based on the callers. I looked at https://opensource.apple.com/source/dyld/dyld-210.2.3/include/mach-o/dyld-interposing.h and saw that it could be used to essentially "swizzle" C functions.
My question is - will dyld_interpose also interpose the C function in all libraries / frameworks that contain my interposing code?
eg.
Library1 - had C Function
void foo(int bar) {
...
}

Library2 - Has interposing code. Depends on Library1
void my_foo(int bar) {
...
}

DYLD_INTERPOSE(my_foo, foo);

Will Library3 that depends on both Library1 and Library2 be interposed as well? What if it is attached to an application? I've got some success getting it working on an framework.


text:
Q: How do I add a service to an AngularJS app? I'm trying to build a trying to add a service to my Angular app.
But everything breaks when I add Session to the controller:
Error: [ng:areq] Argument 'CustomersCtrl' is not a function, got string

As you might have guessed, I'm just starting to learn Angular. Some start help would be nice. :-)
app/assets/javascripts/angular-app/controllers/customers.js.coffee
angular
  .module('app')
  .controller 'CustomersCtrl', 'helloWorldFromService',
    ($scope, Restangular, helloWorldFromService) ->
      console.log('hello': helloWorldFromService.sayHello())

app/assets/javascripts/angular-app/services/hello.js
angular
  .module('app')
  .service('helloWorldFromService', function() {
    this.sayHello = function() {
    return "Hello, World!"
    };
  });

A: your controller must look like this (with minification)
 .controller('CustomersCtrl', ['$scope','Restangular','helloWorldFromService',
function($scope, Restangular, helloWorldFromService) {
            }
         ]
    );


text:
Q: Read and display the text file contents upon click of button using Javascript On click of a button called result, I want to read and display a text file (which is present in my local drive location say: C:\test.txt) using Javascript function and display the  test.txt file contents in a  HTML text area.
I am new to Javascript,can anyone suggest the code for Javascript function to read and display the contents of .txt file?

A: An Ajax request to a local file will fail for security reasons.
Imagine a website that accesses a file on your computer like you ask, but without letting you know, and sends the content to a hacker. You would not want that, and browser makers took care of that to protect your security!
To read the content of a file located on your hard drive, you would need to have a <input type="file"> and let the user select the file himself. You don't need to upload it. You can do it this way :
<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var result = document.getElementById("result");

  reader.onload = function(event) {
    result.innerHTML = event.target.result;
  };

  reader.readAsText(selectedFile);
}

JS Fiddle

A: Using $.ajax() function: http://api.jquery.com/jQuery.ajax/
$(function(){
    $.ajax({
        url: "pathToYourFile",
        async: false,   // asynchronous request? (synchronous requests are discouraged...)
        cache: false,   // with this, you can force the browser to not make cache of the retrieved data
        dataType: "text",  // jQuery will infer this, but you can set explicitly
        success: function( data, textStatus, jqXHR ) {
            var resourceContent = data; // can be a global variable too...
            // process the content...
        }
    });
});

A: As You've mentionned HTML, I assume you want to do this in a browser; Well the only way to access a local file in a browser is by using the File API, and the file can only be obtained via a user's manipulation such selecting a file in an <input type='file'> element, or drag&dropping a file in your page.

A: We could achieve this by, I should say, creating a virtual file!
Storing the contents of the text file into a Javascript string variable. However, one should consider all new lines and other special symbols\characters and etc.!
We than can markup a script tag in our HTML to load that *.js Javascript like this:

The only difference here is that a text file that could contain:
Goodnight moon
Follow the white rabbit

In a Javascript script string variable should look like this:
var my_virtual_file = "Goodnight moon\nFollow the white rabbit";

Later on, you can access this variable and treat it as you wish...
A programming language like Javascript that follows standards like ECMAScript, gives you a wide range of capabilities to treat and convert data from one type into another.
Once you have your Javascript script loaded, you can then access that variable by any button in your HTML by assigning a function call on its onclick attribute like this:
<button onclick="MyVirtualFile()"></button>

And ofcourse, you just add a script tag to your HTML, like this:

... or your may just create and import another Javascript script containing that same function, under your desire.
If you are concerned about how much information you can store into a Javascript string variable, just take a look at this interesting (and old as this one :D) SO thread.
Lets see if this snippet works :):

var my_virtual_file = "Goodnight moon\nFollow the white rabbit"

function MyVirtualFile(){
    alert(my_virtual_file);
    // Do anything else with your virtual file
};
<!DOCTYPE html>

HTML Javascript virtual file

  <button onclick="MyVirtualFile()">Alert my_virtual_file</button>

You can programatically access and dynamically change the contents of your Javascript script, but you should remind that you need to reload your HTML so the browser can load the new contents.
On your filesystem, you can just treat this *.js as a *.txt file, and just change its contents keeping in mind the Javacript.


text:
Q: The specified UUID is not allowed for this operation I am developing an IOS Application for our Bluetooth Low Energy device, and I am running into a problem whereas i am unable to write to a certain characteristic (that is set to require authenticated write and authenticated read) on a BGM111.
The problem i am experiencing happens in the following order:

First Run:
          1.) Connect to device
          2.) Write a "secret" code to the device, causing it to enable bonding mode
          3.) Read the characteristic that is set to Authenticated Read, forcing the IOS App to request to pair with it (user presses Allow
  Pair)
          4.) Write the desired value to the characteristic, which works on this run   Second Run and beyond (any time after closing the
  application, and re-opening it):
          1.) Connect to device
          2.) Write "secret" code again, to ensure this is still a valid device, (again causing enabling of bonding mode)
          3.) Read the characteristic again (works)
          4.) Write the desired value to the characteristic, which this time gives the error of "The specified UUID is not allowed for this
  operation." which has an error code value of 8

Why am I getting this issue?

A: BGM111 can connect with multiple device ?
Please change device once and connnect again
i think same device will connect will give same udid it is already there so it's making issue


text:
Q: Assigning function that returns a reference to non-reference type I've encountered something I hadn't seen before and am trying to make sense of it.
If I have a function that returns an reference to something, it seems that when I call that function, I can assign the returned reference to a variable declared as a reference to the type, or a variable declared as the type itself, and nothing changes.
Here is a basic example that demonstrates what I'm talking about:
int size = 150;
std::vector<int> v1(size);

void init(){
   for(int i = 0; i < size; ++i){
       v1[i] = i;
   }
}

std::vector<int>& foo(){
   return v1;
}

int main(){
   init();
   std::vector<int> v2 = foo();
   std::vector<int>& v3 = foo();

   for(int i = 0; i < size; ++i){
     std::cout<<v2[i]<<" ";
   }
   std::cout<<"\n";
   for(int i = 0; i < size; ++i){
     std::cout<<v3[i]<<" ";
   }
   std::cout<<"\n";
   return 0;
}

Can someone explain to me exactly how it is that v2 and v3 can both be assigned with the same function?
I'm embarrassed to say that I honestly would have thought that one of these wouldn't even compile. I've noted that changing v3 also changes the contents of v1, but changing v2 does nothing to v1, so it makes sense to me when one would be preferable to the other. However, I'm having difficulty reconciling the fact that both assignments work.
What's going on here?

A:    std::vector<int> v2 = foo();
   std::vector<int>& v3 = foo();

v2 is copy of v1 (new memory locations) while v3 is a reference to v1 (same memory locations)
What this means is that the address of v1 (&v1) and the address of v2 (&v2) are NOT the same.
However the &v1 == &v3
Therefore, when making changes to the elements of v2, then v1 will NOT be changed.
But, making changes to elements of v3 WILL change v1.
WHY?? Because they both "point" to the same location in memory.


text:
Q: How do I get this button underneath between my two NumberPickers? Right now I have two NumberPickers and a Start button, my XML is set up like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.skytbest.intervaltrainer.MainActivity">
<TextView
    android:id="@+id/timer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentTop="true"
    android:text="Label"
    android:paddingBottom="50dp"
    android:paddingTop="50dp"
    android:textSize="50dp"
    />

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@id/timer">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/numberPickers">

        <NumberPicker
            android:id="@+id/numberPicker1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <NumberPicker
            android:id="@+id/numberPicker2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/start"
        android:layout_below="@id/numberPickers"
    />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textView"
        android:text="@string/colon" />
</RelativeLayout>

And it looks like this:

How can I get my Start button to be directly below the two NumberPickers and span the width of the NumberPickers?
If you're wondering about the TextView it is a ":" that you can't really see right now since the Button is offsetting my NumberPickers, but it is in a different layout so that it can be layered over the NumberPickers without spreading them apart. It looks like a clock when it is centered.

A: I would start by making the root layout a RelativeLayout then using android:layout_below for your Button. Something like this should get you close
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@id/timer">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ll">

    <NumberPicker
        android:id="@+id/numberPicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <NumberPicker
        android:id="@+id/numberPicker2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>
<Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/start"
        android:layout_below="@id/ll" // id of your LinearLayout
        />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/textView"
    android:text=":" />
</RelativeLayout>

It wasn't sure where you wanted your TextView so I left it alone.


text:
Q: Finding all posts of a unique identifer using BeautifulSoup and python I wanted to do something very simple, basically scraping the forum titles of a forum. The problem I ran into is that these forum thread names are identified by a unique "id" tag which is unique.
import requests
from bs4 import BeautifulSoup
threads = requests.get('url', headers=headers)
soup = BeautifulSoup(threads1)
results = soup.findAll("a", href=True, id=True)

This leaves me with a large non-parsed chunk of information. Alot.
However this is the part I truly want to extract:

title of thread - bla bla bla

The problem as you can see is that every single thread_title_000000
has a unique number after it. So I can't isolate it using class or tag statements?
I was thinking I could make a loop with a number range that would go through all the ids' with a unique number, however I don't know how.
It feels ineffective of continuously minimizing the html code chunk if my objective extraction is identified by a unique id.


text:
Q: align image on left text in line on right I have code and it outputs the image and text that I require. The problem is I have tried all the css styles I can to try and get it to output the image on the left and text in line on the right. Can anybody help me please it seems the when it is outputted the alertblock and $service->serviceName  seemed to be outputting together rather than individual.
template.php
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title><?php echo $title; ?></title>
        <link rel="stylesheet" type="text/css" href="Styles/Stylesheet.css" />

All rights reserved

index.php

        <meta charset="UTF-8">

        <title></title>

<?php
include 'Template.php';
?>

test.php
<?php

//$emails = imap_search($inbox, 'ALL');
$emails = imap_sort($inbox, SORTARRIVAL,1);

$output = '';

$jsonfile = file_get_contents("test.json");
$decoded = json_decode($jsonfile);

//print_r($jsonfile);

foreach ($decoded as $service) {

//print_r($service);

 echo "
id."Service>";
        echo  $service->serviceName;

    foreach ($emails as $mail) {
        $looptimes =0;
        $headerInfo = imap_headerinfo($inbox, $mail);

        //$output .= $headerInfo->subject . '
';
        //print_r($headerInfo->subject);

    if ($headerInfo->subject == $service->downSubject) {
        // prints out image
        echo '','
','
';

        break;

    }elseif ($headerInfo->subject == $service->upSubject) {
        echo'','
','
';
        break;
    }
    else
    {
        $looptimes++;
    }
}

sendrequest.js
function sendRequest()
{
$("#alertblock").load("php/test.php", function () {
$(this).unwrap();
});
}

A: Its pretty hard to understand what your code is doing by how you set it up and it's not clear what you are trying to achieve. Could you post the HTML you get inside the browser without the PHP so people can see the problem?
What is echo'ed first comes on the left side. Are you echo'ing the image first and then the text?
Example:

  text first, before image

  text after image


text:
Q: importing putty connections from old registry- load hive disabled How do I import putty connections from an old registry? The old hard drive is USB connected.
The option "load hive" is disabled in Regedit.
What are my options?
Operating system:Windows Seven
I got a new HD and installed WIN7 on the new one. The old HD(had WIn7 installed) boots to BSOD. Blue screen of death. The old HD is with me for limited time, so what files related to putty do I need to copy to the new HD?
THanks

A: As detailed in this article Load Hive... is only enabled when HKEY_USERS or HKEY_LOCAL_MACHINE is selected. Once you have loaded the old hive you can locate the PuTTY settings and export them (and import them again after fixing the key names in the exported file).
Usually you don't have to copy anything else to have PuTTY work as before. If you've created any keys (with Pageant) you might want to copy these to your new disk.


text:
Q: Java 8 Streams, example that not compile My question is short, why does it not compile?
final ArrayList <Integer> list = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());

The problem occurs in Collectors.toList() part.

A: Collectors.toList() returns some List implementation that doesn't have to be ArrayList, and probably isn't.
Try
final List <Integer> list = IntStream.rangeClosed(1, 20)
                                     .boxed()
                                     .collect(Collectors.toList());

You can use collect(Collectors.toCollection(ArrayList::new)) if you specifically need an ArrayList.
final ArrayList <Integer> list = IntStream.rangeClosed(1, 20)
                                          .boxed()
                                          .collect(Collectors.toCollection(ArrayList::new));


text:
Q: Ubuntu sometimes immediately shuts down when power button is pressed (but only sometimes) I'm running Ubuntu 13.10 on my Lenovo Y500 laptop, and I'm getting strange behavior surrounding the power button. The series of events goes something like this:

*

*I turn on my computer and enter Ubuntu (I am dual-booting with Windows 8.1 using rEFInd, by the way)

*I press the power button on my laptop, which brings up a small gui menu on Ubuntu, allowing me to choose from several shut-down-related options. I hibernate the computer, using the gui.

*I turn my computer back on and re-enter Ubuntu.

*I press the power button. The gui menu from before briefly flashes before the computer abruptly enters a shutdown sequence without any further action on my part. It's as if it immediately assumed I had clicked on the option for 'shutdown'.
This exact series is basically how it goes every time; that is, Ubuntu will display me the menu if I'm running from a cold boot, but not if I restarted from a hibernation. How can I get this gui to come up (and stay up without it choosing for me) every time?
Additional information: I get an apport error message dialog that shows up every time I reboot after the computer immediately turning itself off.


text:
Q: GridView convert 'Y' or 'N' into checkbox.checked on ItemTemplate field I have a GridView below that will show some text and provide a checkbox.
    <asp:GridView ID="surveyTableTest" runat="server" AutoGenerateColumns="false" >
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:HiddenField ID="hdnSurveyID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "survey_id") %>' />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="URL">
                <ItemTemplate>
                    <asp:Label ID="surveyURL" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "URL") %>' />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Used">
                <ItemTemplate>
                    <asp:CheckBox ID="surveyUsed" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

I have a simple class which is bound to the GridView. This is populated from a SQL stored procedure.
    public class surveyURL
    {
        public int survey_id { get; set; }
        public string URL { get; set; }
        public string used { get; set; }
    }

How can I take the information from 'used' which is NCHAR(1) 'Y' or 'N' and turn that into a checkbox.checked result where 'used' = 'Y'
This is what I am currently doing in C#, this is enough to populate the hiddenfield and first template field. I don't know how to proceed for the checkbox.
    var test = cn.Query<surveyURL>("sp_create_url", p, commandType: CommandType.StoredProcedure);

    surveyTableTest.DataSource = test;
    surveyTableTest.DataBind();

A: You can use the Checked property of CheckBox control and use the C# Conditional operator like this:-
<asp:CheckBox ID="surveyUsed" runat="server"
              Checked='<%# Eval("used").ToString() == "Y" ? true: false %>' />


text:
Q: Android Studio Emulator crashing when trying to run multi-class project I have a multi class project. This is the assignment: Create an app that allows to enter information to order package delivery.  I have to have the two additional classes, and pass the information from one to the other, but I'm not sure why the app is wanting to crash to even see if the code will work.  My instructor has looked at it without much luck, but he's so busy I decided to see if others could take a peek at it. Thanks in advance!
The MainActivity.Java

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    parcel parcelObject;
    address addressObject;
    EditText startAdd;
    EditText startZip;
    EditText endAdd;
    EditText endZip;
    EditText parcelWeight;
    Button button;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        //addressObject = new address(this);
        parcelObject = new parcel(this);

    }
    public void buttonOnClick(View v ) {
        Button button=(Button) v;
        TextView textView = (TextView) findViewById(R.id.shippingTotal);
        parcelObject.shipping();
        textView.setText("Your Shipping Total is: $ " + parcelObject.sCost);
    }
   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

address.java

import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
 * Created by Cyn on 10/16/2015.
 */
public class address {
    parcel parcelObject;
    EditText startAdd;
    EditText startZip;
    EditText endAdd;
    EditText endZip;

    double sZip, eZip;

    public  address (Activity activity) {
       startAdd = (EditText)activity.findViewById(R.id.originZip);
        startZip = (EditText)activity.findViewById(R.id.originZip);
        endAdd = (EditText)activity.findViewById(R.id.destAdd);
        endZip = (EditText)activity.findViewById(R.id.destZip);

        sZip = Double.parseDouble(startZip.getText().toString());
        eZip = Double.parseDouble(endAdd.getText().toString());
    }

}

and the parcel.java

import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Created by Cyn on 10/16/2015.
 */
public class parcel {
    address addressObject;
    EditText startAdd;
    EditText startZip;
    EditText endAdd;
    EditText endZip;
    EditText parcelWeight;

    double sZip, eZip, pWeight, sCost;

    public parcel(Activity activity) {
        addressObject = new address(activity);
        startAdd = addressObject.startAdd;
       endAdd = addressObject.endAdd;
        endZip = addressObject.endZip;
        sZip = addressObject.sZip;
        eZip = addressObject.eZip;

        parcelWeight = (EditText)activity.findViewById(R.id.packageWeight);
        pWeight = Double.parseDouble(parcelWeight.getText().toString());

    }

    public void shipping() {

        if (sZip == eZip) {
            sCost = pWeight * 1;
        } else {
            sCost = pWeight * 2;
        }

    }
}

And the where the error parts of the android monitor are:

11-20 01:27:53.768 1444-1444/cyn.assignment4 D/AndroidRuntime: Shutting down VM
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime: FATAL EXCEPTION: main
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime: Process: cyn.assignment4, PID: 1444
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{cyn.assignment4/cyn.assignment4.MainActivity}: java.lang.NumberFormatException: Invalid double: ""
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread.-wrap11(ActivityThread.java)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:  Caused by: java.lang.NumberFormatException: Invalid double: ""
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at java.lang.StringToReal.invalidReal(StringToReal.java:63)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at java.lang.StringToReal.parseDouble(StringToReal.java:267)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at java.lang.Double.parseDouble(Double.java:301)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at cyn.assignment4.address.<init>(address.java:33)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at cyn.assignment4.parcel.<init>(parcel.java:22)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at cyn.assignment4.MainActivity.onCreate(MainActivity.java:35)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:6237)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread.-wrap11(ActivityThread.java)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-20 01:27:53.772 1444-1444/cyn.assignment4 E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-20 01:28:36.701 1444-1451/cyn.assignment4 W/art: Suspending all threads took: 135.053ms
11-20 01:30:38.025 1444-1451/cyn.assignment4 W/art: Suspending all threads took: 218.758ms
11-20 01:31:17.505 1444-1444/cyn.assignment4 I/Process: Sending signal. PID: 1444 SIG: 9

A: sZip = Double.parseDouble(startZip.getText().toString());
eZip = Double.parseDouble(endAdd.getText().toString());

Here is it. You are trying to parse double from a String, and the String is empty. Check it first with
if(!startZip.getText().toString().isEmpty&& startZip.getText()!=null){
    sZip = Double.parseDouble(startZip.getText().toString());
}
if(!endAdd.getText().toString().isEmpty&&endAdd.getText()!=null)...

A: Though the answers were partially right, two small changes made the code work. One being a simple typo fix (that I didn't catch).
First, a change in the main activity: Where we moved the "parcelObject = new parcel (this);   from the onCreate, to the top of the buttonOnClick

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        //addressObject = new address(this);

    }
    public void buttonOnClick(View v ) {
        parcelObject = new parcel(this);
        Button button=(Button) v;
        TextView textView = (TextView) findViewById(R.id.shippingTotal);
        parcelObject.shipping();
        textView.setText("Your Shipping Total is: $ " + parcelObject.sCost);
    }

Then the small typo was with:

sZip = Double.parseDouble(startZip.getText().toString());
eZip = Double.parseDouble(endAdd.getText().toString())

it should be:

sZip = Double.parseDouble(startZip.getText().toString());
eZip = Double.parseDouble(endZip.getText().toString())

"endAdd" verse "endZip" , what must have happened was that I probably clicked the wrong auto fill.
but to snazz up the code a bit more , this is the final address.java code:

package cyn.assignment4;

import android.text.TextUtils;
import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
 * Created by Cyn on 10/16/2015.
 */
public class address {
    parcel parcelObject;
    EditText startAdd;
    EditText startZip;
    EditText endAdd;
    EditText endZip;

    double sZip, eZip;

    public  address (Activity activity) {
       startAdd = (EditText)activity.findViewById(R.id.originZip);
        startZip = (EditText)activity.findViewById(R.id.originZip);
        endAdd = (EditText)activity.findViewById(R.id.destAdd);
        endZip = (EditText)activity.findViewById(R.id.destZip);

        String checkUserInput =  startZip.getText().toString();
        if (TextUtils.isEmpty(checkUserInput)) {
            startZip.setError("You must enter a valid zip code");
        }
        else {
            sZip = Double.parseDouble(startZip.getText().toString());

        }

        String checkUserInput2 =  endZip.getText().toString();
        if (TextUtils.isEmpty(checkUserInput2)) {
            endZip.setError("You must enter a valid zip code!");
        }
        else {
            eZip = Double.parseDouble(endZip.getText().toString());
        }

    }

So that with the small movement chance in the main activity and the app works like a charm :).


text:
Q: Unauthorized interaction with google calendar API v3 I'm in the same situation as this guy (only that my problem is with python): I'm trying to retrieve data using a service account (using this example and after reading this blog entry since my application is a google app) but I get hit with a login required error and I cannot understand why.
Let me represent it with a whole example:
In [1]: import httplib2
In [2]: from apiclient.discovery import build
In [3]: from oauth2client.client import SignedJwtAssertionCredentials
In [4]: f = open('abd45679ffg32343-privatekey.p12', 'rb')
In [5]: key = f.read()
In [6]: f.close()
In [7]: credentials = SignedJwtAssertionCredentials(
        '2127313127654990@developer.gserviceaccount.com', key,
        scope=['https://www.googleapis.com/auth/calendar',
               'https://www.googleapis.com/auth/calendar.readonly'])
In [8]: http = httplib2.Http()
In [9]: http = credentials.authorize(http)
In [10]: service = build(serviceName='calendar', version='v3', http=http,
   ....:         developerKey='XcddfRgtyt676grggtT')
2012-05-14 18:24:35,170 INFO  [root][MainThread] URL being requested: https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest
2012-05-14 18:24:35,170 INFO  [oauth2client.client][MainThread] Attempting refresh to obtain initial access_token
2012-05-14 18:24:35,179 INFO  [oauth2client.client][MainThread] Refresing access_token
In [11]: service.calendarList().list().execute()
2012-05-14 18:25:00,418 INFO  [root][MainThread] URL being requested https://www.googleapis.com/calendar/v3/users/me/calendarList?alt=json&key=XcddfRgtyt676grggtT
---------------------------------------------------------------------------
HttpError                                 Traceback (most recent call last)
/home/mariano/Code/Kalendar/rest/kalendar/<ipython-input-12-0cb769615d74> in <module>()
----> 1 service.calendarList().list().execute()
/home/mariano/Code/Kalendar/rest/env/local/lib/python2.7/site-packages/google_api_python_client-1.0beta8-py2.7.egg/apiclient/http.pyc in execute(self, http)
387
388       if resp.status >= 300:
--> 389         raise HttpError(resp, content, self.uri)
390     return self.postproc(resp, content)
391
HttpError: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/users/me/calendarList?alt=json&key=XcddfRgtyt676grggtT returned "The user must be signed up for Google Calendar.">

Any pointers about why is this happening and how to solve it would be greatly appreciate.

A: Service Accounts are available and work with Calendar API for me.
You need to change your following statement:
credentials = SignedJwtAssertionCredentials('2127313127654990@developer.gserviceaccount.com', key, scope=['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly'])

to
credentials = SignedJwtAssertionCredentials('2127313127654990@developer.gserviceaccount.com', key, scope=['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly'], prn='requestor@domain.com')

A: The service accounts do work with the Calendar API. You have to also grant access on your domain management as well.
Do as user1260486 and btspierre said, and add the "prn=requestor@domain.com" to the constructor for SignedJWTAssertionCredentials.
Then go to your domain management and add your client_id access to the API.
Here's a walkthrough about it.
For the scope specify "https://www.googleapis.com/auth/calendar, https://www.googleapis.com/auth/calendar.readonly"

A: I don't think service accounts are available for Calendar API. The service account has no calendar of its own.


text:
Q: Cannot get directories from source I need your help to solve this small issue. I gave a source path such as "\version\test" in my c# project. But when I run it, i want to get folders from source but i got error because source path is incorrect due to \bin\debug\version\test. I only need to read folders from project's path not debug. How to solve this problem? Your advice much appreciated. thanks

A: You are using a relative path, and the working directory when you run your application is \bin\debug.
So you should either set the working directory to the project directory in the debug properties of the project, or use a different relative path, such as ..\..\version\test

A: If your application is winforms application then it is:
Application.StartupPath
If your application is WPF application then please see below link:
Getting the application's directory from a WPF application

A: If you want to get path use following code sample:
string path =new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName;

This will give you current solution folder path.