Q:

Understanding the PDF DOM

I am writing an application that has to read and interpret data stored in some PDF files. The reading part is done but I am only able to get a dump of all the words on a page and not the format of the words. What I mean is that if I have to extract a table, I am getting the numbers in the table but not the markup which defines the table.
Further, there is some formatting used which displays a few of these numbers within parentheses (meaning that those numbers are negative) but the parentheses themselves are not part of the text. Hence, I am not able to distinguish between positive and negative numbers present in the PDF table!
How do you get the PDF markup along with the text? Is a PDF similar in structure to an XML with tags used to markup tables etc.? If not, then, is there a resource which describes the salient features of the PDF DOM?
I am using VBA and the Acrobat library (AcroExch etc.)

A:

There is no such thing as "PDF markup" in the sense of HTML etc. A table in PDF cannot be distinguished from line art, other than by using OCR, which can be error-prone if the layout is complex. It is simply drawn using geometrical shapes, like in a vector-based graphics program.

A:

"Is a PDF similar in structure to an XML with tags used to markup tables etc.?"
No, not at all.
And there is no such thing as a 'DOM' either. Google for a file named *PDF32000_2008.pdf*. The current PDF specification for v1.7 (ISO spec) is that file. You should be able to locate it on the Adobe website.


Q:

Variable as the property name in a JavaScript object literal?

Possible Duplicate:
How do I add a property to a Javascript Object using a variable as the name?
Use variable for property name in JavaScript literal?

Is it possible to add a variable as the property name of an object in JavaScript, like this:
var myVar = "name";
var myObject = {
    {myVar}: "value"
};

A:

You can use the [] syntax to use an expression as the property name (compared to the .prop and prop: value syntaxes where they are always treated as strings):
var myObject = {};
var myVar = "name";
myObject[myVar] = "value";

There is no way to use that inside an object literal, though. You have to create the object first and then assign each property separately.

Edit
With ES6, this is now possible using a ComputedPropertyName, which manifests in the form of the following syntax:
var myVar = "name";
var myObject = {
    [myVar]: "value"
};

A:

Like this?
var myVar = "name";
var myObject = {};

myObject[myVar] = "value";

A:

Yes, but not directly.
var myVar = "name";
var object = {};
object[myVar] = "value";


Q:

How to store date string in Django model with MySQL?

I have a date as String s_date '07/20/2015'.
I need to store this date in Django model with MySQL.
How can I do that?
Suppose I have model Project and a dateField startingdate
new_project = Project()
new_project.startingdate = s_date

or
date = deadline.split('/')
year = date[2]
month = date[0]
day = date[1]
new_project.starting = datetime.date(year, month, day)

A:

Use strptime to parse date-strings:
>>> datetime.datetime.strptime('07/20/2015', '%m/%d/%Y')
datetime.datetime(2015, 7, 20, 0, 0)

If you want a date object, do this:
>>> datetime.datetime.strptime('07/20/2015', '%m/%d/%Y').date()
datetime.date(2015, 7, 20)


Q:

How to split a data layer and business object layer, what are the appropriate duties of each?

If there was a line of business application layered like this, would this be an appropriate division of labor :
Data Access

Invokes only stored procedures, maps properties of DTOs to a hash tablse which are used to populate ADO.NET command's parameter collections.
Only assembly with reference to SqlDataClient.
Significant logic dealing with what means blank, null, and empty in the mapping code, but other wise no validation or other domain specific logic.

So-Called Business Logic

splits multiple result sets into individual DataTables, e.g.
public void ReturnNthRecordSetFromStoredProcFoo()
pass through to data access for datasets, e.g.
public void ReturnDataSet(string name){
           return (new PersonController).GetAnotherDataSet(name);}
maps one row of a DataTable to one DTOs
Significant logic dealing with what means blank, null, and empty in the mapping code.
Holds transaction object, although it is used exclusively to wrap single stored procedure calls.
Doesn't have a reference to SqlDataClient, so it can't use SqlDataReaders to fill DTOs
No reference to System.Web.UI
Authorization rules, but otherwise no domain specific logic.

UI

2 way data binding of DTOs to ASP.NET forms.
Validation of properties of controls- generally no validation directly against DTOs
"Collections" are navigated by binding DataSets to grids.  In fact attempting to do anything with collections requires the UI to iterate over DataRows in DataTables and know what the appropriate column names are (which are generally only kind-of-similar to the DTOs)

So the question, finally-- with this application, should the Data Access Layer assume the the duties of the so-called business layer be merged?  Isn't this already a two layer, (almost one!) application except for the inconvenience of an extra assembly?
Additional info: Ok, I already know that the application server will be one machine, probably forever, since it is an low-user-count intranet app.  So I know not to design for physically separate application tiers.  Also, it will probably only support one UI and be entirely scrapped if it ever need to support something other than ASP.NET-- another oft quoted reason for tiers/layers.

A:

Depending on your server load should determine the number of physical layers.  The number of logical layers is really more of a personal choice.
In our organization we use the CSLA framework.  It is a business object framework that strives to make rich, databound UIs simple to use and maintain, while giving flexibility in the data layer.
I wont go into too much depth here as it would be better for you to determine for yourself if the framework is worth it for you to use, but needless to say, it has its own SafeDataReader class which accounts for nulls, eliminating the need to use datasets.
Its "dataportal" (article is older but still relevant) allows you to easily move the data access to its own layer with very little effort, and no change of code.
DNRtv has a few video pod casts in which the designer of CSLA, Rockford Lhotka, shows the workings of the sample application. Part 1 and Part 2.
The shows are only an hour each and can probably help you decide if its the right thing for you to use.

A:

It sounds to me that the responsibility between tiers is a little muddled.  The data layer sounds fairly standard.  The ("so-called") business layer is the place where things get muddled.
Some thoughts on the Business Layer:

There seems to be a lot of data representations.  You mention DataTables, DataSets, Data Transfer Objects.  A standard approach across the entire application would be better.
Business layer methods with names like ReturnNthRecordSetFromStoredProcFoo and ReturnDataSet are not meaningful and do not provide an appropriate level of abstraction for business services.  (Maybe those were just poorly chosen examples not from the application?)
Typically a business layer would provide more than a DataSet pass through.  Instead of dealing with mappings, nulls etc. the business layer should focus on validation, business rules, security, and maybe even auditing (although some prefer to do that in the database).
Even though the business layer is only invoking a single stored procedure, I have no problem with the transaction control in the business layer.  Business layer should control the transaction so that multiple data objects can all participate in the same transaction (it could even be across different databases).  Even though there is only one call now, if you ever need to add more calls in the future this will be easy and will not result in retrofitting transaction control into your application.
I think the dependencies are OK -- no reference to the Web.UI or SQLClient from the business layer.
Authorization rules are also OK.  I would expand to include Security and not just authorization.  Also, I don't see any business logic anywhere -- just curious if the business logic is in the stored procedures?  If I was going to guess, I would say yes given that each business method invokes only one stored procedure.  If so, then that is a big no no for me.

I would not combine the business and data layers.  I prefer to keep the business logic layer and the data access layer separate.  Given a choice between combining them and trying to separate the responsibilities a little more I would lean toward the latter.
However, seeing as though this is an existing application with issues I would take a more pragmatic point of view.  Everything comes with a cost and it is important to determine what changes are being made, what is the effort and risk of the changes, what is the real benefit of the changes, and how the changes will impact on the testing cycle.
Some other questions to think about are: what are the main issues you want to address?  Are they functional (e.g. bugs, lack of stability)?  Or performance related?  Or is it architectural?  Or perhaps related to maintainability -- do you need to add new functionality but are finding it difficult?  Do you have a time frame or a budget?  If you can answer some of those questions it might help guide you.


Q:

Binding Label content to Self string field but no result

I'm trying what should be an easy bind in my user control:
<UserControl x:Class="MyApp.FlowNode" ...>
    <StackPanel>
        <Label Content="{Binding Path=Header, RelativeSource={RelativeSource Self}}" />
    </StackPanel>
</UserControl>

With the underlying code being:
public partial class FlowNode : UserControl
{
    public FlowNode()
    {
        InitializeComponent();
    }

    public string Header { get { return "Testing"; } };
}

However, the label stays blank. What am I doing wrong?

A:

Try to use
{Binding Path=Header, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type FlowNode}}}.


Q:

Why are GPAs calculated the way they are?

At most schools an A is a 4.0, an A- is a 3.7, and so on. I feel like this system is not really representative of a person's true skill. For example, a person who got a 100% in a class will get the same GPA as a person who got a 94% in the class. However, a person who gets a 91% in a class will get a significantly higher GPA than someone who got an 89%. Why don't schools base GPA off the actual percentage that someone gets in a class instead of their letter grades?

A:

The big reason: exact numerical scores are not comparable across classes and professors.
Suppose I told you that two students took a class offered in different semesters. We look at their transcript and see that student A scored a 94% with Professor X and Student B scored a 99% with Professor Y. Student B beat out the first person by five percentage points, but do we actually know that Student B is a better student? Maybe Professor Y is a soft grader or Professor X had a really harsh curve that semester. We don't really know whether Student B is better. All we really know is that both students did pretty well.
Hence, grades tend to be assigned and interpreted with a large degree of subjectivity, which fits the ABCDF model better than a score-based model. The general interpretation is:
A - excellent
B - good
C - average
D - needs improvement
F - failing

If the first and second student both get A's, then this means that an expert in their fields (the professors) have said that both students did excellent. This isn't a perfect system, but it is about as good a comparison as you can get.

A:

At most schools an A is a 4.0, an A- is a 3.7, and so on.

This is true at most American colleges and universities, yes.  (It's not true in most of the rest of the world, and the discrepancy is an issue when one wants to compare students from different countries, e.g. in graduate admissions.)

I feel like this system is not really representative of a person's true skill.

I have given out hundreds of grades in university courses, and I make no claim that a student's course grade is "really representative of their true skill."  For instance, it has happened that I wrote grad school letters for an A- student and an A student for whom my primary interaction was teaching them the same course and that I wrote an overall stronger letter for the A- student: based on my interactions with him, I felt that his true skill was higher, whereas the A student did noticeably better on the midterm and the final (though both did very well).

For example, a person who got a 100% in a class will get the same GPA as a person who got a 94% in the class.

There seems to be a premise of this question that universities use standard "letter grade cutoffs."  This is really not always true (though it is sometimes true, and it would be interesting to understand this better).  These cutoffs have not been applied at any of the universities I've been affiliated with as a student or instructor: University of Chicago, Harvard, McGill, University of Georgia.  (See e.g. Question 12 here.) To be honest -- and in part because my own experience with American universities, though quite temporally extensive, is far from universal and probably even from generic -- such talk reminds me of high school, and I get surprised when university students think too seriously about it.  (And this sometimes includes my own university students!)  In the STEM fields in particular, it is common for exams to be written in such a way that a 50% grade would be a clear A and a 90% grade would be preposterous.
Let me say though that I have not seen it go the other way: in any class I have ever taken or taught: yes, 94% is worth the same letter grade as 100%.  One could go on at great length about this, but for now let me say: I see nothing inherently problematic here from anyone's perspective.
Rather I would like to call attention to the fact that there is a mistake above: students who get a 100% and a 94% will probably get the same course grade.  GPA means grade point average.  This error becomes more clear as follows:

However, a person who gets a 91% in a class will get a significantly higher GPA than someone who got an 89%.

No, this is really not the case.  The typical American university student takes about 40 courses overall.  So a student who gets A's in all but one course and fails the other course will have a GPA of (39*4 + 1*0)/40 = 39*4/40 = 3.9.  If that student got at least a C+ instead of an F, their GPA rounded to one decimal place would be 4.0.  In fact, my undergraduate GPA rounded to one decimal place was 4.0, though I remember well the course in which I received a B (the first graduate course I took) and more vaguely that I got less than A grades in at least two other courses.  (Because culturally speaking a "4.0 GPA" generally implies all A's, I reported my GPA to two decimal places.)
This is, I think, a really key point: the inference of skill and achievement from course grades is a statistical process, and like most statistical processes, investing too much meaning in any one data point is dubious.  I am currently directing graduate admission in the math department at UGA.  There are occasions when individual course grades are meaningful to us: a student who has generally good grades but quite poor ones in two or three key courses that are the most foundational to graduate success is viewed negatively beyond the influence of the GPA (and this of course is why we do not just look at GPAs but get much more information, including full transcripts and lists of textbooks from the courses taken in the major).  But for one of these key courses -- say real analysis -- what if one student gets a B+ and another gets an A-?  Then we really don't care, and if we don't care, I'm not sure who would.
Let me finally make a few more remarks about the system of letter grades at universities.

There is nothing especially clever or apt about it.  Another answer claims that we have the system basically due to historical inertia.  The answer goes on to say some other things that I disagree with, but I certainly do agree with this.  It is easy to pick apart the particulars of the system -- why no E? why no A+? [or if you do have an A+ -- as some universities do -- how do you figure that into the GPA?] Why pluses and minuses at all?  (In fact, UGA had no plus/minus grades for many years, and the aforelinked FAQ is in fact an FAQ about the use of plus/minus grading!)  Most importantly Why choose the same grading scale as is used in K-12 education, so that students will come to college/university with many preconceived notions about how grades will be assigned that they will gradually find out can be quite inaccurate?
A wider range of grades is not necessarily "better" or "more accurate."  You hear a lot about grade inflation, and it is interesting that the language subtly conveys that it is somehow a problem.  It is much more interesting to try to explain why it's a problem.  One argument advanced along those lines is that it blurs distinctions between academic achievements.  My colleague Jordan Ellenberg wrote a nice article demolishing this argument some years ago.  The main idea is the one I gave above: students are taking a large number of courses.  We could have just two possible grades, "excellent" and "very good," and as along as instructors assign the "very good" grade to students in a broad enough set of circumstances, over time the magic of probability and statistics will serve to separate the students.  In fact I think I would prefer a grading scale that has fewer grades and that is not reminiscent of high school grading.  For me a very natural scale would be one that has three grades: the lowest one is given to students who have not met (sufficiently many) clearly defined course objectives.  It would roughly correspond to the "F" in the current system, but it should be given for failure to meet objectives, not for a numerical score in a certain range or for the bottom X% of the class.  The top grade should be given to students who excelled in the course in some meaningful way (not for a numerical score in....).  The middle grade should be given to everyone else.  I think that such a system would lose little or no information from the present one, and more to the point, it is to a large degree how I think about letter grades as given.
I admit that it is entirely debatable, but I actually feel that it would be a net negative to record percentage grades in transcripts rather than to "discretize" as is currently done.  If you're a young student, then maybe you're proud of your 98% and want it to be recognized as better than your colleague's 94%.  But a context in which students are fighting over that 4% is not necessarily conducive to better learning.  For me, this situation conveys strong memories of high school, in which our (weighted) percentage scores in each course were used to compute our class rank.  This led to a cohort of students who were highly motivated to get the highest possible scores on every exam.  I remember students studying for several more hours in order to make sure they had memorized 100% of the material instead of 97% of it.  But this memory space was relatively short term: it would have to be vacated for the next course, if not the next exam.  These bright young people could have used this time in more valuable ways, academically and otherwise.  By the way, the grapes may be sour but perhaps not in the way you'd expect: I was the valedictorian (i.e, class rank 1) of my high school class.  At the time I had the suspicion that this achievement was less significant than it was being made out to be.  Looking back from the middle of an academic career I can now confirm this.  University students are significantly more grade-conscious than is beneficial to them in any way, including academically.  Blurring the distinction between 98% and 94% seems quite healthy.


Q:

yoga 2 pro won't boot after update to ubuntu 15.10/ GDM

After upgrading to Ubuntu 15.10, my mouse pointer was no longer visible. As a remedy, I installed GDM as suggested in some posts here. That worked, but now (first full boot after installation of gdm) the laptop stopped showing the login screen, showing this instead:

Edit: using ctrl-alt-f1, I am able to enter a terminal and try stuff out in tty1.
Edit2: internet access seems to work too.
Edit3: sudo apt-get updating and upgrading install stuff, but nothing that makes the problem go away.
Edit4: part of some graphical interface is loaded, as the Ubuntu shutdown screen is shown on reboot -n
Edit5: removing gdm and rebooting got me a new problem with this startup screen message . Here I can ctrl-alt-f1, log in, and sudo lightdm to enter the graphical interface. However, now I am constantly asked for my password. Not sure why. Also, sound is not working. Any help greatly appreciated.
Edit6: trying to install new kernel didn't solve the problem. Removed gdm and using lightdm instead solved all of the booting problems. But the cursor is still invisible.
At least that's consistent

A:

step 1
First I reverted to lightdm. If you never installed gdm you can skip this step. This sounds straightforward but it's not, as you need to use gdm to select lightdm as the default before removing gdm. So:
CTRL-ALT-F1
log in
sudo apt-get install --reinstall gdm
select lightdm as the default window manager
sudo apt-get remove gdm
restart for good measure.
step 2
If it doesn't work still:
CTRL-ALT-F1
log in
sudo apt-get install ubuntu-session (reinstall if you have to)
This
solved it for me.
Why you ask? No idea. Your mileage may vary.
Update
My mileage did vary, after an update I was back to square one. I noticed some inconsistencies too, so I decided to use
sudo apt-get update
sudo apt-get install --reinstall ubuntu-desktop
sudo apt-get install --reinstall unity

And it seems to be working again. For now.


Q:

Como usar REST para validar o recebimento de XML via POST

Eu tenho uma aplicação em Delphi que envia um XML com um código via Post. Eu tenho que desenvolver uma aplicação em Symfony que precisa validar o recebimento desse XML via post. Ouvir dizer que seria via Rest mas eu nunca usei Rest.
Gostaria de uma orientação ou orientação para Symfony 3 e de preferência em português.

A:

Meu caro, nesse caso não tem uma receita de bolo, o ideal é que você vá até a documentação do Symfony (https://symfony.com/doc/current/index.html) e dê uma olhada no que o framework disponibiliza para você.
Como no seu caso é um API REST, recomendo fortemente o uso do micro-framework baseado em Symfony chamado Silex (http://silex.sensiolabs.org/). Por se tratar de um micro-framework, ele é bem mais enxuto, trazendo o essencial para se construir um API Rest com um stack poderoso.
Obs: Os links estão em inglês, mas não tem como fugir disso. Boa sorte!

A:

Sua pergunta é bastante ampla, então vou explicar "por cima" o que você pode fazer, se a ideia é realmente utilizar Symfony 3:

crie seu projeto Symfony 3 com o comando composer create-project symfony/framework-standard-edition <nome-do-projeto>; isso criará um projeto com diversas dependências básicas para a maioria dos projetos web (Doctrine, Swiftmailer, Twig etc);
crie uma classe AppBundle\Entity\Data com os dados que você irá receber (coloquei um exemplo mais abaixo);
modifique a única rota para receber os dados da requisição e mapeá-los para a classe criada acima.
Habilite o serviço serializer em seu config.yml (exemplo abaixo);
rode seu projeto com o comando bin/console server:start
teste a rota com uma requisição POST por meio do HTTPie: echo '<data><tag>oi</tag></data>' | http 127.0.0.1:8000/

Arquivo config.yml:
framework:
    serializer:
        enabled: true

(ps: não é necessário excluir todas as configurações da chave framework, apenas adicione a configuração do serializer).
Classe AppBundle\Controller\DefaultController:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Data;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Serializer\SerializerInterface;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $data = $this->getSerializer()->deserialize($request->getContent(), Data::class, 'xml');
        print_r($data); die;
    }

    /**
     * @return SerializerInterface
     */
    private function getSerializer()
    {
        return $this->get('serializer');
    }
}

Classe AppBundle\Entity\Data:
<?php

namespace AppBundle\Entity;

class Data
{
    public $tag;
}

Se tudo deu certo, você terá uma instância da classe AppBundle\Entity\Data preenchida com os dados recebidos via POST:
HTTP/1.1 200 OK
Connection: close
Content-type: text/html; charset=UTF-8
Host: 127.0.0.1:8000
X-Powered-By: PHP/5.6.22

AppBundle\Entity\Data Object
(
    [tag] => oi
)


Q:

Android Parse JSON String for Listview within View Flipper

I'm just trying to parse a simple JSON string in the following format: ["X","Y","Z"] and put it into a listview. The listview is within a view flipper in order to have tabs visible at all times throughout the app.
The problem i'm having is the app is stopping unexpectedly, here is the full code for the main launching activity:
public class Activity extends TabActivity implements OnClickListener {

Button doSomething;
TabHost tabHost;
ViewFlipper flipper;
ListView listview;
HttpResponse re;
String json;
JSONObject j;

@SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.tablayout_1);

    doSomething = (Button) findViewById(R.id.btn_do_something);
    doSomething.setOnClickListener(this);

    flipper = (ViewFlipper) findViewById(R.id.layout_tab_one);

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

   //@SuppressWarnings("unchecked")
   ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,this.fetch());

   listview.setAdapter(adapter);

    flipper.setOnClickListener(this);

    String tabname1 = getString(R.string.tabexample_tab1);
    String tabname2 = getString(R.string.tabexample_tab2);
    String tabname3 = getString(R.string.tabexample_tab3);
    String tabname4 = getString(R.string.tabexample_tab4);

    tabHost = getTabHost();
    tabHost.addTab(tabHost.newTabSpec("tab1").setContent(R.id.layout_tab_one).setIndicator(tabname1));
    tabHost.addTab(tabHost.newTabSpec("tab2").setContent(R.id.layout_tab_two).setIndicator(tabname2));
    tabHost.addTab(tabHost.newTabSpec("tab3").setContent(R.id.layout_tab_three).setIndicator(tabname3));
    tabHost.addTab(tabHost.newTabSpec("tab4").setContent(R.id.layout_tab_four).setIndicator(tabname4));

    tabHost.setCurrentTab(0);

    listview.setOnItemClickListener(new OnItemClickListener(){
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
             flipper.showNext();

        }});

}

public ArrayList<String> fetch()
{
    ArrayList<String> listItems = new ArrayList<String>();

    try {
        URL twitter = new URL(
                "JSON.php");
        URLConnection tc = twitter.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                tc.getInputStream()));

        String line;

        while ((line = in.readLine()) != null) {

      //make sure youe String line is completely filled after that..
      if (!line.equals(null) && !line.equals("") && line.startsWith("["))
       {
      JSONArray jArray = new JSONArray(line);
      for (int i = 0; i < jArray.length(); i++)
       {
          JSONObject jobj = jArray.getJSONObject(i);
         // also make sure you get the value from the jsonObject using some key
         // like, jobj.getString("country");

         listItems.add(jobj.getString(""));
       }
          }

        }

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return listItems;
}

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub

}

}

Log output:
    08-25 19:29:48.544: DEBUG/AndroidRuntime(850): Shutting down VM
08-25 19:29:48.544: WARN/dalvikvm(850): threadid=1: thread exiting with uncaught exception (group=0x40014760)
08-25 19:29:48.564: ERROR/AndroidRuntime(850): FATAL EXCEPTION: main
08-25 19:29:48.564: ERROR/AndroidRuntime(850): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.android/com.app.android.Activity}: android.os.NetworkOnMainThreadException
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.app.ActivityThread.access$500(ActivityThread.java:122)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.os.Looper.loop(Looper.java:132)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.app.ActivityThread.main(ActivityThread.java:4123)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at java.lang.reflect.Method.invokeNative(Native Method)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at java.lang.reflect.Method.invoke(Method.java:491)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at dalvik.system.NativeStart.main(Native Method)
08-25 19:29:48.564: ERROR/AndroidRuntime(850): Caused by: android.os.NetworkOnMainThreadException
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at java.net.InetAddress.lookupHostByName(InetAddress.java:477)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at java.net.InetAddress.getAllByName(InetAddress.java:249)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:304)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:292)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:274)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1038)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:523)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at com.android.Activity.fetch(Activity.java:193)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at com.android.Activity.onCreate(Activity.java:144)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.app.Activity.performCreate(Activity.java:4397)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
08-25 19:29:48.564: ERROR/AndroidRuntime(850):     at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
    08-25 19:29:48.564: ERROR/AndroidRuntime(850):     ... 11 more

Ok the app is launching now but the listview is not being populated with the JSON Strings for some reason?

A:

Your app is throwing a NetworkOnMainThreadException, and the documentation says this about it:

The exception that is thrown when an application attempts to perform a
  networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or
  higher. Applications targeting earlier SDK versions are allowed to do
  networking on their main event loop threads, but it's heavily
  discouraged.

Looking at your code, you call fetch() in your onCreate(), which runs on the UI Thread.  You will need to do this in a background thread (or target an SDK version less than Honeycomb).  Take a look at AsyncTask for some more info on this solution.
 ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,this.fetch());


Q:

Swap specific chars in python

How can I swap characters in a string in Python?
For example:
text = 'gghghg didjf ekofrhhwehg'

I want to swap all of the 'g' in the text for 'k'.
Would I use ord() and chr() functions?
Update:
When i run this code:
text = 'gghghg didjf ekofrhhwehg'
text.replace("g", "k")

print text

It doesnt change the output

A:

You can simply use, str.replace, like this
>>> text = 'gghghg didjf ekofrhhwehg'
>>> text.replace("g", "k")
kkhkhk didjf ekofrhhwehk

Alternatively, you can create a translation table and use str.translate, like this
>>> from string import maketrans
>>> text.translate(maketrans("g", "k"))
kkhkhk didjf ekofrhhwehk

Note: If you actually meant swapping all gs with ks and vice-versa then you should use str.translate, like this
>>> from string import maketrans
>>> 'gluke'.translate(maketrans("gk", "kg"))
kluge

See how g in gluke changed to k and k in gluke changed to g, in the result.

About your edit, Python Strings are immutables. So once you create a String object, you can never change its value. You just have to create a new one. So, assign the result of text.replace back to text, like this
>>> text = 'gghghg didjf ekofrhhwehg'
>>> text = text.replace("g", "k")
>>> text
kkhkhk didjf ekofrhhwehk


Q:

Security challenges of administrative share in windows 7

I am going to the network+ class, and today my teacher said that every time you want to configure a network, disable the hidden share of hard drives in windows. He said that if this is enabled, you will be hacked very easily. Is that correct while anyone who want to access shared drives must has the administrator permission?
And also as I searched, to disable this configuration permanently I have to disable the administrative share completely. What problems may happen if this feature is disabled?
Thanks.

A:

Admin shares only permit access over the network to users that are members of the computer's local Administrators group. You can disable them by configuring the AutoShareServer (for server OS) or AutoShareWks (for non-server OS) registry values:
Hive: HKEY_LOCAL_MACHINE
Subkey: System\CurrentControlSet\Services\LanmanServer\Parameters
Value name: AutoShareServer (server OS) or AutoShareWks (for non-server OS)
Value data: 0
Value type: REG_DWORD
(See https://support.microsoft.com/en-us/kb/288164)
There may be negative implications for disabling them--see https://support.microsoft.com/en-us/kb/842715.
Your teacher may be misunderstanding the scope of this feature. As noted, the admin shares are only accessible to members of Administrators (hence the name). If someone is a member of Administrators that is not supposed to be a member of Administrators, they already have the highest level of access anyway. Another way to say this: Disabling the admin shares doesn't prevent hacking; if a hacker can access them, you've been hacked already.


Q:

Convert stash to working change delimited by #ifdef SYM

I have a set of changes in stash@{4} that I would like to apply, but in such a way that the changes are merged into the working copy (or else a new commit) such that either version can be selected by a preprocessor symbol.
(This is a feature of the GNU diff and diff3 programs: see the --ifdef option.)
For instance a hunk like
@@ -123,7 +123,7 @@
 a
 b
 c
-foo
+bar
 d
 e
 f

is actually applied to the working file as
a
b
c
#ifdef SYM
bar
#else
foo
#endif
d
e
f

If SYM is defined, the text corresponds to the patched version, whereas if it is not defined, the text expands to the base version.
Perhaps this can be done with git merge, somehow telling git to use diff3 --ifdef=SYM for merging?

A:

The obvious just struck me: patch has an --ifdef/-D option as well.
git stash show -p stash@{4} | patch -p1 -D SYMBOL

Done!


Q:

Add a file-download widget on a form

I have a file field called "contracts" between my user fields.
What I want is that in the user-profile form this field would come up as a file-download widget.
Does anyone have an idea how to show a file-download widget (even a link to a file would work) in the user-profile form?

A:

Assuming that Your Drupal 7 site is a new site (not upgraded from a D6 installation), I think the best approach is to use the Profile 2 module (dependent on Entity API) and add a file field to the user profile.


Q:

Pseudorandom Number Generator - Exponential Distribution

I would like to generate some pseudorandom numbers and up until now I've been very content with the .Net library's Random.Next(int min, int max) function.  PRNGs of this variety are supposed to be using a Uniform distribution, but I would very much like to generate some numbers using an Exponential Distribution.
I'm programming in C#, although I'll accept pseudocode or C++, Java or the like.
Any suggestions / code snippets / algorithms / thoughts?

A:

Since you have access to a uniform random number generator, generating a random number distributed with other distribution whose CDF you know is easy using the inversion method.
So, generate a uniform random number, u, in [0,1), then calculate x by:
x = log(1-u)/(-λ),
where λ is the rate parameter of the exponential distribution.  Now, x is a random number with an exponential distribution.  Note that log above is ln, the natural logarithm.

A:

The Fundamental Theorem of Sampling holds that if you can normalize, integrate and invert the desired distribution you are home free.
If you have a desired distribution F(x) normalized on [a,b]. You compute
C(y) = \int_a^y F(x) dx

invert that to get C^{-1}, throw z uniformly on [0,1) and find
x_i = C^{-1}(z_i)

which will have the desired distribution.

In your case: F(x) = ke^{-kx} and I will assume that you want [0,infinity]. We get :
C(y) = 1 - e^{-ky}

which is invertable to give
x = -1/k  ln(1 - z)

for z thrown uniformly on [0,1).

But, frankly, using a well debugged library is smarter unless you're doing this for your own edification.

A:

If you want good random numbers, consider linking to the gsl routines: http://www.gnu.org/software/gsl/. They have the routine gsl_ran_exponential. If you want to generate random numbers using a built-in generator with a uniform distribution on [0, 1) (e.g. u=Random.Next(0, N-1)/N, for some large N), then just use:
-mu * log (1-u)

See randist/exponential.c in the gsl source.
EDIT: just for comparison with some later answers - this is equivalent with mu = 1/lambda. mu here is the mean of the distribution, also called the scale parameter on the wikipedia page the OP linked to, and lambda is the rate parameter.


Q:

Backspace strange behaviour when word selected and cursor after open parenthesis

I got a strange issue when I hit backspace while some text is selected and my cursor is close to an open parenthesis, example:
b(aaa)

If I select aaa and my cursor is on the first a, I would like the full aaa string to be removed when I hit backspace. In other words I want this:
b()

But I get that:
b)^?

where ^? is in a different colour (may be a special character).
I suppose that the problem may come from some options or plug-in that I have like the fact that peered parenthesis are highlighted when the cursor is on it, or the command M-<dir> that move the cursor to the other parenthesis... I don't know.
Problem is the same whit " peers symbols or any peers symbols regarding the language that emacs detect. For example in C the problem is present with (``"``{ etc...
Any ideas?
EDIT:
Problem is the same with
vi(is better)

If I want to delete both words in the parenthesis

A:

The problem come from the autopair-mode package.
Disable it :
M-x autopair-mode
Enable electric-pair-mode instead which do almost the same thing :
M-x electric-pair-mode
If all this is in init file, to clear it, remove or comment
(load "autopair.el")
(require 'autopair)
(autopair-global-mode)

from your init file, and add
(electric-pair-mode t)

Solution provided by Lizardo Reyna in comment above


Q:

Polynomial Divisibilty Test

I recently came across a question in a book and I was wondering how to go about solving this. I just need a hint about how I could approach it.
I have to show that $x^{6n+2} - x^{6n+1} + 1$  is always divisible by $x^2 - x + 1$ where $n = \{1,2,3,4,\cdots\}$

A:

Let $\alpha,\beta$ be two (complex) roots of $x^2-x+1$. Then $x^2-x+1=(x-\alpha)(x-\beta)$. Note that $x^2-x+1$ divides $x^3+1=(x+1)(x^2-x+1)$, and hence also $x^6-1=(x^3-1)(x^3+1)$. So both $\alpha,\beta$ satisfy $x^6=1$. Thus we have $\alpha^{6n+2}-\alpha^{6n+1}+1=(\alpha^6)^n\cdot\alpha^2-(\alpha^6)^n\cdot\alpha+1=\alpha^2-\alpha+1=0$, and same for $\beta$. So both $\alpha,\beta$ are roots of $x^{6n+2}-x^{6n+1}+1$. So $x-\alpha,x-\beta$ divide $x^{6n+2}-x^{6n+1}+1$, so also $(x-\alpha)(x-\beta)=x^2-x+1$ divides $x^{6n+2}-x^{6n+1}+1$.


Q:

Chromecast can't load mp3?

I've an issue with a Chromecast app I'm working on. It's an app for Chrome (not for iOS or Android).
I can't figure out why mp3 files aren't loaded by my chromecast device while mp4 are (for the record, I'm using the default receiver).
I based my work on this official sample : https://github.com/googlecast/CastVideos-chrome
Here you can see the code : http://pastebin.com/nJGeT7xP
Here is how I send the mp3 file :
if (session) {
  var mediaInfo = new chrome.cast.media.MediaInfo("http://localhost/tom_www/CastTom/music.mp3", "audio/mpeg");
  var request = new chrome.cast.media.LoadRequest(mediaInfo);
  session.loadMedia(
    request,
    onMediaDiscovered.bind(this, 'loadMedia'),
    onMediaError
  );
} else {
  console.log("No session available, connect first");
}

I hope you can help me.
Thank you.

A:

You will need to put the mp3 in a location accessible to the chromecast.  You can do this by getting the the ipaddress of your chrome device to send to the chromecast or placing the mp3 on a publicly accessible server.


Q:

Compute integral $\int_{-\infty}^{\infty}\frac{e^{-ixt}}{\sqrt{1+x^2}} dx$

How to compute integral $\int_{-\infty}^{\infty}\frac{e^{-ixt}}{\sqrt{1+x^2}}dx$, which is the Fourier transform of $f(x)= \frac{1}{\sqrt{1+x^2}}$?
We already know that we can get the Fourier transform of $\frac{1}{(1+x^2)^2}$ by using the convolution theorem linked-to result.\
Now the question is that can we apply the same for  $f(x)= \frac{1}{\sqrt{1+x^2}}$? And how?
Thanks!

A:

Yes, this integral may be done using complex analysis.  Sort of.  What we end up with are two different representations of a modified Bessel function.  That said, the complex analysis route results in a transformation of the oscillatory Fourier integral - which is harder to compute - into a very quickly convergent integral representation.
Consider the contour intgeral
$$\oint_C dz \frac{e^{i t z}}{\sqrt{1+z^2}} $$
where $C$ is the following contour:

Note that the radius of the large circular arcs is $R$ and the small circle about the branch point at $z=i$ is $\epsilon$.  Note that we avoid crossing the branch cut along the imaginary axis.  By Cauchy's theorem, this contour integral is zero.  (Why?)  On the other hand, the contour integral is equal to, after parametrizing the various pieces:
$$\int_{-R}^R dx \frac{e^{i t x}}{\sqrt{1+x^2}} + i R \int_0^{\pi/2} d\theta \, e^{i \theta} \frac{e^{i t R e^{i \theta}}}{\sqrt{1+R^2 e^{i 2 \theta}}} \\ + i \int_R^{1+\epsilon} dy \, \frac{e^{-t y}}{i \sqrt{y^2-1}} + i \epsilon \int_{\pi/2}^{-3 \pi/2} d\phi \, e^{i \phi} \frac{e^{i t (i+\epsilon e^{i \phi})}}{\sqrt{1+(i+\epsilon e^{i \phi})^2}} \\ + i \int_{1+\epsilon}^R dy \, \frac{e^{-t y}}{-i \sqrt{y^2-1}}+ i R \int_{\pi/2}^{\pi} d\theta \, e^{i \theta} \frac{e^{i t R e^{i \theta}}}{\sqrt{1+R^2 e^{i 2 \theta}}}$$
We now consider the limits as $R \to \infty$ and $\epsilon \to 0$.  We first note that we may combine the second and sixth integrals and show that they vanish in this limit when $t \gt 0$.  Consider the absolute value of the combined integral and it is bounded from above as follows:
$$\frac{2 R}{\sqrt{R^2-1}} \int_0^{\pi/2} d\theta \, e^{-t R \sin{\theta}} \le \frac{2 R}{\sqrt{R^2-1}} \int_0^{\pi/2} d\theta \, e^{-2 t R \theta/\pi} \le \frac{\pi}{ t \sqrt{R^2-1}}$$
which clearly vanishes as $R \to \infty$.  It is straightforward to show that the fourth integral vanishes as $\epsilon \to 0$.  This, because the contour integral is zero, we are left with the following expression for the original Fourier integral:
$$\int_{-\infty}^{\infty} dx \, \frac{e^{i x t}}{\sqrt{1+x^2}} = 2 \int_1^{\infty} dy \, \frac{e^{-t y}}{\sqrt{y^2-1}} = 2 \int_0^{\infty} du \, e^{-t \cosh{u}}$$
The latter integral is $2 K_0(t)$.  That said, note that the integral we obtained is a far easier one to handle numerically if it came to it.  Accordingly, complex analysis is very useful in general for converting oscillatory Fourier integrals that are hard to evaluate numerically into exponential integrals that are very easy.
Note also that the above required $t \gt 0$.  When $t \lt 0$, we must use a different contour below the real axis, but the result is the same.  Therefore,

$$\int_{-\infty}^{\infty} dx \, \frac{e^{i x t}}{\sqrt{1+x^2}} = 2 K_0(|t|)$$

A:

$\frac{e^{-ixt}}{\sqrt{1+x^2}}$ does not belong to $L^1(\mathbb{R})$, but
$$ \lim_{M\to +\infty}\int_{-M}^{M}\frac{e^{-ixt}}{\sqrt{1+x^2}}\,dx =2\, K_0(|t|)$$
where $K_0$ is a modified Bessel function of the second kind (see eq 11). You can prove such identity by noticing that for $t>0$ both sides are solutions of the same differential equation.


Q:

PaperJS with html elements

I am trying to add a input box in specific points( onclick ). How can i do this. For better understanding please refer Fiddle here
And this is my code:
<script type="text/paperscript" canvas="canvas">
    var m=0;

    function onMouseDrag(event) {
    var path = new PointText({
                        point: event.point,
                        content: 'The contents of the point text',
                        fillColor: 'black',
                        fontSize: 25
                    });
    path.removeOnDrag();
    }

     function onMouseUp(event) {
        m++;
        var point = event.point;
        createInput(point);
    }

    function createInput(point){
            console.log(point);
        }
    </script>

A:

Here is the answer,
<input type="hidden" value="" id="x-text">
<input type="hidden" value="" id="y-text">
<input type="hidden" value="" id="content-text">

$("#canvas").click(function(e){
                        if(set==5){
                        var offset = $(this).offset();
                        $("#position").text((e.clientX - offset.left) + ", " + (e.clientY - offset.top));
                        $("#position").empty();
                        var input = $("<input type='text' value='' class='addtext' id='addText'>");
                        var save = $("<input type='button' class='save' value='save' id='save'>");
                        var discard = $("<input type='button' class='discard' value='discard' id='disc'>");
                        $("#position").append(input);
                        $("#position").append(save);
                        $("#position").append(discard);
                        $("#position").css('position', 'absolute');
                        $("#position").css('left', e.clientX - offset.left);
                        $("#position").css('top', e.clientY);
                        var xcor = $("#x-text");
                        var ycor = $("#y-text");
                        var ctext = $("#content-text");
                        var atext = $("#addText");
                        discard.click(function(){
                        $(this).parent().empty();
                        });
                        save.click(function(){
                            ctext.val(atext.val());
                            xcor.val(e.clientX - offset.left);
                            ycor.val(e.clientY);
                            $(this).parent().empty();

                        });
                    }
                });

Here is the paperJS onMouseMove() funciton
function onMouseMove(event){
                if(set == 5){
                document.getElementById('save').onclick = function (){
                    m++;
                    var xcor = document.getElementById('x-text').value;
                    var ycor = document.getElementById('y-text').value;
                    var cont = document.getElementById('content-text').value;
                    var text = new PointText({
                        point: [xcor, ycor - 150],
                        content: cont,
                        fillColor: 'black',
                        fontSize: 25
                        });
                    var txt = new Group();
                    txt.addChild(text);
                    createElem('Notes', m, txt);
                }

            }
        }


Q:

Program only runs audio from desktop and not audio in a package on netbeans?

I've created the game frogger and want to add audio to it. The audio files are .wav.
If I use the file path for the audio stored on my desktop it works. But I want to use the audio i've added to package called "audio" in netbeans. But it comes up with an error.
private String audioFile = "/audio/retrolevel.wav";

  public void getSound() {
    try
{
    Clip clip = AudioSystem.getClip();
    clip.open(AudioSystem.getAudioInputStream(new File(audioFile)));
    clip.start();
}
catch (LineUnavailableException | UnsupportedAudioFileException | IOException exc)
{
    exc.printStackTrace(System.out);
}

}

The error is
java.io.FileNotFoundException: \audio\retrolevel.wav (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at com.sun.media.sound.WaveFloatFileReader.getAudioInputStream(WaveFloatFileReader.java:164)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1179)
at frogger.Board.getSound(Board.java:170)

If audioFile = "C:/Users/Michael/Desktop/Frogger Music/WAV/retrolevel.wav" it works fine.
I'm pretty sure the path is fine for the netbeans one so why does it not work with the file in netbeans?

A:

You need to invoke a classloader in order to access files in your package. See here for API description. This is how it works:
InputStream inaudio = getClass().getResourceAsStream("/audio/retrolevel.wav");
Clip clip = null;
try {
    clip = AudioSystem.getClip();
    clip.open(AudioSystem.getAudioInputStream(inaudio));
} catch (IOException | LineUnavailableException | UnsupportedAudioFileException e1) {
    e1.printStackTrace();
}
clip.start();


Q:

show that function $f:\mathbb{R \to\mathbb{R}}$ defined by $f(x)=|x|^{p}$ for $p\geq1$ is a convex function.

show that function $f:\mathbb{R \to\mathbb{R}}$ defined by $f(x)=|x|^{p}$ for $p\geq1$ is a convex function.
hint is given that use slope criterion .but how to apply slope criterion here .
please help

A:

Hint: I suggest you to prove the simple following assertion
If $f: R \to I $ is convex and  $g: I \to R $ nondecreasing and convex then
 $gof: R \to R $ is convex .
Just apply definition.


Q:

Jinja2 marking HTML string as safe

I have a HTML tag in jinja2 that I want to embed a variable into.
Format.html:
{% set color="red" %}
{% set tag="" %}
This is red {{ tag|safe }}.

If I mark tag as safe, it doesn't render the variable color. If I don't render it as safe it sanitizes the HTML img tag and I can't embed my image. How do I properly embed my image ? I don't want to write out the img tag because I need it as a reusable variable throughout the code.

A:

The problem is that you can't use{{ }} inside another template tag. You can, however, concatenate the string and the variable color inside a template tag like this:
Method #1: Using the ~ symbol. From Jinja2's docs, it converts the variables into strings and concatenates them.
{% set tag = "" %}

OR
Method #2: Using the format filter:
{% set tag = ""|format(color) %}


Q:

Limit recursive function based on number of recursions completed

I have a recursive function that extracts data from a database. The database is huge and the recursion takes a while and eventually ends in an Error as I have exceeded the stack. I am trying to debug the function so I would like to limit the recursion so I can look at the result before the stack error occurs.
Here is the function. How can I put a recursion limit on it?
(df$relatedIdEx is just a character string from the dataframe that is used as the string to lookup a new dataframe with). If the string has already been looked up then it is skip- this is to prevent infinite loops
get_all_dfs <- function(df) {
  lapply(df$relatedIdEx, function(elem) {
    if (as.character(unlist(elem)) %in% already_lookedup) {
      print(paste("Already looked up ",elem," and skipping!"))
      return (NULL)
    } else {
      already_lookedup <<- c(already_lookedup,as.character(unlist(elem)))
    }
    next_df <- myGIConcepts(elem)

    #next_df_list<-list(next_df,my_env)
    if (nrow(next_df)>1) {
      get_all_dfs(next_df)
    } else {
      thelist<-df
    }
  })
}

A:

You can pass the counter to the function, which is a bit more clean, such as get_all_dfs <- function(df,counter).  But your question implies a quick solution will do.  A counter is added as follows.  Note you could move it within the lapply as well, potentially, depending on where you want the counter to be or where to break.
counter <- 0
get_all_dfs <- function(df) {
  counter <<- counter+1
  if (counter > 100) return (NULL)

  lapply(df$relatedIdEx, function(elem) {
    if (as.character(unlist(elem)) %in% already_lookedup) {
      print(paste("Already looked up ",elem," and skipping!"))
      return (NULL)
    } else {
      already_lookedup <<- c(already_lookedup,as.character(unlist(elem)))
    }
    next_df <- myGIConcepts(elem)

    #next_df_list<-list(next_df,my_env)
    if (nrow(next_df)>1) {
      get_all_dfs(next_df)
    } else {
      thelist<-df
    }
  })
}


Q:

Including the final character in text output from a NSScanner

I am using a NSScanner to detect text bound by [square brackets] in a string, and convert it into HTML hyperlinks. I hope to turn convert this text in the following way:
This [is an] example of the [text] I'm using

should convert to
This is an example of the text I'm using

I've implemented a NSScanner, but in order to make it work properly, I need to extract both the first and second of the square brackets.
Here's the current state of my code:
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:stringWithBrackets];

NSString *stringWithoutBrackets;
while ([theScanner isAtEnd] == NO) {
    [theScanner scanUpToString:@"[" intoString:NULL];
    [theScanner scanUpToString:@"]" intoString:&text];

<BREAK>

At this breakpoint, I have a string returned, which does not contain the closing bracket. So, for the example text string shown above, the contents of NSString *text at the first breakpoint is
[is an

In order to properly manipulate the string, I need to work with both the opening and closing bracket.
Essentially, my question is: how do I advance the NSScanner on one character, and include that character into the variable 'text'?

A:

You can skip the ] character with scanString:
if ([theScanner scanString:@"]" intoString:NULL]) {
    text = [text stringByAppendingString:@"]"];
} else {
    // Next character is not ']'
}

The else case would only happen if there is no matching ] character. text contains the part from [ to the end of the string in that case.
Alternatively, you could use NSRegularExpression and e.g. the matchesInString method which returns an array of all ranges in the string matching the regular expression.


Q:

Sine and Cosine Expansion Problem

We know:
$$\sin{x} = x - \frac{x^3}{3!} + \frac{x^3}{5!}-\dotsb$$
 and so on. Also,
$$\cos{x} = 1 - \frac{x^2}{2!} +\frac{x^4}{4!}-\dotsb$$
and so on.
With the help of these expansions we need to prove that $\sin^2 x+\cos^2 x=1$ .
I tried generalizing $\sin{x}$ as
$$\sum (-1)^n\frac{x^{2n+1}}{(2n+1)!}$$
and $\cos{x}$ as
$$\sum (-1)^n\frac{x^{2n}}{(2n)!},$$
 then squaring and adding. But it didn't get through.
Please help!

A:

I think the easiest way to see it is to notice that $e^{ix}=\cos(x)+i\sin(x)$ which is easily verified by writing down the Taylor expansion of both sides. Then
$$\sin^2(x)+\cos^2(x)=e^{ix}e^{-ix}=1$$
If you want to verify $f(y)=e^{y}e^{-y}=1$, here's how: first show $\frac{d}{dx}e^y=e^y$ from the Taylor series. Then show $f'(y)=f(y)-f(y)=0$ by the chain rule. Conclude $f(y)$ is a constant, and plug in $y=0$ to get $f(y)=1$.


Q:

why does `awk` print all elements of a for loop, but can't export them all to the clipboard?

Given some data like so:
"Something something","1234567890123456","12/34/5678","Other thing","123",""

I'm trying to get awk to print the fields and then export them to the X clipboard using xclip with the following:
echo $data | sed 's/"//g' | awk -F',' '{for(i=1;i<NF;i++) {print $i; system("echo \"" $i "\" | xclip -i")}}'

which correctly gives the right output:
Something something
1234567890123456
12/34/5678
Other thing
123

but it seems to only copy the last field to the clipboard. I am using a clipboard manager (klipper) so I would expect there to be all of the fields listed.
What am I missing?

A:

This is not an awk issue at all. Apparently, xclip can't handle the speed of the input its receiving. Similarly, for i in {1..3}; do echo $i | xclip -i; done fails in just the same way. Adding a sleep after the call to xclip will solve the problem. Based on my experiments, there will need to be 0.1 seconds per item, so for 6 fields shown, you would need:
echo $data | sed 's/"//g' | awk -F',' '{for(i=1;i<NF;i++) {print $i; system("echo \"" $i "\" | xclip -i; sleep 0.6")}}'


Q:

Where can I find Snek and Zaba in order to unlock their achievements?

I can't find those two creatures:

Snek
Zaba

I want to get their achievements. Where can I find them?

A:

Using the image below as a reference:

 They can be found in Chapter 5, inside the house marked as 4:

For Snek:

 blow random hornes while you get a snail head. Than blow the bottom horn while you get the complete creature.

For Zaba:

 blow random hornes while you get a frog head. Than blow once the bottom horn and once the top horn.

Source: jayisgames.com Walkthrough

For more detailed information on this particular location, see the following question:

 What is the pattern to the stomach room with the horns?


Q:

Javascript DOM detect elements style change (Without JQUERY)

I developing a javascript application and i need to detect id="mydiv" 's any style changes without JQUERY.
document.getElementById("mydiv").addEventListener("WHATISANYCHANGESEVENTNAME", function() {
     alert("change detected");
})

How can i do that.
Thanks

A:

You can use MutationObserver

let observer = new MutationObserver((mutations, observer) => {
    mutations.map( m => console.log(m.target.style.cssText) );
});

observer.observe(mydiv, {attributes: true});

// TEST which change background
function changeBg(e) {
  e.target.style.background = '#'+(Math.random()*2**24|0).toString(16); // random color
}
.foo { width: 100px; height: 100px; background: yellow }

clik on me


Q:

simplest way to generate xml in python

I have a defaultdict(list).. So, data structure of following format:
1:[1,2,3,4,5]
2:[2,3,4]

I want to generate the following xml
<html>
<page>
<src>1</src>
<links>
   <link>1</link>
   <link>2</link>
    ...
    <link>5</link>
</links>
</page>

<page>
<src>2</src>
<links>
   <link>2</link>
   <link>3</link>
    <link>4</link>
</links>
</page>
<html>

And then write an indented xml to file

A:

You can use BeautifulSoup:
from bs4 import Tag

d = {1: [1,2,3,4,5], 2: [2,3,4]}

root = Tag(name='html')
for key, values in d.iteritems():
    page = Tag(name='page')
    src = Tag(name='src')
    src.string = str(key)
    page.append(src)

    links = Tag(name='links')
    for value in values:
        link = Tag(name='link')
        link.string = str(value)
        links.append(link)

    page.append(links)
    root.append(page)

print root.prettify()

prints:
<html>
 <page>
  <src>
   1
  </src>
  <links>
   <link>
    1
   </link>
   <link>
    2
   </link>
   <link>
    3
   </link>
   <link>
    4
   </link>
   <link>
    5
   </link>
  </links>
 </page>
 <page>
  <src>
   2
  </src>
  <links>
   <link>
    2
   </link>
   <link>
    3
   </link>
   <link>
    4
   </link>
  </links>
 </page>
</html>


Q:

Sort my contacts alphabetic using cURL

I'm receiving all of my contacts on Google Contacts using this method:
session_start();

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/accounts/ClientLogin');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = array(
    'accountType' => 'GOOGLE',
    'Email' => 'email',
    'Passwd' => 'password',
    'source' => 'sourcetest',
    'service' => 'cp'
);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$responses = explode("\n", curl_exec($ch));
$_SESSION['auth'] = str_replace('Auth=', '', $responses[2]);
$_SESSION['email'] = 'email';

$url = 'https://www.google.com/m8/feeds/contacts/default/full';
$url .= '?group=http://www.google.com/m8/feeds/groups/'.$_SESSION['email'].'/base/6';
$url .= '&max-results=500&alt=json';

$ch = curl_init($url);

$header[] = 'Authorization: GoogleLogin auth='.$_SESSION['auth'];
$header[] = 'GData-Version: 3.0';

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);

$response = curl_exec($ch);
curl_close($ch);

/** **** **** **** **** **** **** **** **** **** **** **/

# CONTROL
if(isset($response_as_array['feed']) AND isset($response_as_array['feed']['entry'])) {

    # TABLE
    echo '
';
    echo '
';
        echo '';
            echo 'Namn';
        echo '	';

        echo '';
            echo 'Telefon-nummer';
        echo '	';
    echo '
';

    # LOOP
    foreach($response_as_array['feed']['entry'] AS $i => $entry) {

        # CONTROL: Hide my name
        if(utf8_decode($entry['gd$name']['gd$fullName']['$t']) != 'Erik Edgren') {

            echo '
';
                echo '';
                    echo utf8_decode($entry['gd$name']['gd$fullName']['$t']);
                echo '	';

                echo '';
                    echo isset($entry['gd$phoneNumber'][0]) ? $entry['gd$phoneNumber'][0]['$t'] : '';
                echo '	';
            echo '
';

        }

    }

    echo '
';

}

It works fine but it's not sorting the contacts alphabetically. How can I do this?
Thanks in advance.

A:

I assume that you have an array in $response_as_array['feed']['entry'] which have all your contacts, then you can use:
usort($response_as_array['feed']['entry'], function($a, $b) {
    return strcmp($a['gd$name']['gd$fullName']['$t'], $b['gd$name']['gd$fullName']['$t']);
});


Q:

Navigation in Xamarin.Forms

I have two pages say Page1 and page2.
In Page-1 I have a listview and an Image button(tap gesture).
Here if I click listview item, it navigates to Page2 where
it plays a song.
Navigation.PushModalAsync(new page2(parameter1));

Song continues to play. Then I go back to page1 by clicking back button. Then as mentioned I have an imagebutton in page1, if I click this image button, I want to go the same page which was shown earlier(page2) with same status song continues to play (it should not play from the beginning).
I understand, if I click the back button, it destroys the model page. For some reason, I can't use pushasync().
Is this possible?

A:

Would recommend not to tightly couple your audio/media player logic with your navigation logic or Page objects - especially if you want it to continue playing in the background.
Simplest approach would be to have a AudioPlayerService class that subscribes to MessengingCenter for audio player commands - such as play, pause etc. When a play command is published, it can initiate a background thread to play the audio file.
MessagingCenter.Subscribe<Page2, AudioPlayerArgs> (this, "Play", (sender, args) => {
      // initiate thread to play song
});

Now, when you navigate from page1 to page2, you can publish/send a command to the AudioPlayerService class through MessengingCenter to start playing the song. This way, any number of back-and-forth between page1 or page2 won't affect the audio player as it can ignore the play commands if it is already playing the same audio file.
MessagingCenter.Send<Page2, AudioPlayerArgs> (this, "Play", new AudioPlayerArgs("<sound file path>"));

Note: I personally avoid using MessengingCenter in my code - A better approach would be to rather introduce an interface for IAudioPlayerService with appropriate methods to play, pause etc. and use DependencyService to maintain the AudioPlayerService state as a global object (which is default behavior)
public interface IAudioPlayerService {
     bool PlayAudio(string file);
     bool PauseAudio();
     bool StopAudio();
}

[assembly: Xamarin.Forms.Dependency (typeof (IAudioPlayerService))]
public class AudioPlayerService : IAudioPlayerService {
      //implement your methods
}

And, use following code to control your audio player service in your Page/ViewModel objects.
DependencyService.Get<IAudioPlayerService>().Play("<sound file path>");


Q:

Krull Dimension of $K \otimes_k L$

Let $k$ be a field and $K,L$ are arbitrary extensions of $k$.
What do we know about $dim(K \otimes_k L)$ (as Krull dimension). How does it depend on transcendence degrees $trdeg_k(K), trdeg_k(L)$?
Futhermore: If we cosider by $k$ instead of a field a ring and $K,L$ be it's ring extensions. How does $dim(K \otimes_k L)$ depend on $dim(K), dim(L)$?

A:

In the case where $k$ is a field we have
$$ \dim (K \otimes_k L) = \min(\operatorname{trdeg}_k K, \operatorname{trdeg}_k L) $$
There is a Proof in Görtz's and Wedhorn's Algebraic Geometry 1 (Lemma B.97).
No such thing is possible in the second case: Suppose $k$ is a ring that "happens to be" a field and $K = L = k(x_1, \dots, x_n)$ are the ring extensions of $k$. We have $\dim K = \dim L = 0$ since they are fields but $\dim(K \otimes_k L) = n$. So $\dim(K \otimes_k L)$ does not only depend on $\dim K$ and $\dim L$.


Q:

Why do folded code blocks unfold "automatically" in PhpStorm

While writing code in PhpStorm the folded code blocks unfold automatically. I don't know why and this is making me real crazy. Somebody please help.

A:

It's a bug -- very annoying bug.
https://youtrack.jetbrains.com/issue/WEB-13995 -- watch this ticket (star/vote/comment) to get notified on progress.

UPDATE: Current status of the corresponding ticket is "resolved" so it must be working OK in WebStorm v11/PhpStorm v10.


Q:

toggling between visiblity hidden and visible doesnt work

The code only seems to hide it when I click on the element but when I click the element again, it does not reappear.
HTML (AngularJS)

Click Me!

Hide Me...Then Show Me Again

Controller:
$scope.showIt=function(){
    if($scope.tog="visible"){
      $scope.tog="hidden";
    }
    else{
      $scope.tog="visible";
    }
}

$scope.tog="visible";

Thanks in advance:)

A:

What about ng-show directive?

Click Me!

Hide Me...Then Show Me Again

A:

The style is called visibility also in the if condition you need to use == not =.
But a better solution will be to use the ng-style directive or use a class based solution

var app = angular.module('my-app', [], function() {})

app.controller('AppController', function($scope) {
  $scope.showIt = function() {
    if ($scope.tog.visibility == "visible") {
      $scope.tog.visibility = "hidden";
    } else {
      $scope.tog.visibility = "visible";
    }
  }
  $scope.showIt2 = function() {
    $scope.hidden = !$scope.hidden;
  }

  $scope.tog = {
    visibility: "visible"
  };
  $scope.hidden = false;
})
.hidden {
  visibility: hidden;
}

Click Me!

Hide Me...Then Show Me Again

Click Me!

Hide Me...Then Show Me Again


Q:

Is it possible to configure a GPIO as both input and output?

I am planning to implement a GPIO based I2C in atmega16.
Since it should have two pins SCL, SDA. The SDA pin should be bi directional but what i know is that either we can set a pin as input or output at a time.
By what way we can implement it?

A:

The SDA pin should be bi directional but what i know is that either we can set a pin as input or output at a time.

This is true, but the I2C master "knows" when to expect incoming data. Since this is a synchronous bus, the master can switch between driving the output or switching to tri-state/input right before clocking data in/out.
This application note from Atmel may be useful to you: Atmel AVR156: TWI Master Bit Bang Driver
The example from Atmel uses a polling-approach, which limits speed. If one of your GPIOs has pin change interrupt support, you could probably utilize that to get more speed if required.


Q:

Navigating from Page/ Page Function to PageFunction Null Reference Exception occurs

Page.cs
private void PageButton_Click(object sender, RoutedEventArgs e)
{
    PageFunction pageFunction = new PageFunction();
    pageFunction.Return += new ReturnEventHandler<String>(pageFunction_Return);
    this.NavigationService.Navigate(pageFunction);
}

static void pageFunction_Return(object sender, System.Windows.Navigation.ReturnEventArgs<String> e)
{
    String returnedVaule = e.Result;
    MessageBox.Show(returnedVaule);
}

PageFunction.cs
private void PageFunctionButton_Click(object sender, RoutedEventArgs e)
{
    OnReturn(new ReturnEventArgs<string>("Returned"));
}

As Shown above i have a Page and a PageFunction.
On PageButton_Click of Page.cs, i am navigating to PageFunction, But after the execution of the whole PageButton_Click event, a null reference exception (i.e, Object reference not set to an instance of an object).
And i dont know why this exception ocurred.
Help me out with this problem.
Thanks.

A:

Remember -> pagefunction<string>
it may help you.


Q:

PHP variable in Javascript

Consider this simple example;
<?php $text = test; ?>

<script type="text/javascript" defer="defer">

var test;

test = "<?php echo $text; ?>"

$(document).ready(function(){
alert(test);
});

</script>

This works fine. Creating the alert with the text from the php var. However, if I place;
<?php $text = test; ?>

below the script - it does not work. I've tried the defer function. What am I doing wrong?
Cheers

A:

If you place
  <?php $text = "test"; ?>

below the JS code, the the variable $text is not defined yet, so you cannot echo it earlier (edit) in the script.


Q:

Ember: Add conditions in form-element to display field contents

How to add conditions in Ember template.
What I want to achieve is like this condition.
if(modalForAdd == true) // if modalForAdd is true then set the model or the property of each input textfield to blank
{
  {{bs-form-element controlType="text" label="Quantity" property=""}}
}
else
{
  {{bs-form-element controlType="text" label="Quantity" property="model.quantity"}}
}

Here is my code for template
    {{#bs-modal open=openModalForDetails title="Add new Order" body=false footer=false}}
    {{#bs-modal-body}}
       {{#bs-form model=this action=(action "SaveNewOrder" model "this")}}
          {{bs-form-element controlType="text" label="Item SKU" property="model.item" id="item"}}
          {{bs-form-element controlType="text" label="Quantity" property="model.quantity" id="quantity"}}
          {{bs-form-element controlType="text" label="Description" property="model.description" id="description"}}
          {{bs-form-element controlType="text" label="Discount" property="model.discount" id="discount"}}
          {{bs-form-element controlType="text" label="Coupon" property="model.coupon" id="coupon"}}
          {{bs-form-element controlType="text" label="Price" property="model.price" id="price"}}
       {{/bs-form}}
    {{/bs-modal-body}}
    {{bs-modal-footer closeTitle="Cancel" submitTitle="Add"}}
{{/bs-modal}}

A:

The if helper has an inline version that can be used as subexpression.
You can just do:
{{bs-form-element controlType="text" label="Quantity" property=(if modalForAdd "" "model.quantity")}}


Q:

Is this the correct way to create SQL assertion?

in order to make the following type of assertion
create assertion assert
check "EMPTY SET" = (select User
     from Video
     where date=current_date()
     group by user
having count(*) >= 10

is this assertion right?
create assertion assert
check  0 = (select count(*)
     from Video
     where date=current_date()
     group by user
having count(*) >= 10

A:

For full details on CREATE ASSERTION see the ISO SQL-92 Standard spec.
The CHECK definition should be in parentheses.
CURRENT_DATE does not have parentheses.
USER and DATE are reserved words.
SQL statements should be terminated with a semicolon character.
SQL Keywords should be in upper case.
Try something more like this:
CREATE ASSERTION assert
CHECK (0 = (
            SELECT COUNT(*)
              FROM Video
             WHERE my_date = CURRENT_DATE
             GROUP
                BY my_user
            HAVING COUNT(*) >= 10
           ));

You can test that the syntax is correct using the online Mimer SQL-92 Validator. However, you should also test your logic e.g. CURRENT_DATE is non-deterministic.
Also, I don't think this ASSERTION will ever bite. When the cardinality of the subquery is less than 10 it will return zero rows and 0 = empty set will evaluate to UNKNOWN. When the cardinality of the subquery is 10 or greater then the search condition will evaluate TRUE. SQL-92 Standard states

The assertion is not satisfied if and
  only if the result of evaluating the
  search condition is false.

Note you can replace your CHECK (0 = (SELECT COUNT(*) FROM...)) construct with CHECK (NOT EXISTS (SELECT * FROM...)), the latter of which I find easier to write.

UPDATE:

How should I write the assertion using
  CHECK NOT EXISTS ?

As I said above, your logic appears flawed so it is hard to implement properly ;)
Let's say the rule is to limit Videos to 10 per user per day. Because this involves only a single table, it would be more appropriate to use a table-level CHECK constraint; such a constraint is checked when the table is updated which is sufficient in this case (there's no reason why it couldn't be an ASSERTION, though, which in theory could be checked each time any table in the schema is updated):
ALTER TABLE Video ADD
   CONSTRAINT video_limit_10_per_user_per_day
      CHECK (NOT EXISTS (
                         SELECT v1.my_user, v1.my_date
                           FROM Video AS V1
                          GROUP BY v1.my_user, v1.my_date
                         HAVING COUNT(*) > 10
                        ));

UPDATE 2:

thanks,now let's say we want to limit
  videos to 100 per user per year, in
  this case using current_date would be
  necessary wouldn't it?

Consider again that a CHECK/ASSERTION will only be checked when data in the table/schema is updated. The problem with using CURRENT_DATE (and other non-determninistic functions) in a constraint is that the business rule can be invalidated simply by the clock ticking over from one time period to the next but if the data hasn't been changed in that period then the data integrity failure will not be detected and the database will contain invalid data.
Another consideration is what is meant by a year in context.
It could be the calendar year (1 Jan to 31 Dec inclusive) or other other fixed dates defined by enterprise (e.g. 1 Apr to 31 Mar inclusive), in which case grouping by year and user then counting is trivial.
A more interesting case is when the rule limits the tally for any 12 month period; extending this to both the past and future avoid the above 'non-deterministic' issue.
Consider a standard approach of using an auxiliary calendar table, containing one row for every day applicable to the enterprise, extended into the past and future only as far as required should still only comprise a few thousand rows. Each row would have the date as a key with a second column for that date plus one year (and if necessary you could fine tune the definition of 'a year' at one-day granularity!) The test for would involve joining to the Calendar table, grouping on the calendar date and user and counting e.g. something like this:
SELECT C1.dt, V1.my_user
  FROM Video AS V1
       INNER JOIN Calendar AS C1
          ON (V1.my_date BETWEEN C1.dt AND C1.dt_plus_one_year)
 GROUP
    BY C1.dt, V1.my_user
HAVING COUNT(*) > 100;

This could be put in a CHECK (NOT EXISTS (... constraint. This could still be a table-level CHECK constraint: because the Calendar table is an auxiliary table it would only be suject to infrequent controlled updates (but again could be an ASSERTION if required).


Q:

How do I correct the css compile order with webpack in Vuejs?

I have a issue about css compile order in Webpack 2 with vue-cli project.
In main.js, I imported a css library file named skeleton.css . This include <a> color style.
import Vue from 'vue'
import App from './App'
import router from './router'
import 'skeleton-css/css/skeleton.css'

In App.vue, I set <a> color style as below
<style lang="scss">
    a {
        text-decoration: none;
        color: #2c3e50;
    }
</style>

When I compiled the code and open the chrome inspector. I found the wrong order insert style.
<style type="text/css">....</style> // App.vue inline style
<style type="text/css">....</style> // skeleton.css style

And my webpack 2 config with vue-cli
{
    test: /\.scss$/,
    use: [{
        loader: "style-loader"
    }, {
        loader: "css-loader"
    }, {
        loader: "sass-loader"
    }]
}

How should I do to adjust correct import style order?

A:

You need reorder the imports in your main.js, since it is the only thing that affects the order of <style> tags in the resulting DOM:
import 'skeleton-css/css/skeleton.css'
import Vue from 'vue'
import App from './App'
import router from './router'

Now skeleton.css comes first, and everything else would come after it.


Q:

sp_Blitz error: "File '' either does not exist.."

SQL Server 2008 v10.0.5538.0
sp_Blitz v5.5

I'm trying to run sp_Blitz for the first time and getting this error message:
sp_Blitz @CheckUserDatabaseObjects = 0

Warning: Null value is eliminated by an aggregate or other SET operation.
  Msg 567, Level 16, State 5, Procedure sp_Blitz, Line 3863 [Batch Start Line 0]
  File '' either does not exist or is not a recognizable trace file. Or there was an error opening the file.

What may be causing the error?

A:

There's a weird bug that only pops up on some instances of SQL Server when the Trace File path has problems. I can't diagnose those, but we took some steps to avoid that bug which are in the latest version of sp_Blitz.
Please head over to firstresponderkit.org to grab the newest version, and file an issue at the GitHub repo if you run into anything else.
Thanks!


Q:

derivative of polar coordinates

I am trying to undersatnd a proof and I am stuck on the derivative part in this proof. I can't understand why is there still a Fx and Fy in the polar coordinate.

A:

The author is describing how partial derivatives work when they say "fixing $\theta$ and letting $r$ vary." The rest is indeed the chain rule
$$
\frac{\partial f}{\partial r}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial r}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial r}\\
=f_x\cos\theta+f_y\sin \theta
$$


Q:

Cumulative Unique words in huge dataframe

How do I get  cumulative unique words from a dataframe column which has more than 500 words per. Dataframe has ~300,000 rows
I read the csv file in a dataframe with column A having text data.
I have tried creating couple of columns (B & C) by looping through column A and taking unique words from column A as set and appending Column B with unique words and Column C with count
Subsequently, I  take unique words by taking Column A and column B(union) from previous row(set)
This works for small number of rows. But once number of rows exceeds 10,000 performance degrades and kernal eventually dies
Is there any better way of doing this for huge dataframe ?
Tried creating seperate dataframe with just unique words and count, but still have issue
Sample code:
for index, row in DF.iterrows():
      if index = 0:
          result = set(row['Column A'].lower().split()
          DF.at[index, 'Column B'] = result
      else:
          result = set(row['Column A'].lower().split()
          DF.at[index, 'Cloumn B'] = result.union(DF.loc[index -1,
                                                'Column B'])
DF['Column C'] = DF['Column B'].apply(len)

A:

Exploit uniqueness of dictionary keys to cumulate words.
I create a dict cumulative_words where I want to store unique words row by row, by updating it with dictionaries having keys made of unique words from a given row sentence.
Code:
cumulative_words = {}

def cumulate(x):
    cumulative_words.update(dict.fromkeys(set(x.lower().split())))
    return list(cumulative_words.keys())

df["Column B"] = df["Column A"].apply(cumulate)
df["Column C"] = df["Column B"].apply(len)

Update:
Given that you said this code still has memory issues at ~ 200k rows,
I'll try something very simple to understand a bit more:

Just update the dictionary of cumulatives

Create the dictionary with unique words before dataframe operations
cumulative_words = {}

for x in df["Column A"].values:
    cumulative_words.update(dict.fromkeys(set(x.lower().split())))

If this still breaks I think we have to change method

Append words to a list

This is the critical point I think, because it creates a list of lists of, roughly, billions of words
cumulative_words = {}
cumulative_column = []

for x in df["Column A"].values:
    cumulative_words.update(dict.fromkeys(set(x.lower().split())))
    cumulative_column.append(cumulative_words.keys())

Assign created list to Column B and count

df["Column B"] = cumulative_column
df["Column C"] = df["Column B"].apply(len)

Maybe there are just too many words to store and a dataframe can't be created, or I don't know how to do. Let me know


Q:

Magento 2 checkout login with mobile number or email

I want to allow the customer to Log in using email or mobile number on the checkout page and the login page.
Note: Mobile number is customer eav attribute.

A:

For Login with the customer, First you need to make mobile number required field in customer Registration form. Whenever customer register, At that time you need to add a field like mobile no. and save that field to Customer registration page.
Now when customer login at that time they enter email id or mobile number. For this you need to override this controller
Magento\Customer\Controller\Account\LoginPost

in your module and add code like below, Path should be like: app/code/Vendor/Modulename/Controller/Account/LoginPost.
Now keep below code in your controller,
<?php
namespace Vendor\Modulename\Controller\Account;

use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;

class LoginPost extends \Magento\Customer\Controller\Account\LoginPost
{
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Api\AccountManagementInterface $customerAccountManagement,
        CustomerUrl $customerHelperData,
        Validator $formKeyValidator,
        AccountRedirect $accountRedirect,
        \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerFactory
    ) {
        $this->_customerFactory = $customerFactory;
        parent::__construct($context,$customerSession,$customerAccountManagement,$customerHelperData,$formKeyValidator,$accountRedirect);
    }

    public function execute()
    {
        if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('*/*/');
            return $resultRedirect;
        }
        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');

            if(!strpos($login['username'], '@') !== false ) {
                $isMobile = $login['username'];
                /* Get email id based on mobile number and login*/
                $customereCollection = $this->_customerFactory->create();
                $customereCollection->addFieldToFilter("mobile", $login['username']);
                foreach($customereCollection as $customerdata){
                    $login['username'] = $customerdata['email'];
                }
            }

            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                    $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
                    $this->session->setCustomerDataAsLoggedIn($customer);
                    $this->session->regenerateId();
                    if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
                        $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
                        $metadata->setPath('/');
                        $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
                    }
                    $redirectUrl = $this->accountRedirect->getRedirectCookie();

                    if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) {

                        $this->accountRedirect->clearRedirectCookie();
                        $resultRedirect = $this->resultRedirectFactory->create();
                        // URL is checked to be internal in $this->_redirect->success()
                        $resultRedirect->setUrl($this->_redirect->success($redirectUrl));
                        return $resultRedirect;
                    }else{
                        $resultRedirect = $this->resultRedirectFactory->create();
                        $resultRedirect->setPath('');
                        return $resultRedirect;
                    }
                } catch (EmailNotConfirmedException $e) {
                    $value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
                    $message = __(
                        'This account is not confirmed. Click here to resend confirmation email.',
                        $value
                    );
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (UserLockedException $e) {
                    $message = __(
                        'You did not sign in correctly or your account is temporarily disabled.'
                    );
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (AuthenticationException $e) {
                    $message = __('You did not sign in correctly or your account is temporarily disabled.');
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (LocalizedException $e) {
                    $message = $e->getMessage();
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (\Exception $e) {
                    // PA DSS violation: throwing or logging an exception here can disclose customer password
                    $this->messageManager->addError(
                        __('An unspecified error occurred. Please contact us for assistance.')
                    );
                }
            } else {
                $this->messageManager->addError(__('A login and a password are required.'));
            }
        }

        return $this->accountRedirect->getRedirect();
    }
}

I hope this will help


Q:

How to evenly distribute vertices in an uv map?

I try to make a UV map for my object that fits the form of an already existing UV map. I manually positioning the outer edge of the map so it matches the existing map. But the innards are not in good shape.
Now I want to select one of the loops and make the vertices have all the same space between them. I tried to use Looptools but they are not available in UV Image Editor.
How can it be done automatically to even out the spacing of all the inner vertices on a selected loop?

A:

Select the loop and enable the Sculpt tool:

With holding Shift smooth the selected vertices. This will space them evenly:
Make sure the sculpt brush has Lock Borders enabled:


Q:

Can't install PHP after apt-get dist-upgrade

I had a server with perfectly running for months classical LAMP installation on Ubuntu 8.04:
Linux localhost 2.6.24-23-generic #1 SMP Wed Apr 1 21:47:28 UTC 2009 i686 GNU/Linux
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=8.04
DISTRIB_CODENAME=hardy
DISTRIB_DESCRIPTION="Ubuntu 8.04.4 LTS"

Don't know why I've started apt-get update, apt-get upgrade but everything ended with apt-get dist-upgrade :) Everything gone alright... But now I can't start nor Apache, nor PHP, because PHP was simply deleted. When I'm trying to install it:
> apt-get install php5
<...>

The following packages have unmet dependencies:
  php5: Depends: libapache2-mod-php5 (>= 5.2.4-2ubuntu5.17) but it is not going to be installed or
                 php5-cgi (>= 5.2.4-2ubuntu5.17) but it is not going to be installed
E: Broken packages

When I'm trying to install libapache2-mod-php5:
The following packages have unmet dependencies:
  libapache2-mod-php5: Depends: php5-common (= 5.2.4-2ubuntu5.17) but 5.3.6-6~dotdeb.1 is to be installed
E: Broken packages

I don't know what 5.3.6-6~dotdeb.1 is and where is this package, because I've already removed dotdeb repository from APT sources :/
Tried to do apt-get update, apt-get upgrade, apt-get install php5 php5-common php5-cli with no success...
Don't know what to try next :(

A:

Do this first:
sudo apt-get remove php5-common

Followed by:
sudo apt-get install php


Q:

Getting frequency values from histogram in R

I know how to draw histograms or other frequency/percentage related tables.
But now I want to know, how can I get those frequency values in a table to use after the fact.
I have a massive dataset, now I draw a histogram with a set binwidth. I want to extract the frequency value (i.e. value on y-axis) that corresponds to each binwidth and save it somewhere.
Can someone please help me with this?
Thank you!

A:

The hist function has a return value (an object of class histogram):
R> res <- hist(rnorm(100))
R> res
$breaks
[1] -4 -3 -2 -1  0  1  2  3  4

$counts
[1]  1  2 17 27 34 16  2  1

$intensities
[1] 0.01 0.02 0.17 0.27 0.34 0.16 0.02 0.01

$density
[1] 0.01 0.02 0.17 0.27 0.34 0.16 0.02 0.01

$mids
[1] -3.5 -2.5 -1.5 -0.5  0.5  1.5  2.5  3.5

$xname
[1] "rnorm(100)"

$equidist
[1] TRUE

attr(,"class")
[1] "histogram"

A:

From ?hist:
Value
an object of class "histogram" which is a list with components:

breaks    the n+1 cell boundaries (= breaks if that was a vector).
These are the nominal breaks, not with the boundary fuzz.
counts   n integers; for each cell, the number of x[] inside.
density   values f^(x[i]), as estimated density values. If
all(diff(breaks) == 1), they are the relative frequencies counts/n
and in general satisfy sum[i; f^(x[i]) (b[i+1]-b[i])] = 1, where b[i]
= breaks[i].
intensities   same as density. Deprecated, but retained for
compatibility.
mids  the n cell midpoints.
xname     a character string with the actual x argument name.
equidist  logical, indicating if the distances between breaks are all
the same.

breaks and density provide just about all you need:
histrv<-hist(x)
histrv$breaks
histrv$density

A:

Just in case someone hits this question with ggplot's geom_histogram in mind, note that there is a way to extract the data from a ggplot object.
The following convenience function outputs a dataframe with the lower limit of each bin (xmin), the upper limit of each bin (xmax), the mid-point of each bin (x), as well as the frequency value (y).
## Convenience function
get_hist <- function(p) {
    d <- ggplot_build(p)$data[[1]]
    data.frame(x = d$x, xmin = d$xmin, xmax = d$xmax, y = d$y)
}

# make a dataframe for ggplot
set.seed(1)
x = runif(100, 0, 10)
y = cumsum(x)
df <- data.frame(x = sort(x), y = y)

# make geom_histogram
p <- ggplot(data = df, aes(x = x)) +
    geom_histogram(aes(y = cumsum(..count..)), binwidth = 1, boundary = 0,
                color = "black", fill = "white")

Illustration:
hist = get_hist(p)
head(hist$x)
## [1] 0.5 1.5 2.5 3.5 4.5 5.5
head(hist$y)
## [1]  7 13 24 38 52 57
head(hist$xmax)
## [1] 1 2 3 4 5 6
head(hist$xmin)
## [1] 0 1 2 3 4 5

A related question I answered here (Cumulative histogram with ggplot2).


Q:

Getting BASH command PID

I have this piece of code
#!/bin/bash
streamURL=http://devimages.apple.com/iphone/samples/bipbop/gear4/prog_index.m3u8

(
    echo "Debugging for stream: $streamURL";
    echo "Starting debugging...";
    vlc -vvv --color $streamURL --file-caching=10000 2>&1 | sed "s/^/ `date`/";

) | tee  debug.txt &
PROCESS_PID=$!

ps -e | grep $PROCESS_PID
echo " killing process pid: "
echo $PROCESS_PID;
kill -9 $PROCESS_PID
ps -e | grep vlc #still there

My problem is I can't manage to save the "vlc ..." command PID into a variable in order to kill it later. If I move "PROCESS_PID=$!" right after it, it will be empty. Also need the pipe after it for sed. Any suggestions?

A:

You can get the pid by twiddling file descriptors, but it's painful.  For example:
{ PID=$({ (
   echo foo;
   echo bar;
   sh -c 'echo $$ >&5; exec echo baz' ) |
   tr a o; } 5>&1 1>&3 ); } 3>&1

will assign the pid of 'echo baz' to PID.  Replace that echo with your vlc and replace the tr with your sed and you should have a solution.
To try an provide a somewhat simplified explanation of what's going on here, first notice that we are using process substitution to make the assignment to PID.  The $() syntax simply takes the command inside the parentheses and assigns to the variable the output of the command.  It is important to remember that "output" here means "whatever is printed to file descriptor 1".  Inside the sh command, we print a pid to file descriptor 5 and then exec echo.  By using exec, that echo has the same pid that the previous echo wrote.  Now the echo foo, bar and baz are all writing into  the pipe that goes to tr.  The output of tr is being redirected to fd 3 (before the edit, this was fd 2. Which file descriptor to use is mostly arbitrary, but modifying 2 is a bad idea in case any errors are generated) and file descriptor 5 is being redirected to fd 1, so that it becomes the "output" of the process substitution that is assigned to PID.  Then outside the process substitution, we assign fd 3 to give output where it was originally desired.  Hopefully, this paragraph is more explanatory than obfuscating: if confused, look at the code for clarification!
Unfortunately, it gets uglier if you want to run in the background:
{ PID=$({ (
   echo foo;
   echo bar;
   sh -c 'echo $$ >&5; exec 5>&-; exec echo baz' >&3 & ) |
   tr a o; } 5>&1 1>&3 ); } 3>&1

Here, you need to close file descriptor 5 to ensure that the process substitution completes.