How to exit from while loop during Pyserial Xbee communication?

Question: As a part of  my project I am sending bytes over one xbee to another . I have Python code that works fine , except one thing.
In the following receiver code , I have to add some more statements after everything has been received successfully. The problem is , as there is while true condition ( used for continuously receiving packets ) , whatever statements I added after the code will run infinitely. Is there any solution to check " if all packets have received successfully ", exit from while loop and do other statements .
import serial
ser = serial.Serial(port='COM28', baudrate=9600, parity=serial.PARITY_NONE,    stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=0)

c=0
data=[]
msgparts=[]

while True:
  if ser.inWaiting():
     val = ser.readline(ser.inWaiting())
     print val
     print(val)
     fn1="image%s" %c
     c=c+1
     f = open(fn1, 'wb')
     f.write(val)
     print fn1
     f.close()
     msgparts.append(val)

     #### Here I want to add new statements

Answer: I dont know how to check if all message parts are received, but you can use break to break out of loop.
Answer: Instead of
while True:

at the top of the loop, you can start with:
message_complete = False
while not message_complete:

and in the loop have a line, such as:
if val[-1:] == '\n':
    message_complete = True

(If the newline was the end of the message)
Of course, the break statement works here too.
How are you determining message complete?


Is there a way to make a player for iOS which plays IN an HTML document, and NOT fullscreen?

Question: I want to make a player in a website for iOS devices, but I don't want that it plays the video in fullscreen. I want the player that plays it inside the website, making it able to view both the website AND the video.
Witch would look something like this:
Answer: Use the html5 <video> element.
Comment: does that work for all ios devices? Because my iPhone still does full screen.
Comment: My understanding is that the iPhone will always play full screen but the iPad will let you play as you'd like
Comment: yea I found it out, thanks for your answer It's a pity though that iPhone can only play fullscreen


Get productID of the product being edited in Magento

Question: Is there a way, in Magento, to get the productID of the product currently being edited on the Admin backend?
I found this:
Mage::registry('current_product');

but it doesn't seem to get the one being edited.
Edit: If it makes any difference, I'm trying to get it from an extension listening for the event:
catalog_product_gallery_upload_image_after

Answer: The current product's ID is in the URL. You can retrieve it as a parameter like so:
$productId = Mage::app()->getRequest()->getParam('id');

If you want to load the product as an object, store that ID and use
$product = Mage::getModel('catalog/product')->load($productId);

Edit: It looks like you're using an observer. The observer file itself I assume does not extend any part of Magento. (Is this the file? http://svn.magentocommerce.com/source/branches/1.7/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php) Try obtaining the action and getting the request that way
$action = $observer->getAction();
$productId = $action->getRequest()->getParam('id');

Comment: I'm don't think that's working.  This statement:     Mage::log(Mage::app()->getRequest()->getParam('id'));

doesn't print anything

And,   doing a $model->load on it returns a blank product object.
Comment: I have an extension that has an Observer for "catalog_product_gallery_upload_image_after".  The code is in  /Model/Observer.php.
Answer: That should work, as should Mage::registry('product'), as long as it is requested after Mage_Adminhtml_Catalog_ProductController::_initProduct() is called.
Mage::app()->getRequest()->getParam('id') should also work.
Edit based on event
The event being observed is dispatched in response to a JS-originated request. The controller action is unaware of the calling context, and there is no product registered in the registry. Logging the request params or possibly the referrer may give insight.
Comment: I don't think that's working. This statement: Mage::log(Mage::registry('product'));

doesn't print anything
Comment: Updated answer to explain.
Comment: Thanks for the update.  Would it be possible for my module to have two Observers,  one listening for one "further back" that would have the product information, and the current one listening for the image upload?  Could the observer listening further back somehow store the information for the upload listener?
Comment: You are encountering the by-design statelessness of HTTP requests. You could store this in a cookie or in the admin session, both of which seem like overkill. I would resort to this only if I had proven that `$_REQUEST` does not contain identifying information. Beyond this, there is a downstream process which must be triggered by JS which *does* connect this field with its entity.


Area of target board(circular shape)

Question: I know how to find area and circumference of target boards, but I dont know why I am finding one question from new mastering mathematics for Eexcel GCSE syllabus bit weird. As the answer scheme is published by publishers and work out of this question does not match anywhere near to it. I just want to get confirm if I am doing it write.
So here is the question.

When I solve it I get answer 163.35 cm(square) for red area and 157.06 cm(square) for blue area and the difference would be 376.99cm(square).
According to answer scheme the answer is 816.81 cm(square) for red area and 439.82 cm(square) for blue area and the difference would be 6.29.
Comment: How did you solve the question?
Comment: Using the formula for the area of an annulus $\pi(R^2-r^2)$, where $R$ is the radius of the entire figure, and $r$ is the radius of the hole, I got an answer of $732 cm^2$. Can you put a link to the markscheme and post the steps to your answer?
Comment: Hi Toby, kindly accept my apologies for replying late. Here is the link to answer scheme https://www.hoddereducation.co.uk/media/Documents/Maths/Mastering%20Mathematics%20for%20Edexcel/EdexcelGCSEMathsFoundation1_Answers_1.pdf?ext=.pdf and this question answer is on page 186  and question number 5.
Answer: How to solve the question:
The first blue area is calculated using πr²
The first red area is calculated using πr² and then subtracting (the area of the first blue area)
The second blue area is calculated using πr² and then subtracting (the area of the first blue area + the area of the first red area)
The second red area is calculated using πr² and then subtracting (the area of the first blue area + the area of the first red area + the second blue area)
Total blue area = first blue area + second blue area
Total red area = first red area + second red area
Difference = total blue area - total red area
Working out:

First Blue Area: π(5)² = 25π
First Red Area: π(9)² - (25π) = 81π - (25π) = 56π
Second Blue Area: π(14)² - (25π+56π) = 196π - (25π+56π) = 115π
Second Red Area: π(20)² - (25π+56π+115π) = 400π - (25π+56π+115π) = 204π
Total Red Area = 204π + 56π = 260π = 816.814089933 cm²
Total Blue Area = 25π + 115π = 140π = 439.822971503 cm²
Difference between Total Red Area and Total Blue Area=
816.814089933 cm² - 439.822971503 cm² = 376.99111843 cm²

Let me know if you don't understand or need more help.

Area of target board(circular shape)


Trying to assign a custom primary key to a database using values a user enters

Question: I apologise if this has been asked before but cannot find it anywhere but it could be that I am using the wrong terminology. I have a working database and all I am trying to do is create a custom made primary and foreign key using a webform input. So a user will enter their firstname and surname. I want to create a key by combining the two names and add a timestamp (Im thinking this will be nearly impossible for two people using the exact same name, registering at the same date and time). For example Mark Smith registering at 1:00PM 18th August 2017 would return marksmith1808171300 (or something similar to this). This is the code I am using:
<code>$fname=$_POST['fname'];
$sname=$_POST['sname'];

$time=$_SERVER['REQUEST_TIME'];
$userID=$fname+$sname+$time;
</code>
My webform values are sname and fname and these are sending to the database correctly as the firstname and surname. however I am getting a strange serious of numbers and nothing else. This is the number that sent to the database: 1503104412. I done this at 2am 19th August 2017 so it has not returned the date/time. I tried taking out the time and it just returns a 0 as the result so I am assuming I have the syntax wrong. Could someone please show me what I am doing wrong? Also, is there a correct term that is used when referring to doing this?
Comment: string concatanation in php is done with a dot `.`, not a `+`. You are now calculating, adding the integer values.
Comment: @Jeff Thank you so much this has been doing my head in for some time now and worked perfectly. I think I have been working on this so long, It didnt even occur to me to think I was adding. And thank you for letting me know this was called string concatanation!
Answer: `

$today=date("Y/m/d");
$time=date("h:i:sa");
$yourtimestamp = $today."".$time;
$userID = $fname.$sname.$yourtimestamp;
?>`>
Comment: Use it like this so that u can get your time stamp
Comment: $userID = $fname.$sname.$yourtimestamp
Comment: All he have to do is assign it like this for the $userID


output a string then do something and add to the same string

Question: I am trying to write to the console :
Write-Host "Backing up Switch1"

Then run the backup and check if it was successful
Write-Host "Backing up $Building $SwitchName ..."
$initFldrCount =  Get-ChildItem C:\Admin\$SwitchName | Measure-Object | ForEach-Object{$_.Count}
C:\kitty_portable-0.70.0.9.exe -ssh -l Admin -pw Password -cmd $Command $ip
$count++
Start-Sleep 5
$fnlFldrCount = Get-ChildItem C:\Admin\$SwitchName | Measure-Object | ForEach-Object{$_.Count}
#Make sure a backup was made
if (($initFldrCount + 1) -ne $fnlFldrCount){
    $Status = "Failure"
}
else {
    $Status = "Success"
}
Write-Host "===$Status==="

it then outputs
Backing up Switch-1 ...
===Failure===

But I want it to add failure to the end of the Backing up string after the
script
Backing up Switch-1 ...  ===Failure===

How would I go about doing this
Answer: Simply add the -NoNewLine switch to the line
Write-Host "Backing up $Building $SwitchName ..."

as such:
Write-Host "Backing up $Building $SwitchName ..." -NoNewLine


python 3.6 convert string to utc time zone date-time format

Question: I am getting 2 different strings from 2 different sources and I would like to convert these strings to common date-time format in UTC timezone.
The 1st string value is like this : 2017-03-30T13:54:40+0300
and the 2nd string value is like this :  Thu Jul 6 16:57:50 2017 +0530.
I am new to Python and Python 3.6 and it will be great if someone can help me.
Comment: Possible duplicate of [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime)
Comment: @cosinepenguin: I've scanned the question you mention, and the answers, and don't see how this is a duplicate.
Answer: I could solve the problem using first by converting the strings to datetime format ( the formatting was tricky part here) and later by converting the these datetimes to local time zone using astimezone function in datetime module.
Thanks everyone for the help.
@Rohit Poudel, the link shared helped me understand date-times in python better.Can you please check if this is indeed duplicate of the mentioned link and if not , mark as non-duplicate as I am a newbie.
Answer: For the ISO8601 format string (your 1st string) do this:
Install these modules (Linux assumed, and assuming you have pip installed):
$ pip install iso8601 pytz

Then in your Python console:
>>> import datetime, iso8601, pytz
>>> s1 = '2017-03-30T13:54:40+03:00'
>>> s1a = '2017-03-30T13:54:40.123456+03:00'    # with fraction of sec. added
>>> dt1 = iso8601.parse_date(s1)
>>> dt1
datetime.datetime(2017, 3, 30, 13, 54, 40, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800), '+03:00'))
>>> dt1a = iso8601.parse_date(s1a)
>>> dt1a
datetime.datetime(2017, 3, 30, 13, 54, 40, 123456, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800), '+03:00'))

dt1 and dt1a are instances of datetime.datetime.  They are "aware" times bearing your +03:00 timezone offset.
Now convert that into UTC times:
>>> dt1a.astimezone(tz=pytz.utc)
datetime.datetime(2017, 3, 30, 10, 54, 40, 123456, tzinfo=<UTC>)

If you wanted the results in ISO8601 format, do this:
>>> dt1a.astimezone(tz=pytz.utc).isoformat()
'2017-03-30T10:54:40.123456+00:00'

You can see that in the last line, the time is 10:54.40.123456 UTC whereas the original was 13:54:40.123456+03:00.
For your second string, convert it to instances of datetime.datetime then proceed as above.
Comment: Alternatively, without needing pytz, do this:
>>> dt1a.astimezone(tz=datetime.timezone.utc)


How to debug this controller in AngularJS?

Question: I have the HTML as follows:

{{ctrl.serviceInstance.additionalPorts}}

And, the controller is defined as:
function _compareArrays(arr1,arr2){
    if (arr1 === null && arr2 === null)
        return true;
    if (arr1 != null && arr2 != null) {
        arr1.sort();
        arr2.sort();
        var result = arr1.length == arr2.length && arr1.every(function(element, index) {
                return element === arr2[index];
            });
        return result;
    }
    return false;
}

I want to check what values are being passed to the variables arr1 & arr2. The code is getting minified in my browser, and I am unable to access the variables directly in the console of the browser. How can I access these?
Thanks!
Answer: I have been using ng-inspector to get the values of the controller scope and it gives a very good tree represtational view of the same.
Answer:

function _compareArrays(arr1, arr2) {
  console.log('this is arr1' + arr1);
  console.log('this is arr2' + arr2);
  if (arr1 === null && arr2 === null)
    return true;
  if (arr1 != null && arr2 != null) {
    arr1.sort();
    arr2.sort();
    var result = arr1.length == arr2.length && arr1.every(function(element, index) {
      return element === arr2[index];
    });
    return result;
  }
  return false;
}

should be done with console.log statements as written above


how to catch the response array & then set on Listview? how to get response in array form & set on listview in Android?

Question: I already post that problem but nobody provide solution even i edit again my post, so then i delete & post again.
I don't much knows the working of StringRequest Class & its response. please help me by a simple & proper guide.it response a single Jsonobject but not array.
In this json response an array of data I don't knows how to catch that array & then set on Listview
server response
I/System.out:
 {
 "success":true,"first_name":"savha","last_name":"jiii","mobile":2147483647
 }
 W/System.err: org.json.JSONException:
 Value
 {
 "success":true,"first_name":"savha","last_name":"jiii","mobile":2147483647
 }
 of type org.json.JSONObject cannot be converted to JSONArray

Json StringRequest Volley
php code
< ?php

$con=mysqli_connect(XXXXXXXXXXXXXX);

$state=$_POST["state"];

$dist=$_POST["dist"];

$statement=mysqli_prepare($con,"SELECT first_name,last_name,mobile FROM first        WHERE state=? AND dist=?");

mysqli_stmt_bind_param($statement,"ss",$state,$dist);

mysqli_stmt_execute($statement);

mysqli_stmt_store_result($statement);

mysqli_stmt_bind_result($statement,$fname,$lname,$mobile);

$response=array();

$response["success"]=false;

while(mysqli_stmt_fetch($statement))

{

$response["success"]=true;

$response["first_name"]=$fname;

$response["last_name"]=$lname;

$response["mobile"]=$mobile;

}

echo json_encode($response);

?>

ServiceRequest class
public class SevakRequest  extends StringRequest {

private static final String LOGIN_REQUEST_URL="http://XXXXXX.php";
private Map<String ,String> params;

public SevakRequest(String state,String dist, Response.Listener<String> listener)
{
    super(Method.POST,LOGIN_REQUEST_URL,listener,null);
    params=new HashMap<>();
   // params.put("service",service);
    params.put("state",state);
    params.put("dist",dist);
}

@Override
public Map<String, String> getParams() {
    return params;
}
}

MainActivity class
public class SearchResult extends Activity {
Button btn1,btn2;
ListView lv1;
TextView tv1;
String serv, stat, dist;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_result);
    btn1 = (Button) findViewById(R.id.btn1);
    btn2 = (Button) findViewById(R.id.btn2);
    lv1 = (ListView) findViewById(R.id.lv1);
    tv1 = (TextView) findViewById(R.id.tv1);

    Intent in = getIntent();
    serv = in.getStringExtra("key1");
    stat = in.getStringExtra("key2");
    dist = in.getStringExtra("key3");
    tv1.setText(serv + " >> " + stat + " >> " + dist);

  Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");

                if (success) {
                    JSONArray jsonArray = new JSONArray(response);
                    int length = jsonArray.length();
                    List<String> listContents = new ArrayList<String>(length);
                    for (int i = 0; i < length; i++) {
                        String fname = jsonResponse.getString("first_name").toString();
                        String lname = jsonResponse.getString("last_name").toString();
                        String mobile = jsonResponse.getString("mobile").toString();
                        listContents.add("First name: " + fname + "\nLast name: " + lname + "\nMobile: " + mobile);
                    }
                    lv1.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, listContents));

                } else {
                    Toast.makeText(getApplicationContext(), "Error occurred", Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    SevakRequest sevakRequest = new SevakRequest(stat, dist, listener);
    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    queue.add(sevakRequest);
}
}

Comment: post your server response.
Comment: `I/System.out:
 {
 "success":true,"first_name":"savha","last_name":"jiii","mobile":2147483647
 }
 W/System.err: org.json.JSONException:
 Value
 {
 "success":true,"first_name":"savha","last_name":"jiii","mobile":2147483647
 }
 of type org.json.JSONObject cannot be converted to JSONArray`
Comment: response now added in problem
Comment: You are receiving a singel object in the json response. The first part of parsing is correct `JSONObject jsonResponse = new JSONObject(response);` but after this you try again to put this in an array. It seams you are expecting something different from what you are receiving. If I understan your php code right, than there is also a mistake, you are overwriting always the same fields inside your $response array.
Comment: It clearly says your response is JSONObject not JSONArray
Comment: first of all thanks for response , what should i do for make it an array? i also think php need some correction .
Comment: Fusselchen , Piyush
Answer: first of all ensure your json data is the correct one. I guess you want this:

{
  "success": true,
  "data": [{
    "first_name": "savha",
    "last_name": "jiii",
    "mobile": 2147483647
  }, {
    "first_name": "john",
    "last_name": "smith",
    "mobile": 333123456
  }]
}

For now just return a static json file, so you can focus on developing your app.
Than you can change your java code like JSONArray arr = jsonResponse.getJSONArray("data"); to get the array of contact Objects.
Personaly I prefere to use a lib like Gson for easier json en-/decode.


SQL error 150 on table creation

Question: I know the error 150 is related to foreign keys, but i can't figure out what wrong here.
CREATE TABLE IF NOT EXISTS User(

   id_user INT NOT NULL  AUTO_INCREMENT PRIMARY KEY,
   nom VARCHAR(255) NOT NULL,
   prenom VARCHAR(255) NOT NULL,
   naissance DATE NOT NULL,
   email VARCHAR(255) NOT NULL

);

CREATE TABLE IF NOT EXISTS Livre(
   id_livre INT NOT NULL  AUTO_INCREMENT PRIMARY KEY,
   titre VARCHAR(255) NOT NULL,
   parution DATE NOT NULL,
   id_edit INT NOT NULL,
   id_user INT NOT NULL,

   FOREIGN KEY ( id_edit)
   REFERENCES Editeur(id_edit)
   ON DELETE CASCADE,

   FOREIGN KEY ( id_user)
   REFERENCES User(id_user)
   ON DELETE CASCADE

);

CREATE TABLE IF NOT EXISTS Publication(

   id_pub INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
   texte TEXT NOT NULL,
   date_pub DATE NOT NULL,
   titre_pub VARCHAR(255) NOT NULL,
   id_livre INT NOT NULL,
   id_user INT NOT NULL,

   FOREIGN KEY ( id_user)
   REFERENCES User(id_user)
   ON DELETE CASCADE,

   FOREIGN KEY (id_livre)
   REFERENCES Livre(id_livre)
   ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS Editeur(
   id_edit INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
   nom VARCHAR(255) NOT NULL,
   pays VARCHAR(255) NOT NULL,
   adresse VARCHAR(255) NOT NULL,
   tel VARCHAR(255) NOT NULL

);

The error occurs when i try to create tables Livre and Publication.
Types are the same so it doesn't seem to be the problem.
Comment: I would recommend using the SSMS GUI to create tables since it's so easy - but, at the very least, script the tables individually so that your errors are easier to troubleshoot.
Answer: By mindful of the order in which you create the tables.
For instance, your table creation statement for Livre defines a foreign key on Editeur.  But the table Editeur has not been created yet.
Adjust the create table statement ordering as required.

SQL error 150 on table creation


input in C program

Question: I wrote a program to generate monomials and polynomial and print monomials and polynomial. The data are input from keyboard. For example, first input the number of groups of data 3, then input the data: 1,3,2,4,3,6,3,4,2 (each group has 3 elements). I need output monomial Y^{1}{2,3}Y^{4}{3,6}Y^{3}_{4,2}. My program can work. But the output is not correct. I think the problem of the program is in the following part. I think the scanf is not good in the following. Are there other better input method to fix this problem? The whole program is in http://hi.baidu.com/lijr03/blog/item/51e17b0c63614bc863d98629.html
monomial create_monomial(int number) /* create a monomial */
{

   monomial m,s;
   monomial p;
   int i;

   printf("Please input the parameters (for example,  2, 2, 3 denotes the monomial P^{2}_{2,3}). The first subscripts i's of P's should be in increase order.");
   m=(monomial)malloc(sizeof(monomial_node));
   m->head=m->tail=(monomial)malloc(sizeof(monomial_node));

   if(m->head==NULL)
   {
     return NULL;
   }

   m->head->next=m->tail;

   m->tail->next=NULL;

   p=(monomial)malloc(sizeof(monomial_node));

   m->head->next=p;

   p->next=m->tail;

   scanf("%d", &((p->y).l));
   scanf("%d", &((p->y).i));
   scanf("%d", &((p->y).k));

  if(number > 1)
  {
   for(i=0;i<number-1;i++)

   {

    s=(monomial)malloc(sizeof(monomial_node));

    scanf("%d", &((s->y).l));
    scanf("%d", &((s->y).i));
    scanf("%d", &((s->y).k));

    s->next=p->next;     /* insert the node a */

    p->next=s;

    free(s);

   }
  }
   return m;
}

Comment: Don't cast the return value of `malloc`. Casting is, at best, redundant and may hide an error the compiler would have caught without the cast. Also what are `monomial` and `monomial_node`? Are they equivalent types?
Comment: Did you already post this? http://stackoverflow.com/questions/6444537/code-cannot-work
Comment: @pmg, they are not equivalent. They are defined as  typedef struct node /*a node denotes a P_{i,k}^{l}*/

{

 int l,i,k;

} node;

typedef struct monomial_node /* a monomial denotes a monomial P_{i,k}^{l} \cdots P_{i',k'}^{l'} */

{

 node y;

 int coeff;         /* coeff is s(m_r) */

 struct monomial_node *next;

 struct monomial_node *head;

 struct monomial_node *tail;

} monomial_node, *monomial;

Comment: @pmg, they are defined in the link above.
Comment: Ah! typedefs hiding the pointer-ness of the type, ugh! I like to `malloc` simply with the size of the object itself: `p = malloc(sizeof *p);`
Answer: The free(s) means that you are destroying the monomial that you've just created.  The pointer that you create above it (from p) means that you'll be pointing to a potentially invalid bit of memory when you process m.
Comment: @math 123 - As it stands the free is deleting an object that you are still pointing to; the fact you reuse the variable s is not relevant.
Comment: in the loop, I s is assigned memory again by s=(monomial)malloc(sizeof(monomial_node));
Answer: scanf is a fine choice, but it can be a little peculiar.  I think in this case you need a scanf format like "%d,%d,%d".  The best thing to do, however, is write a small simple C program that just inputs the data and experiment with that.  It would look something like
 int main(){
     int x, y, z ;

     scanf("%d,%d,%d", &x, &y, &z);
     printf("%d,%d,%d\n", x,y,z);
     return 0;
 }

Once you have that working, getting the real program to work should be straightforward.
Comment: I know this. But I need many of x1,y1,z1,x2,y2,z2,... They are input by a loop. Then there are some problems.
Answer: Since you haven't shown what the erroneous output is I can only make an educated guess on exactly what the problem might be, but in addition to the incorrect scanf() calls and the call to free that is deleting the additional allocated nodes in your list, you have "empty" nodes for head and tail.  So when you traverse your linked list, you will need to take into account that the head and tail nodes are empty, otherwise you're going to get some odd values for those nodes since they are uninitialized.

input in C program


Standard method for parsing XML documents without downloading a DTD

Question: So, our application parses XML documents retrieved from a web service (specifically PubMed). Those documents declare a DTD (an example). By default, and contrary to my naive expectations, the XML library we use (JDom2, built on Xerces I believe) downloads that DTD before parsing the XML document. Downloads, as in makes an HTTP request over the internet to the address specified.
From reading other posts here, its my understanding that reading the DTD is necessary given that it may contain entity declarations required to parse the &foo bits in the document (BTW, this is insanity in the XML standard, right?)
I thought that there must be some easy, standard, any-one-who-knows-what-they-are-doing-does-this way of specifying that I have the DTD locally. But, all I see is mentions of setting up an XML catalog (black magic), or creating a custom EntityResolver (pain in my ass).
For other problems that I encounter, I find in Spring or some other Java library a standard way of overcoming them without a lot of boiler plate. For this one however, I feel like I'm writing relatively sloppy brittle code to accomplish something that every other developer must encounter.
How do you write XML applications, using well-known libraries, that don't make web requests over-and-over again to fetch files that never change?
PS:
I discovered this problem because PubMed was having connectivity issues earlier today, and my unit tests (that use mocked up documents based on real queries) were failing when the XML parser couldn't retrieve the DTD.
PPS:
I find it really amusing that the W3C has issues with this when they are the ones that propagated a standard that practically begs for this sort of abuse.
Comment: I hope you get an answer to this, other than "well ... you have to do the work yourself." I always use a custom EntityResolver for this. I have not found it to be brittle---exactly---but it is a lot of code to do a simple thing.
Answer: The best way I can think of to load the DTD from a different source is to use the EntityResolver, it shouldn't be that much of a pain in the rear. I load local xml resources using and EntityResolver for DOM4j and put the file inside my jar so its easily accessible with the following code.
<code>new org.xml.sax.EntityResolver()
{
    @Override
    public InputSource resolveEntity(String publicId, String systemId)
    {
        if (systemId != null && systemId.equals("http://something.com/xml.dtd"))
            return new InputSource(getClass().getResourceAsStream("../xml/local.dtd"));;
    }
};
</code>
I think that is the "standard" way.
Another way maybe to modify the xml document via string replace the dtd reference and inject any Entity references that maybe used.


Clone SpannableStringBuilder

Question: I am working on an Activity in which I parse a text with markup characters.
What I'm doing is converting them to several types of ClickableSpans.
The problem is that I need to implement a function (lets call it function B) that implies having overlapping ClickableSpans and that causes several issues.
So what I'm doing now is creating a new SSB while detecting the overlapping spans, and removing the ones I don't need for this particular function. Working fine.
BUT, I need to be able to go back to the previous SSB and that doesn't seem to work.
STEP BY STEP:
// I CREATE THE SSBs
...
static SpannableStringBuilder ssb;
static SpannableStringBuilder ssbCopy;

// I IMPLEMENT MY CUSTOM FUNCTION THAT PARSES THE TEXT AND SETS THE SBB AS A TEXTVIEW CONTENT
...
textView.setMovementMethod(new LinkTouchMovementMethod());
ssb = addClickablePart(chapterTextStr, markupCharactersArray);
textView.setText(ssb);

// WHEN A BUTTON IS CLICKED I IMPLEMENT MY FUNCTION B. WHERE I CREATE A COPY OF MY ORIGINAL SSB AND STORE IT IN ssbCopy, AND SET IT AS THE TEXTVIEW CONTENT
...
ssbCopy = SpannableStringBuilder.valueOf(ssb);

// I REMOVE THE OVERLAPPING SPANS
...
overlapSpans = ssbCopy.getSpans(index, index+word.length(), TouchableSpan.class);

for (int c=0;c<overlapSpans.length;c++) {
    ssbCopy.removeSpan(overlapSpans[c]);
}

// I SET THE NEW CLICKABLE SPANS
...
ssbCopy.setSpan(touchableSpan, index, index + word.length(), 0);

// AND SET THE NEW SSB CONTENT TO THE TEXTVIEW
textView.setText(ssbCopy);

// EVERYTHING WORKS FINE UP TO HERE
// BUT WHEN I TRY TO SET BACK THE ORIGINAL SSB BACK AS THE CONTENT OF MY TEXTVIEW WHEN THE USER CLICKS A BUTTON
...
textView.setText(ssb);

// THE ORIGINAL SSB IS EXACTLY LIKE THE COPY (ssbCopy) AND CONTAINS THE SAME CLICKABLE SPANS I ADDED. NOT ONLY THE ORIGINAL ONES

I guess it may sound somewhat confusing and I'm not sure if I explained properly, but I can't get around this.
EDIT:
As per kcoppock answer, I learn it isn't possible to clone an ssb and valueOf(ssb) is just a copy of the object.
So I ended up cloning my "ssb" manually by looping through all elements and applying them to the new ssb. Like this:
TouchableSpan[] spans = ssb.getSpans(0, ssb.length(), TouchableSpan.class);

ssbCopy = new SpannableStringBuilder(chapterTextStr+"dsadsa");

for (int c=0;c<spans.length;c++) {
    TouchableSpan obj = spans[c];

    ssbCopy.setSpan(obj, ssb.getSpanStart(obj), ssb.getSpanEnd(obj), 0);
}

By the way, TouchableSpan is a custom class I created that extends ClickableSpan
Answer: The problem here is your use of valueOf(). It doesn't do what you think it does. All it does is return the object passed in, if it is a SpannableStringBuilder; otherwise, it wraps the given CharSequence in a SpannableStringBuilder. From the source:
public static SpannableStringBuilder valueOf(CharSequence source) {
    if (source instanceof SpannableStringBuilder) {
        return (SpannableStringBuilder) source;
    } else {
        return new SpannableStringBuilder(source);
    }
}

So essentially:
ssb == SpannableStringBuilder.valueOf(ssb);

They are one and the same Object. SpannableStringBuilder does not implement Cloneable, so there's no easy way to make a copy, other than to just generate two copies, for example:
ssb = addClickablePart(chapterTextStr, markupCharactersArray);
ssbCopy = addClickablePart(chapterTextStr, markupCharactersArray);

Comment: Thanks for your clarification about valueOf() ! At least I know where the problem resides now. However, I can't implement the generate two copies solution, because I need my copy to have the changes done to the ssb after it was stripped from the markup characters. Will keep trying. Any further ideas appreciated!
Comment: Well, I ended up cloning the ssb "manually". Your answer was the one that let me knew what was wrong, so, marked as correct.
Comment: Yeah, that's probably the only way to go, honestly. Just throw that in a utility class somewhere and save it for later. :) I think you can just pass in `Object.class` to get all span types (if you end up needing more than just `TouchableSpan` cloned).
Answer: The method subsequence in SpannableStringBuilder copies the spans. You could make a copy of you ssb by calling ssb.subsequence(0, ssb.length)
SpannableStringBuilder ssbCopy = (SpannableStringBuilder)ssb.subSequence(0, ssb.length());

Clone SpannableStringBuilder


Gauss-Weingarten relations

Question: In the 3.4 theorem, $F:R^n\supset U \rightarrow F(U)\subset M\subset R^{n+1}$ is a local represent of Riemannian manifold $M$. $g_{ij}$ is Riemannian metric , and $h_{ij}$ is second fundamental form. $\nu$ is outward normal vector. Then, how to show the red line from the Weingarten equation ?
Comment: http://www.math.jhu.edu/~js/Math646/huisken.convexflow.pdf
Comment: @jimbo   Yes, it is this paper. Do you know how to get the red line ?
Comment: @jimbo   could you tell me ? Thanks.
Answer: Let  $\frac{\partial{F}}{\partial x_{k}} = X_k$, and
$$ \nabla_{X_{i}} X_{j} = \sum\limits_{k=1}^n \Gamma^k_{ij} X_k.$$
Because tangential component of Euclidean directional derivative is the Riemannian connection on the surface we have that
$$\frac{\partial^2{F}}{\partial{ x_{i}}\partial{x_{j}}}=D_{X_{i}} X_{j} = \nabla_{X_{i}} X_{j} + \alpha \nu. $$
Now, if we multiply(  inner product ) both sides of the last equation by $\nu$, we get
$$<D_{X_{i}} X_{j},\nu> = <\nabla_{X_{i}} X_{j},\nu> + <\alpha \nu,\nu>= \alpha;$$
(note that $\nabla_{X_{i}} X_{j} \perp \nu, $ so $<\nabla_{X_{i}} X_{j},\nu>=0$).
Thus $\alpha= -h_{ij}$. Therefore
$$\frac{\partial^2{F}}{\partial{ x_{i}}\partial{x_{j}}} = \nabla_{X_{i}} X_{j}  -h_{ij}\nu = \sum\limits_{k=1}^n \Gamma^k_{ij} X_k  -h_{ij}\nu.$$
Since $\left< \nu , X_k  \right>= 0$, we infer from compatibility of metric with respect to the connection that
$\left< \frac{\partial{\nu}}{\partial{ x_{j}} }, X_k  \right>+ \left<\nu, \frac{\partial^2{F}}{\partial{ x_{k}}\partial{x_{j}}} \right>=0$. Thus
$$\left< \frac{\partial{\nu}}{\partial{ x_{j}} }, X_k  \right>= h_{jk}.$$
Similarly, we infer from $\left< \nu, \nu \right> = 1$ and compatibility of metric with respect to connection that $\left< \frac{\partial{\nu}}{\partial x_{j}}, \nu \right> =0 $. Thus $ \frac{\partial{\nu}}{\partial x_{j}}$ is in the tangent space. So there are scalars  $\alpha_i $ such that
$$ \frac{\partial{\nu}}{\partial x_{j}} = \sum\limits_{l=1}^n \alpha^j_{l} X_i.$$
We have that
$$ h_{jk}= \left< \frac{\partial{\nu}}{\partial x_{j}}  , X_k \right> = \sum\limits_{i=1}^n \alpha^j_{i} \left<  X_i,  X_k \right>=  \sum\limits_{i=1}^n \alpha^j_{i} g_{ik}= (\alpha^j_{1},..., \alpha^j_{n})(g_{1k},..., g_{nk})^T.$$
If we multiply both sides by $(g^{k1},..., g^{kn})$, we get
$$(\alpha^j_{1},..., \alpha^j_{n})= h_{jk}(g^{k1},..., g^{kn}). $$
Thus
$$\alpha^j_{l} =h_{jk}g^{kl} .$$
Now, consider
$$Z=\sum\limits_{k=1}^n  \sum\limits_{l=1}^n h_{jk}g^{kl} X_l.$$
We claim that  $ \frac{\partial{\nu}}{\partial x_{j}}= Z$. To see this, we multiply $Z$ by $X_i$, we will have
$$\left< Z, X_i \right> =\left< \sum\limits_{k=1}^n  \sum\limits_{l=1}^n h_{jk}g^{kl} X_l, X_i \right> =  \sum\limits_{k=1}^n  \sum\limits_{l=1}^n h_{jk}g^{kl} g_{li} = h_{ji}= \left< \frac{\partial{\nu}}{\partial x_{j}}  , X_i \right>.$$
Since $X_i$ is a basis for the tangent space, $Z$ is uniquely determined by the values of $ \left< Z, X_i \right>$. Also, we got $\left< Z, X_i \right>= \left< \frac{\partial{\nu}}{\partial x_{j}}  , X_i \right>$ for each $i$,
thus $\frac{\partial{\nu}}{\partial x_{j}} =Z.$
Concluding the proof.
Comment: @Boar Hi, sorry for the late reply. Here $F$
 is a parametrization and the notation is simply $dF(e_k)=\frac{\partial{F}}{\partial x_{k}} = X_k$
, where $\{e_1,...,e_n\}$
 is  the standard basis for $\mathbb R^n$. I have seen it in references for curvature flows. As an example see second chapter of [Xi-Ping_Zhu]_Lectures_on_Mean_Curvature_Flows
Comment: You are welcome, and thank you! I hope this new year has been treating you well so far. Wishing you continued happiness throughout the year
Comment: Hello, may I ask you a question, please? In which book did you see the notation $\frac{\partial{F}}{\partial x_{k}}$? It seems to denote a vector field. Is there a textbook that includes the notation? Thank you very much.
Comment: Thank you and happy new year.
Answer: A surfaces in the euclidean space the Gauss equations and the Weingarten equations
are
$$X_{uu} = \Gamma^1
_{1 1}X_u + \Gamma^2
_{
1 1}X_v + eN,
$$
$$X_{uv} =\Gamma^1_{1 2}X_u + \Gamma^2_{
1 2}X_v + fN,
$$
$$X_{vu} =\Gamma^1_{2 1}X_u + \Gamma^2
_{
2 1}X_v + fN,
$$
$$X_{vv }=\Gamma^1_{2 2}X_u + \Gamma^2_{
2 2}X_v + gN,$$
$$N_u = aX_u + cX_v,$$
$$N_v = bX_u + dX_v$$
A case general is your question.

Gauss-Weingarten relations


Gmail & SwiftMailer Fatal Error

Question: I've looked everywhere and cannot find a solution for this.
I just put up a website using GoDaddy hosting. The website has a form, which uses Gmail SMTP and was working perfectly when I was running a virtual host with XAMPP. After hosting with GoDaddy however, I get the following error when I try to submit:

Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.gmail.com [Connection refused #111]' in /home/modernautoinc/public_html/Swift/lib/classes/Swift/Transport/StreamBuffer.php:259 Stack trace: #0 /home/modernautoinc/public_html/Swift/lib/classes/Swift/Transport/StreamBuffer.php(64): Swift_Transport_StreamBuffer->_establishSocketConnection() #1 /home/modernautoinc/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php(115): Swift_Transport_StreamBuffer->initialize(Array) #2 /home/modernautoinc/public_html/Swift/lib/classes/Swift/Mailer.php(80): Swift_Transport_AbstractSmtpTransport->start() #3 /home/modernautoinc/public_html/mech.php(24): Swift_Mailer->send(Object(Swift_Message)) #4 {main} thrown in /home/modernautoinc/public_html/Swift/lib/classes/Swift/Transport/StreamBuffer.php on line 259

Here is my php:
<code><?php

require_once 'Swift/lib/swift_required.php';

$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$phone = $_REQUEST['phone'];
$make = $_REQUEST['make'];
$model = $_REQUEST['model'];
$VIN = $_REQUEST['VIN'];
$problem = $_REQUEST['problem'];

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
    ->setUsername('email@example.com')
    ->setPassword('example');

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Appointment: Mechanical')
    ->setFrom(array($email => $name))
    ->setTo(array('firstname.lastname@example.com' => 'MA'))
    ->setBody("From: ".$email."\nName: ".$name."\nPhone Number: ".$phone."\nMake: ".$make."\nModel: ".$model."\nVIN: ".$VIN."\nDescription of Problem: ".$problem);

$mailer->send($message);
header('Location: http://www.google.ca');
?>
</code>
Any help would be greatly appreciated. Thank you for your time.
Answer: For GoDaddy Hosting, I've configured my Silex app like this :
<code>$app['swiftmailer.options'] = array(
'host'       => 'p3plcpnl0689.prod.phx3.secureserver.net',
'port'       => 465,
'username'   => 'firstname.lastname@example.com',
'password'   => 'your pass',
'encryption' => 'ssl'
</code>
);
and it works like a charm!!
Comment: I'm testing this right now, and a lot of email I sent with GoDaddy SMTP went to the spam box, which isn't the case with Google SMTP.

Gmail & SwiftMailer Fatal Error


How can I identify the cause of ceiling water damage?

Question: Just wondering if there is an easy way to tell if water damage on the celing is a result of a roof leak, or condensation build up in the house.
Here are some pictures:
https://photos.app.goo.gl/6w9uajoAcbcgYpbT8
I drilled a hole from the bottom and stuck a wire so i can be directly over the damged area.
The worst of it is in the corner but there is a bit of mold along the wall too.
Because the damage is in the corner, its very difficult to see the draywall/roof from the attic. However with the limited pictures i managed to snap it looks pretty dry.
I did order a moisture meter, and plan on testing both sides. Is there any thing else i can look for?
This is an older house, with no kitchen exhaust fan.
Comment: i vote condensation since it's the worst in the corner...
Answer: Not sure if you removed the insulation to take the pics, but if not then missing insulation will create a cold spot which will certainly exacerbate condensation.
I always start with a thorough exterior inspection if possible (to rule it out), but condensation is extremely common in older homes, especially where a ceiling meets an exterior wall. Poor insulation installation at this point is common (it's difficult for some guys to get it right down to meet the insulation in the wall or up to the wall plate etc. as it's often a small space).
Just be aware that there may be an intentional air gap which the insulation should not block. Venting cold roofs is important to prevent warm air escaping the house and condensing on the underneath of cold roof coverings.
Answer: I found using an infrared camera attachment for my phone was worth 10x what I paid for my first one. The flir can identify leaks running down the framework you may not be able to see. I started out with a base model but moved up to a pro model because they were so handy both at home and for work. A flir camera was used to do exactly what you are trying to figure out. We noticed the cold water trail that was hard to see by eye even once we knew where it was. It also shows leaks in duct work, bad connections in outlets and breaker panels (the reason I moved up to a pro model) there are several brands out there but a good base model can be found for~200$. Since you are not sure this may be a tool you can use to identify the source.
Comment: Send pis of roof. How old roof? Look for water stains on frame. Could be crack in capping of roof . Gutter clogged and backs up ,or frost in attic.Even could be in  trim outside.


How can I automate script that works? rtcwake, service network-manager

Question: I have a script I want to run on regular intervals throughout the day (11:05 16:05 and 22:05. But I do not want the computer on the whole day, so I tried a script from sudo crontab -e suggested here.
0 10 * * * sudo rtcwake -m disk -l -t $(date +%s --date '11:00')

The thing is, it worked only if I ran it in the terminal but not from the cronjob. I also tried sudo /usr/sbin/rtcwake xxxx in the cronjob without luck.
But a second problem emerged when the computer woke up from the manual rtcwake-call and my script were to run. The system time was off with two hours because the system time had changed. So I had to put in a second cronjob to fix the time when the computer came to life again
1 11 * * * sudo hwclock -w

As you see it runs one minute after the computer is supposed to wake up from the first rtcwake-call putting it to sleep in the first place. I am still not sure if it works because I have not tried it yet. (The BIOS has the time 09:00 when the computer has 11:00 after the wake up)
But a third problem emerged. When I had run the rtcwakeup-call and tried to run my script manually it did not work because I had no internet connection.
So I manually did a
sudo service network-manager restart

and tried the script. It worked!
My question is, how do I make the thing work as a whole? The script functioned properly when the computer was on 24/7 because there were an internet connection and the time ticked along with system time and OS-time in sync.
The script runs on a Xubuntu 16 LTS computer. Perhaps it has a different setup than other distributions.
If I run sudo hwclock it says the time is 15:20 just like the clock in the corner says. But when I do the rtcwake
sudo rtcwake -m disk -l -t $(date +%s --date '16:25')

it responds that the computer will wake up at 18:25. How can both the hwclock and xubuntu clock be in sync while the timer in rtcwake is off by 2 hours? How do I sync hwclock with rtcwake? (This problem was solved with *sudo hwclock --systohc --localtime)
What is needed:
cronjob - run my script at regular intervals (collecting data from the internet)
cronjob2 - make computer go to sleep even if user or admin is not logged in
cronjob3 - when computer wakes up adjust the time so the first script (cronjob) runs at the time when it was supposed and not two hours later
cronjob4 - restart network before (cronjob) runs so that it has a fresh internet connection
Comment: Your first command likely fails because of the `%` sign - see [Unable to execute command in cron](https://askubuntu.com/a/829822/178692)
Comment: I will try that. Strange that the terminal and cronjob does not interpret it the same.
Comment: I can restart the computer at 18:25 by setting rtcwake to 16:25. I would prefer if I would not have to a two hour adjustment (which might change even more as it has changed already by two hours). Has it to do with local time?
Comment: Not sure if the proposed solution is still current (given the sysV -> upstart -> systemd transition), but possibly related: [Trying to set wake timer, date is confusing](https://askubuntu.com/questions/668552/trying-to-set-wake-timer-date-is-confusing)
Comment: I fixed the timing problem with this sudo hwclock --systohc --localtime from this https://docs.slackware.com/howtos:hardware:syncing_hardware_clock_and_system_local_time    ------>>I have heard about emergent properties, but these are emergent problems. At every step of more administration weaknesses are exposed which manual commands do not show the user.
Comment: If you have found a solution, please post it as an answer so that it can help others
Comment: I have only solved part of the problem. The difference between hwclock and local time which rtcwake uses. If everything else falls into place later this afternoon I will let you know.
Comment: Please do not send this message "Please avoid extended discussions in comments. Would you like to automatically move this discussion to chat?" when the user does not have enough reputation to engage in a chat. ---> IF user < reputation than X then "Please do not engage in long comments" ELSE IF user > reputation than X "Please avoid extended discussions in comments. Would you like to automatically move this discussion to chat?"
Answer: The solutions were to adjust the commands in cron
From (without backslash %s):
sudo rtcwake -m disk -l -t $(date +%s --date '16:25')

To (with backslash %s):
sudo rtcwake -m disk -l -t $(date +\%s --date '16:25')

After every awakening I also run time sync cron-job, which run approximately 3 minutes after the wake up time. During this time the OS time will jump from a lagging of two hours to the correct time. After this the hardware clock can be synchronized with the OS-time. If you sync it to fast it will sync back in time and ruin the rest of the scripts that depend on the correct time:
sudo hwclock --systohc --localtime

The latter ensures that the BIOS clock and localtime are the same. Otherwise they will drift from each other when the internal battery clock moves independently from the processor that is at rest while the computer is asleep.
To make sure the time sync works I have put both the correct time to run the cron time sync and two hours before which is the intervall my computer lags.
It means if I want the time sync to go off at 18:55 I also put in 16:55 so that it runs even if the hardware clock is out of sync with the OS clock
55 16,18 * * * hwclock --systohc --localtime

You will have to monitor your own system to see what discrepancies occur. If it moves around just put in more hours to do the sync. Perhaps even every hour. When the computer is asleep nothing will be done, but while it is awake it will sync the time every hour.
Comment: FYI the `sudo`s aren't required since you are running these from root's crontab (`sudo crontab -e`)
Comment: At this moment I would even add "magic_spell_pray_to_god_make_this_work sudo any_command && please_do_as_I_want_it_to_do"
Comment: I trust mechanical watches much more than digital. After the ordeal with these cron jobs I do definately do not trust computer time.


Silverlight Accordion Tab Issue

Question: All,
I have simple accordion with 2 accordion items each containing 4 text boxes. When I tab into the accordion item, why can't I tab across each of the textboxes in the accordion item? I tried practically everything from tabindex to TabNavigation='Local' & 'Cycle'.
I want to be able to tab through all textboxes in the accordion item.
Requested code:
<UserControl x:Class="Pimarc.Silverlight.Commerce.UI.View.TestView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit">

<Grid x:Name="LayoutRoot" Background="White">
    <toolkit:Accordion HorizontalAlignment="Left" Margin="30,46,0,0" Name="accordion1" VerticalAlignment="Top" Width="200">
        <toolkit:AccordionItem Header="abac" IsTabStop="True" TabNavigation="Cycle">
            <StackPanel>
            <TextBox Name="textBox1" Width="120" TabIndex="0" />
                <TextBox Name="textBox2" Width="120" TabIndex="1" />
                <TextBox Name="textBox3" Width="120" TabIndex="2" />
                <TextBox Name="textBox4" Width="120" TabIndex="3"/>
            </StackPanel>
        </toolkit:AccordionItem>

        <toolkit:AccordionItem Header="bob">
            <StackPanel>
            <TextBox Name="textBox5" VerticalAlignment="Top" Width="120" />
            <TextBox Name="textBox6" VerticalAlignment="Top" Width="120" />
            <TextBox Name="textBox71" VerticalAlignment="Top" Width="120" />
            <TextBox Name="textBox81" VerticalAlignment="Top" Width="120" />
            </StackPanel>
        </toolkit:AccordionItem>
    </toolkit:Accordion>
</Grid>

Comment: Can you extend your post with some xaml to better understand/repro your problem?
Answer: This is a known issue of the accordion see: Tab order of controls in Accordion control
However there is a easy workaround:
You need to set the TabNavigation property with the help of the ExpandableContentControlStyle.
So you need to create a style:

And use this in your AccordionItem:
<toolkit:AccordionItem Header="abac" IsTabStop="True"
     ExpandableContentControlStyle="{StaticResource TabNavigationStyle}">

Silverlight Accordion Tab Issue


Lenovo ThinkPad T440p + Ubuntu 12.04/14.04

Question: Is there anybody, who is able to install Ubuntu 12.04 or 14.04 (64bit) on Lenovo Thinkpad T440p and get fully functional NVIDIA Optimus? This laptop model is certified by Canonical to be fully supported by Ubuntu, but install Ubuntu 14.04 is nearly impossible, due to the fact, that 14.04 desktop ISO image crash during initial boot.
Any help?
See, for exmaple: ThinkPad T440p: problems with various Ubuntu flavours
Add info regarding bad 12.04 support: T440p problems with 12.04
Answer: Downgrade BIOS from 2.22 to 1.14   resolved mine problems.
BIOS update utility :
http://support.lenovo.com/en_US/downloads/detail.page?DocID=DS037575
I've ran file 'gluj04us.exe' (1.14 BIOS) from Windows 7, then Laptop restarted 3 times (flash operations).
After 4th reboot laptop I've reinstalled Ubuntu 14.04 and every hardware stuff working properly.
Comment: What about NVIDIA optimus support, sleeping, power management, wifi, etc, etc. Everything really works???
Comment: Confirmed, everything works.
Comment: Including SSD disks??? See: http://askubuntu.com/questions/441243/bumblebee-and-lenovo-os-crash-after-unsuccesful-installation/502429#502429
Answer: From your link :

I had the same problem with my T440p i7-4700MQ with Intel and Nvidia.
I managed to finally boot off a 14.04 Live-DVD by pressing F6 and/or
  ESC as soon as the "Press Enter" disappeared. Then I modified the boot
  options to "nomodeset" which led me to the choice between "try ..."
  and "install ...". I went for "try..." and once the desktop showed up
  from where I then installed Trusty 64bit.
It goes without saying that the boot options in grub are set to
  nomodeset, but at least the notebook is working. WLAN is ok. I reach
  speeds up to 780 MBit/s. There remain several issues though: display
  brightness buttons are not functional, fingerprint reader is not
  detected, and the proprietary nvidia driver is something that will
  maybe work properly some day.

Edit: once you install using the "nomodeset", edit the file /etc/default/grub and remove the option "nomodeset". Then open "Additional Drivers" and install the nvidia driver. This allows the brightness buttons to work fine.
Did you try the nomodeset boot parameter?
And instructions for installing Nvidia Prime:

Update: the instructions below should work under Ubuntu 14.04 Trusty
  Tahr too.
Note: the  nvidia-prime package only supports the proprietary Nvidia
  drivers and won't work with Nouveau!
If you're using Ubuntu 13.10 Saucy Salamander or 14.04 Trusty Tahr and
  want to test the Optimus support in the Nvidia Graphics Drivers
  319.12+, here's what you need to do:

Firstly, purge Bumblebee if installed:

sudo apt-get purge bumblebee*
Also, make sure libvdpau-va-gl1 is not enabled system-wide because it
  causes Nvidia Settings to crash on start - if it is, either disable it
  or simply remove the package:
sudo apt-get purge libvdpau-va-gl1

Install the proprietary Nvidia drivers and the Nvidia Prime package:

sudo apt-get install nvidia-319 nvidia-settings-319 nvidia-prime

Reboot the system.

That's it, after a reboot, your laptop should be using the Nvidia GPU
  to render the desktop.
Comment: Does not work at all!!!
Comment: What is the error message?
Comment: see: [link](https://answers.launchpad.net/ubuntu/+question/246834)
Comment: So you are getting the "SQUASHFS error: zlib decompression failed" error? Try your USB drive in a USB 2 port, or try a USB 3 drive in a USB 3 port, or try a USB DVD drive. In [this thread](https://forums.lenovo.com/t5/T400-T500-and-newer-T-series/T540p-T440p-UltraDock-external-display-issues/td-p/1368847/page/4) people are reporting USB problems with T440 under Windows too. Have you [installed the latest BIOS?](http://support.lenovo.com/en_US/downloads/detail.page?DocID=DS037575)
Comment: Also see [this thread](https://bbs.archlinux.org/viewtopic.php?id=176370), it seems that under certain combinations of BIOS settings it is possible to brick the laptop: they recommend turning off UEFI booting.
Comment: This answer helped me a lot, using the "nomodeset" was the only way to install 14.04. The only catch is that once it is installed I removed the "nomodeset" option from grub editing /etc/default/grub and installed the nvidia driver from the default "Additional Drivers" program. Now the computer works perfectly as a Certified Hardware model should. Thanks!
Comment: For me the key for the installation of of ubuntu 14.4 on Lenovo t440p also was also to activate "nomodeset" at the very beginning of the installation as described above by bain May 5th. Thank you for posting! Just as a little hint: I had to press Fn+F6 instead of just F6 to get into the BootOptions menue which is described for example [here](https://help.ubuntu.com/community/BootOptions). So far I had not problem with the graphic card and I did not follow the Nividia related instructions
Answer: Not the answer you need but I run 64-bit Ubuntu desktop on Lenovo Thinkpad X121e. It is a terribly slow laptop and I gave up trying to run Windows 7 on it.
Except for speed and lack of CD/DVD player I have no issues.
I started using 12.04 LTS and have upgraded to 14.04 LTS
Comment: Thanks, but your notebook is completely different story :)
Answer: My Lenovo T440p has just arrived in my house. And this Laptop use UEFI and a secure boot to prevent some security problems. I have installed the latest Ubuntu 14.04 LTS 64bit version just to assure you that the installation is possible. I don't know if you could install Ubuntu 12.04 as for me, it does not support the UEFI frame.
if you windows 8 have 4 partions like me, you could proceed the installation like me.
1 Disable in BIOS the Secure Boot. And shrink some space for Ubuntu, do not format it.
2 Make a U disk boot version of Ubuntu 14.04 LTS with the help of UltraISO for example.
3 Change the order of boot by taken first the U disk, and proceed the process of installation. if you chose the NVidia GT730M like me, maybe you should modify the first item during U disk boot:
click 'e' to edit the command line for Install Ubuntu when you run into the
Try Ubuntu ....
install Ubuntu
Windows 8 boot loader ...
and change the "quiet splash" to "nomodeset"
(do not type the quote mark). To prevent the black waiting screen . LOL. Click Ctrl + x to proceed.
4 You can enjoy the environment of Ubuntu 14.04 LTS. But, for me, there is still some problem with the shutdown option, Ubuntu can not shut down correctly due to some Wifi driver (Intel things).
Regards
Comment: What is exact type number of your T440p?
Comment: 20ANCTO1WW, If could help you.
Answer: I'm also experiencing problems with the T440p.
For what concernes the optimus bug, see
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1268669
Comment: Thanks! I am still waiting for any suitable solution or workaround, so far Ubuntu is not possible to reliable operate on T440p :(
Answer: I've a T420 and I hope most of its configurations might be same as your T440p. I'm also having some issues to get the optimus to work and presently settled for using laptop in discrete(pure nvidia) graphics mode(enable/disable from BIOS) with nvidia's 331.38 version of the driver. For installation use nomodset as suggested above.
Hope this will get your laptop working.
Comment: T420 and T440p are very different (HW)
Answer: I am able to install Ubuntu 12.04.4 desktop 64-bit on my Lenovo t440p (with SSD) from a USB stick without any BIOS downgrade. After a clean install, the wireless will not work immediately, but it works after you find a ethernet cable to do apt-get update/upgrade:
<code>sudo apt-get update
sudo apt-get upgrade
</code>
It might worth a try if you are still finding a solution.
In addition, I can somehow install the later versions ("12.04.5" or "14.04.1") via various tricks I found online, but the system becomes extremely unstable ... Just my 2 cents.


Play same game on two different platforms

Question: My son has Minecraft on two different platforms (Xbox One and iOS 10).
He wants to continuously and seamlessly be able to move from one to the other: the Xbox at home, but iOS when mobile.
Is this possible?
Answer: Yes, you may share worlds across platforms using the Minecraft Bedrock Edition


How to get last4 digits BEFORE submit the data with Stripe

Question: What I want to achieve is to be able to show the last 4 digits of the card in a summary before doing the submit.
I have a Checkout page by steps(4), in the 3rd step I fill the card info, when I go to the four step I want to be able to show a summary that show the last 4 digits of the card.
In all my research all what I found that show me the card info (last4) is after the submit, through the stripeToken or the customer, for  example in this question Getting Last4 Digits of Card using Customer Object - Stripe API with PHP
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];

// Create a Customer
$StripeCustomer = \Stripe\Customer::create(array(
          "description" => "$username",
          "card" => $token
));
$last4 = $StripeCustomer->sources->data[0]->last4;

another thing I was trying to do was to create the Customer using WP user id
$customer_id =  get_user_meta(get_current_user_id(), '_pw_stripe_user_id', true);
$customer = new \WC_Stripe_Customer($customer_id);

but it returns me a default empty Customer, so I don't have the last4, I assume this happens because before doing the submit there is no such Customer.
I can't access to the input value because is an iframe that Stripe insert in the form.
So any way to get the last4 before the submit? Thx in advance.
Comment: Not sure I follow exactly. You want to see the card number (fine, last four) before it is securely submitted to Stripe?
Comment: @ficuscr  Yes I need to show a summary including the last 4 digits before it is securely submitted to Stripe
Comment: Not sure how that would work, short of you doing the submit/create on step 3, making the "confirmation" you perform more of a "review". I mean think about it, if not sent to Stripe would be client-side code, and whole idea is that you don't take on PCI compliance burdens, they are not going to facilitate letting you scrape the full card number. I'm talking abstractly and don't know Stripe well but that's my gut.
Comment: are the numbers entered in to your web page? or stripes?
Comment: the numbers are entered in an input that stripe inject in my page through an iframe
Comment: then you have NO access to them, so this cant be done
Comment: I had hope that the token could be accessed before submitting or pre-saving the customer and getting some information from the card before doing the submit
Answer: If you use the custom version of Checkout you can easily do this, just grab token.card.last4 in your token callback. You could show this, or any kind of summary, to your user before you choose to submit the token token.id to your backend if you'd like.
Example: http://jsfiddle.net/9mgqzuL1/
token: function(token) {
    console.log(token);
    document.getElementById('last4').innerHTML = token.card.last4;
    // you'd then want to do something with token.id and submit your form
  }

Comment: I don't think I understood the question.
Comment: @duck thx, but you are getting the last 4 when you click on the submit button that it create the token, I need it before clicking the button
Comment: It's not possible _before_ clicking the button, but this _is_ before you submit it to your backend to actually process the charge, which is what the above does. So they could enter their card, you could present them with a summary after the token is generated, they could click something else at which time you submit the form and pass `token.id` off to your backend to charge.
Comment: Yes it is true, it is before I submit it to my backend, but I need it in a step before the submit, so I hope it can be done before clicking the button, thx any way.
Comment: Unfortunately there's no way to do that with checkout or stripe.js v3 as they are in an iframe. You might be able to use the older v2 of Stripe.js, however, that forces you to do more extensive PCI compliance (SAQ A-EP) which means more time and $$$. https://stripe.com/docs/security#validating-pci-compliance


How to update form in an iFrame from input field in the main document?

Question: I have a text input field (email address) with a submit button in the main document and a form in an iFrame. When I click on the submit button in the main document, the email address in the form in the iFrame should be updated with the value entered into the text input field in the main document. How to do that exactly? :S
Answer: I've corrected my answer. You can find more info here perhaps: How can I access iframe elements with Javascript?
Keep in mind that you have a cross-domain restrictions in most browsers, that will not allow you to tamper with an iframe that is on another domain comparing to your "main document".


C# - Loop foreach until true

Question: New to C#. But due to circumstances at work I have to "learn on the fly."
Been struggling the last 2 days with my code and I consumed as many questions here and articles on MSDN as I could but I think they confused me further.
I launch app A using my code. App A launches app B (I cannot launch app B, I'm beyond that).
What I want to do w/ my code is the moment app B's MainWindowTitle is available, hide the window.
So far, I can only accomplish this w/ a Thread.Sleep(xxx); before the code you see below.
I want to avoid using timers.
What I'm trying to do is loop the code below until it is true.

When app A launches app B, it takes a few seconds for the MainWindowTitle to become available. But the code runs so fast that it's not available yet and the code is done.

IntPtr hWnd = IntPtr.Zero;
foreach (Process procList in Process.GetProcess())
{
    if (procList.MainWindowTitle.Contains("SAP Logon"))
    {
        hWnd = procList.MainWindowHandle;
    }
}
ShowWindow(hWnd, 0);

That code only works if I precede it with something like:
Thread.Sleep(10000);

before the entire block of code. And the only reason it works is b/c it allows enough time to pass for the Window to open and contain the title I'm looking for.
I have tried while loops.

Outside the 'foreach'
Outside the 'if'
Around the 'foreach' (that locked up the system really quickly...) hah!
Around the 'if'

I feel like one of the following should work, but it doesn't, or I'm completely screwing it up.
while (!procList.MainWindowTitle.Contains("SAP Logon")) { } // ! at the beginning OR
while (procList.MainWindowTitle.Contains("SAP Logon") == null) { } // equaling null OR
while (procList.MainWindowTitle.Contains("SAP Logon") < 0) { } // etc., etc.,
while (procList.MainWindowTitle.DOESNOTContain("SAP Logon")) { } // I know this is wrong but it almost seems like what I need...

Anyone have any suggestions? My brain is scrambled eggs and this is the last bit that I need to finish this app.
If my only alternative IS Thread.Sleep(), so be it, but I would prefer to not use it.
One last thing: I have to target .net 2.0.
Thank you kindly!
Comment: Use while loop for that.
Comment: Your title has no bearing on the problem.
Answer: Your idea of using the while loop should work. You could try something like this:
IntPtr hWnd = IntPtr.Zero;
bool isFound = false;
while(!isFound)
{
  foreach (Process procList in Process.GetProcess())
  {
    if (procList.MainWindowTitle.Contains("SAP Logon"))
    {
        isFound = true;
        hWnd = procList.MainWindowHandle;
    }
  }
  Thread.Sleep(100); // You may or may not want this
}
ShowWindow(hWnd, 0);

Comment: Perfect! Thank you, this is exactly what I was looking for! I thought it might be a while(){} but for the life of me just couldn't figure out HOW to word it. Thanks!
Answer: Instead of checking for the caption of the app in every single process, you can check using just the name of the EXE itself.  I would also put in a timeout for good measure. For example, with Notepad you'd do:
        Process[] ps;
        DateTime timeout = DateTime.Now.AddSeconds(30);
        do
        {
            System.Threading.Thread.Sleep(100);
            ps = Process.GetProcessesByName("notepad"); // <--- no path, AND no extension (just the EXE name)
        } while (ps.Length == 0 && timeout > DateTime.Now);
        if (ps.Length > 0)
        {
            ShowWindow(ps[0].MainWindowHandle, 0);
        }
        else
        {
            MessageBox.Show("Process Not Found within Timeout Period", "Process Failed to Spawn");
        }

Comment: Thanks! Not sure how to apply this to my case since the app I'm launching is launching another app and the process doesn't exist yet.Plus I already got my answer above. But thanks for the code. I'm sure sooner or later I'll need it anyway. I save all these bits of code - good learning tool for me.
Answer: Have you tried or seen this:
.NET Events for Process executable start
This should do what you are looking for...
Comment: Thanks! This actually looks very useful for a bunch of stuff I need to do in an upcoming project.

C# - Loop foreach until true


How to retrieve posts(books) based on category(taxonomy) in wordpress?

Question: I am trying to display posts of specific category(taxonomy) that is 'Book1'.
I tried to display it with the following code.
                    $args = array(
                        'post_type' => 'book',
                        'posts_per_page' => 6,
                        'tax_query' => array(
                            array(
                                'taxonomy' => 'Book1',
                                'field' => 'id',
                                'terms' => 1
                            )
                        )
                    );
                    echo '
';
                    $postss = get_posts( $args );

                    if ( ! empty( $postss ) && is_array( $postss ) ) {
                        // Run a loop and print them all
                        $i=1;
                        foreach ( $postss as $termm ) {
                                echo ' '.$i.' '.$termm->post_title. '
';
                                $i++;
                        }
                    }
               ?>

In output no any item is displayed.
Comment: Does this answer your question? [Link1](https://stackoverflow.com/questions/9322090/wordpress-getting-posts-in-a-custom-taxonomy),[Link2](https://stackoverflow.com/questions/25004486/how-to-get-posts-by-custom-taxonomy-in-wordpress),[Link3](https://stackoverflow.com/questions/3354272/get-all-posts-from-custom-taxonomy-in-wordpress)
Answer: $custom_terms = get_terms('Book1');

foreach($custom_terms as $custom_term) {
    wp_reset_query();
    $args = array(
        'post_type' => 'book',
        'posts_per_page' => 6,
        'tax_query' => array(
            array(
                'taxonomy' => 'Book1',
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
     );

    $loop = new WP_Query($args);
    if($loop->have_posts()) {
        echo '
'.$custom_term->name.'
';

        while($loop->have_posts()) : $loop->the_post();
            echo ''.get_the_title().'
';
        endwhile;
    }
}

try this code
Answer: $args = array(
        'post_type' => 'book',
        'posts_per_page' => 6,
        'tax_query' => array(
            array(
                'taxonomy' => 'Book1',
                'field' => ''term_id', // here you are worng name too
                'terms' => 1
            )
        )
    );
    echo '
';
    $postss = get_posts( $args );

    if ( ! empty( $postss ) && is_array( $postss ) ) {
        // Run a loop and print them all
        $i=1;
        foreach ( $postss as $termm ) {
                echo ' '.$i.' '.$termm->post_title. '
';
                $i++;
        }
    }

?>
// best solution
<?php

$query = new WP_Query( array(
    'post_type' => 'book',          // name of post type.
    'tax_query' => array(
        array(
            'taxonomy' => 'Book1',   // taxonomy name
            'field' => 'term_id',           // term_id, slug or name
            'terms' => 1,                  // term id, term slug or term name
        )
    )
) );

while ( $query->have_posts() ) : $query->the_post();
    // do stuff here....
endwhile;

/**
 * reset the orignal query
 * we should use this to reset wp_query
 */
wp_reset_query();
?>

Answer: I did it by doing like this. Thanks all.
        $args = array(
            'post_type' => 'book',
            'cat' => '35'
        );
        echo '
';
        $postss = query_posts($args);
        if ( ! empty( $postss ) && is_array( $postss ) ) {
            // Run a loop and print them all
            ?><?php $i=1;
            foreach ( $postss as $termm ) { ?>

                    <?php echo ' '.$i.' '.$termm->post_title. '
';$i++;?>
                <?php
            }
        }


Arduino Class "does not name a type"

Question: I am currently making a class in order to control 3 DC motors
and in Arduino
and i create 4 object in Arduino (main)
Here is the code:
but when i run this code lot of errors occurs like this
'elevator' does not name a type
'elv1' was not declared in this scope
'elv2' was not declared in this scope
'elv3' was not declared in this scope
'elv4' was not declared in this scope

So, I would expect some help from people here, regarding how can I make my class work.
Thank you in advance
this is my code
elevator.h:
#ifndef elevator_H
#define elevator_H

class elevator {
    public:
        int pos(int swa, int swb,int swc ,int swd);
        void forwardDC(int A11,int A22);
        void reverseDC(int A11,int A22);
        void Breaking(int A11,int A22);
        void stopDC(int A11,int A22);
        char dir;
};

#endif

and this is elevator.cpp:
#include "Arduino.h"
#include "elevator.h"

int elevator::pos(int swa ,int swb ,int swc ,int swd) {
    int flag =0;
    if (flag >= 4)
        flag = 0;
    if (digitalRead(swa) == HIGH)
        flag = 1;
    if (digitalRead(swb) == HIGH)
        flag = 2;
    if (digitalRead(swc) == HIGH)
        flag = 3;
    if (digitalRead(swd) == HIGH)
        flag = 4;
    return flag;
}

void elevator::forwardDC(int A11,int A22) {
    digitalWrite(A1, LOW);
    digitalWrite(A2, HIGH);
    elevator::dir = 'F';
    delay(1000);
}

this declaration in Arduino (.ino):
#include <elevator.h>

elevator elv1;
elevator elv2;
elevator elv3;
elevator elv;

Comment: where did you save the `elevator.h` and `elevator.cpp` files? If they are in the same directory as the `.ino` you shall include the header using `#include "elevator.h"`. Otherwise, you shall put them in a directory in the `~/Documents/Arduino/libraries` directory (or the equivalent one you use). Your problem means that the arduino IDE is not finding the header (or worst, it finds another header..)
Comment: TL;DR and format your code too.
Comment: Maybe you should pass an argument to the `#include` directive.
Comment: I'm so sooryI can't understand you . you mean like this #include elv1 ??
Comment: #include
Comment: thanks for your replay, but all 3 extension in the same folder (.h & .cpp & .ino in one folder )
Answer: When you use
#include <elevator.h>

it implies a library from the libraries folder.  Instead, try
#include "elevator.h"

Answer: You have to add the function to create a new elevator variable.
In elevator.h:
public:
  elevator();
  ...

In elevator.cpp:
elevator::elevator() {
}

Arduino Class "does not name a type"


Do higher combos increase my damage?

Question: I wonder if the size of the combo meter has influence on anything if you don't have runes, which have special effect for higher combo counts. I am aware that with getting combos you can use special skills like executes, but this is not what I mean.
Comment: Are you talking about whether the size of the combo meter increases the damage of your strikes?
Comment: No the damage of normal weapon hits or skills or any influence in general
Comment: So what you're asking is if you do more damage if your combo counter is higher?
Comment: Yes or if the skill damage is higher. I wonder If there is any influence when you have a high combo.
Answer: Combos do not directly increase your damage, but higher combos do award more experience at the end of the combat. At the end of the combat, your highest combo is multiplied by 10 and awarded as experience for Talion. There is also a Tier 5 ability that doubles your attack damage while you have a Hit Streak active.
Comment: @h0ch5tr4355 Higher hit steak values also allow you to break wooden shields & power past berserkers' parrys.
Comment: That is the answer I have searched. Didn't think about EXP and so it has an advantage to get higher combos.

Do higher combos increase my damage?


Approximating Functions with Polynomials in Taylor Series

Question: I'm having difficulty with a series of problems I've been working on and I can't seem to find a straightforward explanation of how to solve them. The problem is approximating functions.
$f(x)=x^{1/3}$, $a=8$, approximate $7.5^{1/3}$
I was able to calculate $p_1(x)=2+(1/12)(x-8)$, $p_2(x)=2+(1/12)(x-8)-(1/288)(x-8)^2$
I know need to use the linear approximating polynomial and the quadratic approximating polynomial to come up with an answer. I'm unsure of how to use the $7.5^{1/3}$ to come up with an answer. Any help would be greatly appreciated.
Comment: Did you think of setting $x=7.5$ in the approximating polynomials?
Answer: Hint : Just plug $x=7.5$ into the approximation-polynomials.
The exact result and the approximations are (calculation with PARI/GP) :
<code>? 7.5^(1/3)
%4 = 1.957433820584431797712468030
? 2+1/12*(7.5-8)
%5 = 1.958333333333333333333333333
? 2+1/12*(7.5-8)-1/288*(7.5-8)^2
%6 = 1.957465277777777777777777778
?
</code>
Comment: That worked! Thank you so much!
Comment: You see : The polynomial with degree $2$ gives already a very good approximation.
Comment: So just plug the 7.5 into the p1(x) to solve it, or should I plug 7.5^(1/3) into p1x?
Comment: Only $7.5$ , not $7.5^{1/3}$. You calculated the taylor sequence around $a=8$. You want to approximate $f(7.5)$, and $f(x)$ is approximated by the taylor-polynomials.
Answer: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
7.5^{1/3} & = \pars{15 \over 2}^{1/3} = \pars{60 \over 8}^{1/3} =
\pars{64 - 4 \over 8}^{1/3} =
\bracks{{64 \over 8}\pars{1 - {1 \over 16}}}^{1/3} =
2\pars{1 - {1 \over 16}}^{1/3}
\\[3mm] & \approx 2 - {1 \over 24} - {1 \over 1152} - {5 \over 165888} - {5 \over 3981312}
\approx 1.95743\color{#f00}{388109246}
\end{align}

Relative Error $\ds{\sim 10^{-6}\ \%}$.


Default location of Error Log Elasticsearch

Question: I need to find the default location for the Elasticsearch error log for Ubuntu. When I start the service it states it is okay but when I ask for the service this comes up:
Loaded: loaded (/usr/lib/systemd/system/elasticsearch.service; enabled; vendo
   Active: inactive (dead) since Thu 2017-11-23 05:49:46 CST; 3min ago
     Docs: http://www.elastic.co
 Main PID: 81608 (code=exited, status=0/SUCCESS)

I need to figure out why this is happening but I don't know where the error log is located. I haven't been on this computer in a few years and I did not change it from the default location.
Comment: usually, the log is under /var/log/elasticsearch/{{clustername}}.log
Answer: try journalctl -u elasticsearch.service -xe first.
If this is not good look at /usr/lib/systemd/system/elasticsearch.service file, work out where the config is and find the log.
If that doesn't work install lsof and search for the log in the list of open file
Answer: sudo su
cd /var/log/elasticsearch
tail elasticsearch.log


Static dictionary in .Net Thread safety

Question: Reading msdn documentation for dictionaries it says : "Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."
Those this mean that with a dictionary such as this :

static object syncObject = new object();
static Dictionary<string,MyObject> mydictionary= new Dictionary<string, MyObject>();

Is doing something like the code below unnecessary?

lock (syncObject)
{
   context = new TDataContext();
   mydictionary.Add("key", myObject);
}

Answer: It's referring to static methods on the class itself. The statement is actually boilerplate documentation added to most classes. The Dictionary<> class doesn't actually expose any static methods.
You will have to serialize access to your dictionary class yourself using the lock keyword or perhaps even a ReaderWriterLock. Threading though is a pretty complex topic and the lock keyword isn't always appropriate. There's a great book by Joe Duffy "Concurrent Programming on Windows" that goes into great depth about protecting shared application resources.
Answer: You are misinterpreting "public static members of this type" as "public static instances of this type".
Answer: It means that if you call the Add method (an instance method) you'd better ensure that you have exclusive access to the Dictionary by using your own locking or serialization semantics. Bad things could occur if two threads are modifying the state of your Dictionary at the same time, and it's your responsibility to ensure that this doesn't happen. There's nothing within Dictionary's Add method that will do this locking for you.
If, however, you call some static method on Dictionary (of which there aren't any useful ones) then you'd be fine without a lock.
This is the general rule for all .NET types in the BCL.

Static dictionary in .Net Thread safety


How to make a "live" function without ajax requests on intervals

Question: I want to make a website, where the user gets a live notification if a file on the server gets  edited (for example).
I could do this with an ajax call and if/else statement to check if there is anything new, but was wondering if it is possible to do it another way, without having to resort to infinite HTTP requests.
Is there another possibility to do this? If yes how would it work?
Comment: Your specification is a bit vague, but depending on your server-side technology, you could use something like [Websocket](http://en.wikipedia.org/wiki/WebSocket).. if you are using .Net look into SignalIR or ASPComet.. otherwise, you could look into something like node.js
Comment: i thought i might have to resort to node.js... isnt there a php solution for this?
Answer: Yes: http://socket.io/
Even though it uses Node.JS on the server side which could be a problem.


In the Aria: Eclipse mission, what can I do besides releasing that crazy woman from jail?

Question: I talked to the Eclipse leader in the C-Sec office in the Presidium Commons, but she does indeed sound very dangerous, so I chose to find another solution.
Unfortunately for me, I decided to go off and scan some solar systems instead. Now I completely forgot the content of that conversation.
What's the other solution besides releasing her?
Answer: You can find her second-in-command, a salarian named Sayn on level D2: Docks: Holding Area of the Citadel. He is in area 5: Cargo Hold: A. If you talk to him, you can convince him to take over as leader of Eclipse and you will gain his support.
Answer: You may have to wait for a patch or correction code, as I'm doing now.
I agreed with your assessment of the prisoner and made the same choice.
Unfortunately, the solution involving Sayn appears to have a glitch and may not work.
I successfully convinced him to assume leadership and he happily left the cargo area, but Aria knows nothing about it and Bailey thinks I've never spoken to Sadaris, asking me to come back after I've done so.
Comment: I'm also encountering this problem.  I've been told by a friend (but haven't confirmed myself) that it will resolve once the other two leaders are taken care of.
Comment: I'm having the same issue, and have completed the Blue Suns/Blood Pack pieces. I keep coming back to the Citadel after completing missions, checking Purgatory/C-Sec Outpost/Bailey/Cargo Hold to see if anything new happens. I've had no updates yet, but I'll post back here if completing more missions moves things ahead.
Comment: Before you leave the holding area, Cmdr Bailey should come across your comm and tell you that the counsel has decided to keep the prisoner locked up and Aria set it up.


Scalar function that returns Address

Question: I've updated the code as suggested, but now I'm getting a new error:

Msg 141, Level 15, State 1, Procedure udf_GetCustomerAddress, Line 31
  A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

My code is pasted below:
--The function
Create Function udf_GetCustomerAddress
    (@CustomerID varchar)
Returns varchar
As
Begin
    declare @CustomerAddress varchar

    select
        @CustomerAddress = c.CompanyName, c.Address, c.City,
        c.StateOrRegion, c.PostalCode, c.CustomerID
    from
        Customers c
    where
        c.CustomerID = @CustomerID

    Return @CustomerAddress
End

Thanks again in advance!
Answer: You should change Return varchar by RETURNS VARCHAR
Go
--Address function
Create Function udf_GetCustomerAddress
(@CustomerID varchar)
RETURNS varchar(max)
As
Begin
    declare @CustomerAddress varchar(max);

    select @CustomerAddress = concat(c.CompanyName, c.Address, c.City,
    c.StateOrRegion, c.PostalCode, c.CustomerID)
    from Customers c
    where c.CustomerID = @CustomerID;

    Return @CustomerAddress;
End

Have a look at CREATE FUNCTION syntax.
Comment: Thanks @McNets - appreciate it.
Comment: You would never want to use varchar(max) unless you are returning more than 8000 characters. Uncommon when dealing with addresses.
Answer: You need a length for all the varchar()s -- always use a length in SQL Server.  Then you probably want to concatenate the results.  If I assume that all types are strings . . .
Create Function udf_GetCustomerAddress (
    @CustomerID varchar(255)
)
Returns varchar(max)
As
Begin
    declare @CustomerAddress varchar(max);

    select @CustomerAddress = (c.CompanyName + ' ' +
                               c.Address + ' ' +
                               c.City + ' ' +
                               c.StateOrRegion + ' ' +
                               c.PostalCode + ' ' +
                               c.CustomerID
                              )
    from Customers c
    where c.CustomerID = @CustomerID;

    Return @CustomerAddress;
End;

This assumes that you actually want all the fields with some separator.
However, I don't think this is the best way to get the functionality you want.  It is better to add a computed column to the table:
alter table Customers c
    add CustomerAddress as (<expression here>);

Comment: Nice! Thank you @Gordon Linoff
Comment: When I call the function, I still get an error:

Msg 4104, Level 16, State 1, Line 62
The multi-part identifier "dbo.udf_GetCustomerAddress" could not becbound.

I'm calling the function like this:
select dbo.udf_GetCustomerAddress 'company ID' as 'Company Address'

Any thoughts?
Comment: @user7879707 . . . You should ask another question and show how the function is being called.

Scalar function that returns Address


How to trigger an any aws resource based on creation of another aws resource?

Question: I am using cloudformation template to build a dynamo db ( see below), once the stack builds successfully, I would like to alert/notify/trigger another aws resource, like a lambda function or a step function or a aws data pipeline to start such that I can start populating the dynamo. what is the best way to trigger another process or aws resource once cloudformation stack creation is successful ?
<code>AWSTemplateFormatVersion: 2010-09-09
Description: AWS CloudFormation Template To Create a DynamoDB

Parameters:
  HashKeyElementName:
    Type: String
    Default: Id
    Description: Hash Key Name
  HashKeyElementType:
    Type: String
    Default: S
    Description: Hash Key Type
Resources:
  Table:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: MyTable
      AttributeDefinitions:
        -
          AttributeName: !Ref HashKeyElementName
          AttributeType: !Ref HashKeyElementType
      KeySchema:
        -
          AttributeName: !Ref HashKeyElementName
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
Outputs:
  MyTable:
    Description: Table Created using this template.
    Value: !Ref Table
</code>
Comment: https://stackoverflow.com/questions/70742972/can-cloudformation-trigger-event-after-creation-of-each-resource Does this answer your question?
Answer: You can setup SNS topic and a lambda function to get events from stack creation. An example of how to do it is given in AWS docs:

How can I receive an email alert when my AWS CloudFormation stack enters ROLLBACK_IN_PROGRESS status?

You would have to adapt the example and the lambda to suit your needs.


Can I fill and paint a split porch post or is replacement recommended?

Question: My wife and I both noticed this week that in the cold temperatures (northern Ohio) the wood on one of the columns on our front porch has split near the bottom, where it contacts concrete (see images below). The house was built in 1926 and very well maintained, though I know some exterior elements have been replaced over time.
My inclination is to wait for warmer weather, then patch it with Gorilla brand exterior wood filler, sand and paint. Thoughts on this approach? Is there anything else that I should be considering, including replacement of the column itself?
Answer: A split (check) in a heavy timber is not usually cause for concern, but in this case I suspect that the post may be showing signs of rot from long-term contact with concrete. It's probably not specifically related to the weather.
We seem to see multiple splits (some around the corner). There's also an apparent darkening of the wood. This suggests moisture and maybe decay.
At some point you'll probably want to replace the post, but if it's not very soft it's not urgent. When you do, put a pad of some inorganic, corrosion-resistant material under it. A block of synthetic decking, shaped to match the post or sized as an accent piece, could work well.
You'll need to determine whether the post bears weight. In modern homes the roof trusses are often self-supporting over a porch, but that may not be the case for you. If it is carrying weight, install a temporary post while you work.


Converting column of object type to pytorch tensor

Question: I am new to machine learning and python.
I am working on data which has 2 columns of object type and a large number of columns of float type.
For converting a float type columns to tensor, the below code works fine:
cont_cols = ['row_id', 'player1','player2','playervar_0','player_1']
conts = np.stack([train_df[col].values for col in cont_cols],1)
conts = torch.tensor(conts,dtype= torch.float)

But when I tried doing with object type data column as below:
    obj_cols = ['winner','team']
    objs = np.stack([train_df[col].values for col in obj_cols],1)
    objs = torch.tensor(objs, dtype= torch.float)

I am getting the error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[60], line 2
      1 objs = np.stack([train_df[col].values for col in obj_cols],1)
----> 2 objs = torch.tensor(objs, dtype= torch.float)

TypeError: can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

I would be really great and kind help if someone can guide me on this.
Edit
To make the question more clear, column 'winner' contains winner, loser, draw, loser, winner, winner,draw,......
The column team contains team1, team2, team1, team1, team2,....
Edit2
I tried this approach. I think, this approach is fine? Please suggest some better approach?
 train_df['winner'] = train_df['winner'].map({'loser': 0, 'winner': 1, 'draw': 2})
    train_df['team'] = train_df['team'].map({'team1': 0, 'team2': 1})
    obj_cols = ['winner','team']
    objs = np.stack([train_df[col].values.tolist() for col in obj_cols],1)
    objs = torch.tensor(objs, dtype= torch.float)
    objs[:5]
    tensor([[1., 0.],
            [0., 1.],
            [0., 0.],
            [0., 1.],
            [2., 0.]])

Comment: Just a note: It would be great if you could provide an example of your data as a table next time :)
Answer:
To make the question more clear, column 'winner' contains winner, loser, draw, loser, winner, winner,draw,...... The column team contains team1, team2, team1, team1, team2,....

Your problem is that your data are strings (or "objects") that cannot be converted to a tensor directly.
You have to convert your unique string values into numbers somehow. You are on the right path regarding what you did in "Edit2" :)
If you want to preserve the labels of your columns, you could map the column to pandas.Categorical and then use the .codes attribute to get the integers for the tensor (see here), e.g.:

winner
team

loser
team1

winner
team2

draw
team1

winner
team1

df = pd.DataFrame({
    "winner": ["loser", "winner", "draw", "winner"],
    "team": ["team1", "team2", "team1", "team1"]
})
# you can control the order here, i.e. winner -> 0, loser -> 1, etc.
df["winner"] = pd.Categorical(df["winner"], ["winner", "loser", "draw"])
df["team"] = pd.Categorical(df["team"], ["team1", "team2"])

objs = np.stack([df[col].cat.codes for col in ["winner", "team"]],1)

# Output of objs:
# array([[1, 0],
#        [0, 1],
#        [2, 0],
#        [0, 0]], dtype=int8)

Or you can also simply use pandas.factorize() to get an integer  representation of you labels:
objs = np.stack([train_df[col].factorize().values for col in obj_cols],1)

Answer: Try this
obj_cols = ['winner','team']
objs = np.stack([train_df[col].values.tolist() for col in obj_cols],1)
objs = torch.tensor(objs, dtype= torch.float)

Comment: Thank you @Awal for the response. I am getting the error: TypeError: can't convert np.ndarray of type numpy.str_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.


What is this handleChange method doing?

Question: handleChange(e) {
        const index = Number(e.target.id.substring(e.target.id.length - 1, 19));
        const copyFormArray = JSON.parse(JSON.stringify(this.state.educationData));
        copyFormArray[index][e.target.name] = e.target.value;
        this.setState({
            educationData: copyFormArray,
        });
    };

What does this handleChange method do, specifically in the index variable? I understand what substring and the Number constructor do but the second argument I cannot find any answers for this specific question although it works as intended.
Comment: By second argument, are you referring to `19`?
Comment: @ÁlvaroTihanyi yes, the 19 in the substring method
Comment: That's the optional `indexEnd` parameter. Which according to [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) is _The index of the first character to exclude from the returned substring._
Comment: @ÁlvaroTihanyi In this case when the indexEnd is smaller than 10 it returns a typeerror that it cannot set the property of undefined, but when the indexEnd is excluded or > 10 it works.
Answer: Substring works in a tricky way, if second argument (in your case 19) is less than first argument - then they will be "swapped", and if not - it will just take text between indexes (argument1 and argument2).
So say for example i have a string:
var x = "aaaaa-5";

if i will write:
x.substring(x.length-1)

It will give me "5".
Then if i will write:
x.substring(3,6)

It will give me "aa-"
But then if i will write:
x.substring(6,3)

It will be exactly the same as previous call - "aa-"
So internally logic of substring is kind of like this:
function substring(start,end) {
 if(start > end) {
    var buf = end;
    end = start;
    start = buf;
 }
 //... other logic
}

Comment: I see, in this case when the indexEnd is smaller than 10 it returns a typeerror that it cannot set the property of undefined, but when the indexEnd is excluded or > 10 it works.
Comment: why 10? You mean 19? And you now go more specifically to logic and data that you have there, which i am not aware of
Comment: I was hacking with different numbers to try and understand why it is specifically 19. I was following a loose tutorial and the method wasn't explained so I'm trying to breakdown this part. Anyways appreciate it.
Comment: I guess in your case 19 should have been at the beginning (first argument), that's were confusion came from i guess

What is this handleChange method doing?


Is there a System Restore in Ubuntu Server?

Question: I'm thinking about installing the desktop on my Ubuntu Server (sudo apt-get install ubuntu-desktop).
Is there a "system restore" I can run in case I don't want the desktop anymore?
Comment: That's what we call a `backup` ;-)
Comment: I see you can use `Déjà Dup` (http://www.howtogeek.com/108869/how-to-back-up-ubuntu-the-easy-way-with-dj-dup/) but what option is there for the server? This looks like it is used on the desktop version.
Answer: No, but you can just apt-get remove ubuntu-desktop and apt-get autoremove to clean up the dependencies.
Comment: You may want to expand this to explain how this will only work if *nothing* has been manually installed (or marked as manually installed) that depends on `ubuntu-desktop`, since `ubuntu-desktop` was installed. Furthermore, anything that's been installed manually that depends on something that was installed automatically as a dependency of `ubuntu-desktop` may prevent large amounts of software from being autoremoved. There's a reason techniques [like this](http://psychocats.net/ubuntu/pureubuntu) have been developed. (Please note *that* won't solve *this* problem; it's for a similar problem.)
Comment: @EliahKagan, huh?  It will work just fine; it will just remove whatever you installed that depends on the desktop.