text:
Q: Is #pragma once a safe include guard? I've read that there is some compiler optimization when using #pragma once which can result in faster compilation.  I recognize that is non-standard, and thus could pose a cross-platform compatibility issue.
Is this something that is supported by most modern compilers on non-windows platforms (gcc)?
I want to avoid platform compilation issues, but also want to avoid the extra work of fallback guards:
#pragma once
#ifndef HEADER_H
#define HEADER_H

...

#endif // HEADER_H

Should I be concerned? Should I expend any further mental energy on this?

A: I wish #pragma once (or something like it) had been in the standard.  Include guards aren't a real big deal (but they do seem to be a little difficult to explain to people learning the language), but it seems like a minor annoyance that could have been avoided.
In fact, since 99.98% of the time, the #pragma once behavior is the desired behavior, it would have been nice if preventing multiple inclusion of a header was automatically handled by the compiler, with a #pragma or something to allow double including.
But we have what we have (except that you might not have #pragma once).

A: The performance benefit is from not having to reopen the file once the #pragma once have been read. With guards, the compiler have to open the file (that can be costly in time) to get the information that it shouldn't include it's content again.
That is theory only because some compilers will automatically not open files that didn't have any read code in, for each compilation unit.
Anyway, it's not the case for all compilers, so ideally #pragma once have to be avoided for cross-platform code has it's not standard at all / have no standardized definition and effect. However, practically, it's really better than guards.
In the end, the better suggestion you can get to be sure to have the best speed from your compiler without having to check the behavior of each compiler in this case, is to use both pragma once and guards.
#ifndef NR_TEST_H
#define NR_TEST_H
#pragma once

#include "Thing.h"

namespace MyApp
{
 // ...
}

#endif

That way you get the best of both (cross-platform and help compilation speed).
As it's longer to type, I personally use a tool to help generate all that in a very wick way (Visual Assist X).

A: I don't know about any performance benefits but it certainly works.  I use it in all my C++ projects (granted I am using the MS compiler). I find it to be more effective than using
#ifndef HEADERNAME_H
#define HEADERNAME_H
...
#endif

It does the same job and doesn't populate the preprocessor with additional macros.
GCC supports #pragma once officially as of version 3.4.

A: Not always.
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52566 has a nice example of two files meant to both be included, but mistakenly thought to be identical because of identical timestamps and content (not identical file name).

A: #pragma once does have one drawback (other than being non-standard) and that is if you have the same file in different locations (we have this because our build system copies files around) then the compiler will think these are different files.

A: GCC supports #pragma once since 3.4, see http://en.wikipedia.org/wiki/Pragma_once for further compiler support.
The big upside I see on using #pragma once as opposed to include guards is to avoid copy/paste errors.
Let's face it: most of us hardly start a new header file from scratch, but rather just copy an existing one and modify it to our needs. It is much easier to create a working template using #pragma once instead of include guards. The less I have to modify the template, the less I am likely to run into errors. Having the same include guard in different files leads to strange compiler errors and it takes some time to figure out what went wrong.
TL;DR: #pragma once is easier to use.

A: Using #pragma once should work on any modern compiler, but I don't see any reason not to use a standard #ifndef include guard. It works just fine. The one caveat is that GCC didn't support #pragma once before version 3.4.
I also found that, at least on GCC, it recognizes the standard #ifndef include guard and optimizes it, so it shouldn't be much slower than #pragma once.

A: Using gcc 3.4 and 4.1 on very large trees (sometimes making use of distcc), I have yet to see any speed up when using #pragma once in lieu of, or in combination with standard include guards.
I really don't see how its worth potentially confusing older versions of gcc, or even other compilers since there's no real savings. I have not tried all of the various de-linters, but I'm willing to bet it will confuse many of them.
I too wish it had been adopted early on, but I can see the argument "Why do we need that when ifndef works perfectly fine?". Given C's many dark corners and complexities, include guards are one of the easiest, self explaining things. If you have even a small knowledge of how the preprocessor works, they should be self explanatory.
If you do observe a significant speed up, however, please update your question.

A: Today old-school include guards are as fast as a #pragma once. Even if the compiler doesn't treat them specially, it will still stop when it sees #ifndef WHATEVER and WHATEVER is defined. Opening a file is dirt cheap today. Even if there were to be an improvement, it would be in the order of miliseconds.
I simply just don't use #pragma once, as it has no benefit. To avoid clashing with other include guards I use something like: CI_APP_MODULE_FILE_H --> CI = Company Initials; APP = Application name; the rest is self-explanatory.

A: The main difference is that the compiler had to open the header file to read the include guard. In comparison, pragma once causes the compiler to keep track of the file and not do any file IO when it comes across another include for the same file. While that may sound negligible, it can easily scale up with huge projects, especially ones without good header include disciplines.
That said, these days compilers (including GCC) are smart enough to treat include guards like pragma once. i.e. they dont open the file and avoid the file IO penalty.
In compilers that dont support pragma I've seen manual implementations that are a little cumbersome..
#ifdef FOO_H
#include "foo.h"
#endif

I personally like #pragma once approach as it avoids the hassle of naming collisions and potential typo errors. It's also more elegant code by comparison. That said, for portable code, it shouldn't hurt to have both unless the compiler complains about it.

A: If we use msvc or Qt (up to Qt 4.5),  since GCC(up to 3.4) , msvc both  support #pragma once, I can see no reason for not using #pragma once.
Source file name usually same equal class name, and we know, sometime we need refactor, to rename class name, then we had to change the #include XXXX also,  so I think manual maintain the #include xxxxx is not a smart work.  even with Visual Assist X extension, maintain the "xxxx" is not a necessary work.

A: Additional note to the people thinking that an automatic one-time-only inclusion of header files is always desired: I build code generators using double or multiple inclusion of header files since decades. Especially for generation of protocol library stubs I find it very comfortable to have a extremely portable and powerful code generator with no additional tools and languages. I'm not the only developer using this scheme as this blogs X-Macros show. This wouldn't be possible to do without the missing automatic guarding.

A: I use #ifndef/#define include guards using symbols that incorporate a UUID like this:
#ifndef ARRAY__H_81945CB3_AEBB_471F_AC97_AB6C8B220314
#define ARRAY__H_81945CB3_AEBB_471F_AC97_AB6C8B220314 /* include guard */

#endif

I'v always used editors that were able to generate the UUIDs automatically.
This prevents name clash with files with the same base name from other libraries, and detects if the exact same file is placed in multiple locations inside the file system.
The down-side is the increase table size since the symbols are much bigger but I have not yet seen problems with it.

A: I use it and I'm happy with it, as I have to type much less to make a new header. It worked fine for me in three platforms: Windows, Mac and Linux.
I don't have any performance information but I believe that the difference between #pragma and the include guard will be nothing comparing to the slowness of parsing the C++ grammar. That's the real problem. Try to compile the same number of files and lines with a C# compiler for example, to see the difference.
In the end, using the guard or the pragma, won't matter at all.

A: Using '#pragma once' might not have any effect (it is not supported everywhere - though it is increasingly widely supported), so you need to use the conditional compilation code anyway, in which case, why bother with '#pragma once'?  The compiler probably optimizes it anyway.  It does depend on your target platforms, though.  If all your targets support it, then go ahead and use it - but it should be a conscious decision because all hell will break loose if you only use the pragma and then port to a compiler that does not support it.


text:
Q: Doesn't work horizontal form I wanted to use the bootstrap and make a horizontal form. Unfortunately, my form generates a normal, normal one. As if form-horizontal does not work (blocks are generated from ReactJS).

<block>
    <block>

formularz wprowadzania danych osobowych!

        <block>
            <form class="form-horizontal">

                    Imie:

                        <input class="form-control" type="text" id="firstName" name="firstName" value="">

                    Nazwisko:

                        <input class="form-control" type="text" id="lastName" name="lastName" value="">

                        <input type="submit" value="dalej">

            </form>
        </block>
    </block>

A: *

*Dropped the .form-horizontal class requirement.

*.form-group no longer applies styles from the .row via mixin, so .row
is now required for horizontal grid layouts (e.g.,
).

*Added new .col-form-label class to vertically center labels with
.form-controls.

*Added new .form-row for compact form layouts with the grid classes
(swap your .row for a .form-row and go).

Bootstrap 4 Forms

redpajama_set_name: RedPajamaStackExchange


text:
Q: Context switching issue in appium mobile automation Hi I tried switching from native to hybrid pages in mobile automation . it throws an error  chrome driver  is already in use. How to fix it in mobile automation.

A: If you need to automate android app using java, you can switch between contexts using the below method.
public final String WEBVIEW = "WEBVIEW_com.maxsoft.testextractor";
public final String NATIVE_APP = "NATIVE_APP";

public void switchContextTo(String context){
        if (context.toLowerCase().equals(WEBVIEW.toLowerCase())) {
            androidDriver.context(WEBVIEW); // set context to WEBVIEW_1
        } else {
            androidDriver.context(NATIVE_APP); // set context to NATIVE_APP
        }
    }


text:
Q: How to delete a folder asynchronously I have a windows service running that deletes folders from network drive. I want to make the deleting asynchronous. How can this be done?
Right now i am looping through the directories and calling
Directory.Delete(fullPath, true);

Thanks

A: I would use the Task Parallel Library:
Task.Factory.StartNew(path => Directory.Delete((string)path, true), fullPath);

A: If you are looping, you could use a parallel foreach
// assuming that you have a list string paths.
// also assuming that it does not matter what order in which you delete them
Parallel.ForEach(theListOfDirectories, x => Directory.Delete(x));


text:
Q: Magento Simple Configurable Products and Discounts I have Simple configurable products installed on magento.  How can I apply a discount to a configurable product which makes sure that all the simple products associated to the configurable also get the discount applied to them?

A: You could use Magento's Catalog Price Rules (Admin > Promotions > Catalog Price Rules).
There's some good information on how these work here:
http://www.magentocommerce.com/knowledge-base/entry/what-are-catalog-price-rules-and-how-do-i-use-them
Good luck!

A: I was also looking for the answer to this, but unfortunately didn't found it yet.
Below helped though. In addition to below, what i did is instead of selecting config product SKU, i selected all the simple product SKU which are part of that config product.
How to create a coupon on specific product in Magento?


text:
Q: How do I detect a precise IE build from javascript? I have noticed that my app won't work in IE version 11.0.9600.18314. I see this number when I click "About Internet Explorer" button in the menu. Looks like I can't fix my error (it has something to do with WebGL), so at least I could warn users about it and ask them either to upgrade or to switch to another browser.
However when I look for this in navigator.userAgent - I don't those numbers after second dot. I can see only "rv:11.0" and that's it. No traces of "9600.18blablabla".
Can this info be found anywhere else perhaps? Thanks.


text:
Q: Laravel 4:Can the migration file be reused? Can the migration file be reused?
In my project,I use the migration to make the database table.
And then I sent to my friend.
But he can't use the migration command to get these tables;
Always 'Nothing to migrate',So,May I ask how you do that?

A: Nothing to migrate appears only if Laravel detected that  migration done already. Now question is, how Laravel detect migration already done?
if you go to your database (using PhpMyadmin or Sequel pro), you will see there is a table called migrations. Laravel store all migration information to the migrations table. Do not share this table with your friend. . If you share the table already, ask your friend to empty the table.
Than run the migration again.


text:
Q: Accessing and Editing UI Elements between Different Classes in PyQT5 I am in the process of writing code that generates a main 'TopLevel' window where information is entered and then, upon the click of a pushbutton, another window opens and this information is sent through and accessed/edited/interacted with in that window. I have seemingly tried every way I can find on this website and others to try to access ui elements (be they labels, text inputs or, in this specific case, a dictionary) between different classes and nothing has worked so far.
I've edited the code below so that all the relevant elements are available and this version runs up to the point that the error is produced. The user types whatever they want in the box underneath "Input dictionary elements", clicks "Done" to add it to the list underneath "List of dictionary elements" and can then press "Expand" under the leftmost box to open the second window that I want to pass the list to.
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QDesktopWidget, QMessageBox, QPushButton, QAction, qApp, QMenu, QLineEdit, QLabel, QTextEdit, QComboBox, QScrollArea, QVBoxLayout, QScrollBar, QListWidget
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtCore import pyqtSlot, QCoreApplication, QMetaObject, QRect

def setKey(dictionary, key, value):
    if key not in dictionary:
        dictionary[key] = value
    elif type(dictionary[key]) == list:
        dictionary[key].append(value)
    else:
        dictionary[key] = [dictionary[key], value]

class TopLevel(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Top Level')
        self.resize(800,550)
        topLevelLabel = QLabel(self)
        topLevelLabel.setText('Top level of tree')
        self.topLevelBox = QTextEdit(self)
        self.topLevelBox.resize(200,50)
        self.topLevelBox.move(60,100)
        topLevelLabel.move(60,70)

        topLevelExpandButton = QPushButton('Expand', self)
        topLevelExpandButton.resize(50,30)
        topLevelExpandButton.move(100,150)
        topLevelExpandButton.pressed.connect(self.open_New_Window_Expand)

        selectSCLabel = QLabel(self)
        selectSCLabel.setText('Input dictionary elements')
        self.selectSCBox = QTextEdit(self)
        self.selectSCBox.resize(300,50)
        self.selectSCBox.move(300,100)
        selectSCLabel.move(300,60)
        selectSCLabel.resize(400,50)

        selectSCConfirmationButton = QPushButton('Done', self)
        selectSCConfirmationButton.resize(40,30)
        selectSCConfirmationButton.move(560,150)
        selectSCConfirmationButton.pressed.connect(self.selectSCConfirmationButtonPressed)

        listOfSelectedSCLabel = QLabel(self)
        listOfSelectedSCLabel.setText('List of dictionary elements')
        listOfSelectedSCLabel.setWordWrap(True)
        listOfSelectedSCLabel.move(60,190)
        listOfSelectedSCLabel.resize(200,30)
        self.listOfSelectedSCArea = QScrollArea(self)
        self.placeholderListItem = QWidget()
        self.vboxOfListItems = QVBoxLayout()
        self.listOfSelectedSCArea.move(60,220)
        self.listOfSelectedSCArea.resize(200,300)
        self.listOfSelectedSCArea.setVerticalScrollBarPolicy(0)
        self.listOfSelectedSCArea.setHorizontalScrollBarPolicy(0)
        self.listOfSelectedSCArea.setWidgetResizable(True)

        self.listOfSelectedSCDictionary = {}
        self.SCIterate = 1
        self.show()

    def open_New_Window_Expand(self):
        self.new_window = QMainWindow
        self.ui = NewLevelExpand()
        self.show()

    def selectSCConfirmationButtonPressed(self):
        newSCName = self.selectSCBox.toPlainText()
        nameToLabel = QLabel(self)
        nameToLabel.setText(newSCName)
        self.vboxOfListItems.addWidget(nameToLabel)
        self.placeholderListItem.setLayout(self.vboxOfListItems)
        self.listOfSelectedSCArea.setWidget(self.placeholderListItem)
        setKey(self.listOfSelectedSCDictionary, self.SCIterate, newSCName)
        self.SCIterate = self.SCIterate + 1
        print(self.listOfSelectedSCDictionary)

class NewLevelExpand(TopLevel):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self, parent = TopLevel):
        self.setWindowTitle('Expanded Level')
        self.resize(800,550)
        print(self.listOfSelectedSCDictionary)

        self.show()

def main():
    app = QApplication(sys.argv)
    tl = TopLevel()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

With tinkering with this code, I have generated numerous different error messages but the code above produces the message: "AttributeError: 'NewLevelExpand' object has no attribute 'listOfSelectedSCDictionary'"
As I say, I feel I have tried everything relating to this topic on stackoverflow and nothing has worked. Any advice and guidance, pointing out stupid errors, suggestions to changing my coding style to make it clearer, etc. would be massively appreciated.

A: Premise: I cannot help you a lot with the logic behind your program; I've to admit, it's a bit confused, and I don't understand how you're going to pass data to the new window, nor how you are going to use it.
The error you're facing is because NewLevelExpand is a subclass of TopLevel, and when you call its super().__init__() this results in calling the ancestor's __init__().
In the TopLevel class, __init__() calls initUI, which creates the whole UI and the listOfSelectedSCDictionary dictionary.
The problem is that you are overriding initUI in the subclass, so the result is that the base class initUI is never called (meaning that the UI nor the dictionary are actually created).
The solution to this specific problem is to call the base class implementation of initUI in the subclass:
class NewLevelExpand(TopLevel):
    # ...
    def initUI(self):
        super().initUI()
        self.setWindowTitle('Expanded Level')
        self.resize(800,550)
        print(self.listOfSelectedSCDictionary)


text:
Q: Javascript handle big date (dates that has a year higher than the math max int) I am trying to do a javascript code that is able to handle huge dates. The date year might be higher than the max possible int.
I don't need hour, minutes, second and milliseconds from the current javascript Date object, just number of days.
I have been searching for libraries which might offer this possibility but I did not found any :(
I also looked at this answer: How to use Date in Javascript for prehistoric dates?
But I would like the solution to work with future dates also. And some past dates might be bigger than the big bang
I hope that someone can help me with this issue :)


text:
Q: Shared Method in Parent Pulling Info From and Producing Child? Here's what I'd like to achieve. After mucking around with it for a day and a half, though, I've become nearly convinced that it can't be done. If someone can show me how to achieve this, I'd be quite grateful.
I have a .NET parent class Parent with a shared method Fetch(). Fetch can take a variety of parameters to help it know what particular records to fetch, but that's irrelevant at the moment.
Fetch() needs to know what table to look in to find the records its after. The table is different for each child class that inherits Parent. I'd like to keep the table name in a string that's a property of the Child class. Then each Child can provide its own table name, and Parent can handle the Fetching which works the same way for all of them.
Once it's executed the query, Fetch() should then have a DataReader. All Child classes have a constructor which can receive a DataReader as a parameter and use it to produce an instance of itself with attributes populated from the reader.
One thing I have to stress:
Fetch is a Shared method. If I were designing it from scratch, I might not make it so, but as it is I'm refactoring the code of some absolute moron (who may or may not have been me 2 years ago) who went and built a handful of projects that use Fetch() as a shared method of each Child class (or rather, each class that I want to make into a child of this new Parent), and it sure would be nice not to have to change every occurrence in those projects to instances.
EDIT:
What I'm running into specifically is that I cannot figure out how to get the tablename into Fetch(), nor how to determine the child class in order to call its constructor on the resulting DataReader.
So to recap:

*

*Parent has Shared Fetch() method

*Method is called as in Child.Fetch()

*Parent gets table info from Child

*Fetch() knows class name of Child so it can call the constructor with the DataReader it fetches.

Can it be done? Many thanks.

A: Parent can have a MustOverride property that Child would be required to implement, that could contain the table information. That solves the problem of how Parent knows what table to look in for each Child, but you cannot have a MustOverride Shared member, so you'd need instances of Child to work with in Parent.
Maybe you could have a generic Fetch on parent that created instances of Child of the correct type based on the type parameter. It's certainly possible given the correct constraints.

A: If Fetch knows the full name of the child class then it should be able to use reflection to get hold of the type of the child and from there I would expect you'll find it plain sailing.


text:
Q: How can I check the status of the specific job that was send to HTcondor? Is there a way to check the status of the specific job (e.g by cluster/process id) and how to retrieve those ids when job is submitted?

A: For further reference i solved this by Condor's ClassAd Mechanism.
I inserted a custom ClassAd attribute in my condor.submit file:
+customAttribute = myID;

Then i can check for example JobStatus for this Job by:
condor_q -constraint 'customAttribute == myID' -f "%s" JobStatus

A: This is possible without requiring a custom ClassAd, as per micco's suggestion (though I can envisage situations where this would be desirable).
You can provide the condor_q command with either a cluster/process ID to return its status, e.g. the following to return the status of job 5:
condor_q 5

Furthermore, if you are submitting clusters of jobs, you can retrieve the status of particular jobs within the batch using the following e.g. for task 123 within cluster 5:
condor_q 5.123


text:
Q: Fragment containing multiple threads in ViewPager In my android application I have one activity containing ViewPager for two fragments. Inside both fragments I am communicating with server, which means there's NOT only UI thread. If I send a request to the server, a progress bar appears till a response comes back inside both fragments. The problem is that when the first fragment is visible to a user, the progress bar of the second fragment also apears.
I want to make it in a such way that the progress bar of one fragment should not disturb another fragment. However, the request should NOT be sent every time a user swithces viewPager.
How can this be done?


text:
Q: pd.read_csv not correctly parsing date/month field when set parse_date = ['column name'] I ran in to this bug while trying to parse the few dates through parse_dates of pandas.read_csv(). In the following code snippet, I'm trying to parse dates that have format dd/mm/yy which is resulting me an improper conversion. For some cases, the date field is considered as month and vice versa.
To keep it simple, for some cases dd/mm/yy get converted to yyyy-dd-mm instead of yyyy-mm-dd.
Case 1:
  04/10/96 is parsed as 1996-04-10, which is wrong.

Case 2:
  15/07/97 is parsed as 1997-07-15, which is correct.

Case 3:
  10/12/97 is parsed as 1997-10-12, which is wrong.

Code Sample
import pandas as pd

df = pd.read_csv('date_time.csv')
print 'Data in csv:'
print df
print df['start_date'].dtypes

print '----------------------------------------------'

df = pd.read_csv('date_time.csv', parse_dates = ['start_date'])
print 'Data after parsing:'
print df
print df['start_date'].dtypes

Current Output
----------------------
Data in csv:
----------------------
  start_date
0   04/10/96
1   15/07/97
2   10/12/97
3   06/03/99
4     //1994
5   /02/1967
object
----------------------
Data after parsing:
----------------------
   start_date
0 1996-04-10
1 1997-07-15
2 1997-10-12
3 1999-06-03
4 1994-01-01
5 1967-02-01
datetime64[ns]

Expected Output
----------------------
Data in csv:
----------------------
   start_date
0   04/10/96
1   15/07/97
2   10/12/97
3   06/03/99
4     //1994
5   /02/1967
object
----------------------
Data after parsing:
----------------------
  start_date

0 1996-10-04
1 1997-07-15
2 1997-12-10
3 1999-03-06
4 1994-01-01
5 1967-02-01
datetime64[ns]

More Comments:
I could use date_parser or pandas.to_datetime() to specify the proper format for date. But in my case, I have few date fields like ['//1997', '/02/1967'] for which I need to convert ['01/01/1997','01/02/1967']. The parse_dates helps me in converting those type of date fields to the expected format without making me to write extra line of code.
Is there any solution for this?
Bug Link @GitHub: https://github.com/pydata/pandas/issues/13063

A: In version pandas 0.18.0 you can add parameter dayfirst=True and then it works:
import pandas as pd
import io

temp=u"""start_date
04/10/96
15/07/97
10/12/97
06/03/99
//1994
/02/1967
"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp),  parse_dates = ['start_date'], dayfirst=True)
  start_date
0 1996-10-04
1 1997-07-15
2 1997-12-10
3 1999-03-06
4 1994-01-01
5 1967-02-01

Another solution:
You can parsing with to_datetime with different parameters format and errors='coerce' and then combine_first:
date1 = pd.to_datetime(df['start_date'], format='%d/%m/%y', errors='coerce')
print date1
0   1996-10-04
1   1997-07-15
2   1997-12-10
3   1999-03-06
4          NaT
5          NaT
Name: start_date, dtype: datetime64[ns]

date2 = pd.to_datetime(df['start_date'], format='/%m/%Y', errors='coerce')
print date2
0          NaT
1          NaT
2          NaT
3          NaT
4          NaT
5   1967-02-01
Name: start_date, dtype: datetime64[ns]

date3 = pd.to_datetime(df['start_date'], format='//%Y', errors='coerce')
print date3
0          NaT
1          NaT
2          NaT
3          NaT
4   1994-01-01
5          NaT
Name: start_date, dtype: datetime64[ns]

print date1.combine_first(date2).combine_first(date3)
0   1996-10-04
1   1997-07-15
2   1997-12-10
3   1999-03-06
4   1994-01-01
5   1967-02-01
Name: start_date, dtype: datetime64[ns]


text:
Q: JSON string containing \" not being parsed I am creating a JSON string using James Newton-King's excellent JSON libary.
I create the JSON string using the following line of code:
string userJSON = Newtonsoft.Json.JsonConvert.SerializeObject(existingAdminUser, Newtonsoft.Json.Formatting.None);

The result looks as follows:
"{\"LoginId\":\"0f1b6c88-08ec-416f-b221-7568dc7c242a\",\"Firstname\":\"Charles\",\"Surname\":\"Barber\",\"Fullname\":\"Charles Barber\",\"Email\":\"charles17@test76876.com\",\"Systems\":null,\"IsValid\":false,\"IsValidExcludingSystems\":true,\"ValidationMessage\":\"\"}"

I am then placing this string into my http response using the following line of code:
HttpContext.Current.Response.Write("<input type=\"hidden\" name=\"adminextrainfo\" id=\"adminextrainfo\" value=\"" + userJSON + "\" />");

I am then trying to access/parse the JSON at the client, using:
var userdetails = $.parseJSON(valueOfHiddenField);

The parse attempt fails, and if I try viewing the contents of the field (using an alert) then I only see the very first { char.  It seems that the \" character sequence is being treated as a newline by js.  How can I encode the hidden field value at the server, or how can I deal with the hidden field value at the client such that it 'handles' the \" character sequence?
Thanks very much.

A: So we have a little escaping / encoding mess here. Your string:
"{\"LoginId\":\"0f1b6c88-08ec-416f-b221-7568dc7c242a\",\"Firstname\":\"Charles\",\"Surname\":\"Barber\",\"Fullname\":\"Charles Barber\",\"Email\":\"charles17@test76876.com\",\"Systems\":null,\"IsValid\":false,\"IsValidExcludingSystems\":true,\"ValidationMessage\":\"\"}"

isn't correct unless it is shown in some C# context (e.g. the Visual Studio debugger). All these slashes are only needed if you put this in C# source code. If you assign it to a variable, the variable will store it without the slashes as they are for escaping within the C# code only. They can't be the root of your problem because they only exist within the Visual Studio Debugger, not within your application.
However, you can't just insert the JSON into HTML. It contains several characters (e.g. the double quote at the second position), that have to be escaped because they have a special meaning in HTML.
So your fix should be:
HttpContext.Current.Response.Write("<input type=\"hidden\" name=\"adminextrainfo\" id=\"adminextrainfo\" value=\"" + Server.HtmlEncode(userJSON) + "\" />");


text:
Q: Compare 2 strings in C I'm testing a small program which basically compares whether 2 input strings are identical (as strcmp does). However I keep getting result saying 2 strings are different no matter what. If someone could spot out some mistakes I'd appreciate
int comp(char str1[], char str2[]) {
    int i = 0;
    while (str1[i] == str2[i]) {
        if (str1[i] == '\0' || str2[i] == '\0')
            break;
        i++;
    }
    if (str1[i] == '\0' && str2[i] == '\0')
        return 0;
    else
        return -1;
}

int main(int argc, char * * argv) {
    int cmp;
    char str1[1000], str2[1000];
    cmp = comp(str1, str2);
    if (cmp == 0)
        printf("The two strings are identical.\n");
    else
        printf("The two strings are different.\n");
    return 0;
}

A: Your function works just fine. The only problem is that your two character arrays are not initialized and that causes Undefined Behavior.

A: here is one implementation, using the command line parameters.
#include <stdio.h>
#include <stdlib.h>

int comp(char str1[], char str2[])
{
    int i = 0;
    while (str1[i] == str2[i])
    {
        if (str1[i] == '\0' || str2[i] == '\0')
            break;
        i++;
    }

    if (str1[i] == '\0' && str2[i] == '\0')
        return 0;
    else
        return -1;
}

int main(int argc, char * * argv)
{
    if( 3 != argc )
    {
        printf( "USAGE: %s, firstString secondString\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // implied else, correct number of parameters

    if ( !comp( argv[1], argv[2]) )
        printf("The two strings are identical.\n");
    else
        printf("The two strings are different.\n");
    return 0;
}


text:
Q: Understanding electrons in a weak periodic potential fourier analysis I have been trying to understand Ashcroft's take on electrons in a weak periodic potential, and his approach by Fourier analysis is proving to be extremely challenging. I understand how to get to the master equation:

and then he assumes this (which by itself is odd, but I assume it is to isolate a band and study it isolated from the others):

But this is what I can't wrap my head around:

I can't understand the behaviour of $O(U^2)$. How does he get to that conclusion. I have read the text several times, but I can't make sense of it. Can someone help me? I have looked into parseval's theorem to see if it would help relate the coefficients $c_{k-K}$ but that theorem relates the square of the coefficients to the energy, so it didn't quite help.

A: It is because of this passage before Eq. (9.10):

Since we are examining that solution for which $c_{k-K}$ vanishes when
  $K\ne K_1$ in the limit of vanishing $U$

In other words, in the sum in Eq. (9.10) the coefficient $c_{k-K'}$ are also of order $\mathcal{O}(U)$, which multiplied by $U$ (and assuming no degeneracy, so that the denominator cannot be small) gives $\mathcal{O}(U^2)$.

A: Well, this is easy. Simple math, I suppose.
We have
$$\mathbf{c_{k-K} = \frac{U_{K_1-K}\, c_{k-K_1}}{\epsilon-\epsilon^{\circ}_{k-K}} + \sum_{K'\ne K_1} \frac{U_{K'-K}\, c_{k-K'}}{\epsilon-\epsilon^{\circ}_{k-K}}}$$
Now in place of $\mathbf{c_{k-K'}}$ in the numerator of the 2nd expression in RHS, you plug in the above expression for $\mathbf{c_{k-K}}$.
Then you get the following expression:
$$\mathbf{c_{k-K} = \frac{U_{K_1-K}\, c_{k-K_1}}{\epsilon-\epsilon^{\circ}_{k-K}} + \sum_{K'\ne K_1} \frac{U_{K'-K}}{\epsilon-\epsilon^{\circ}_{k-K}}} \left(\mathbf{\frac{U_{K_1-K'} \, c_{k-K_1}}{\epsilon-\epsilon^{\circ}_{k-K'}} + \sum_{K''\ne K_1} \frac{U_{K''-K'}\, c_{k-K''}}{\epsilon-\epsilon^{\circ}_{k-K'}}}\right)$$
which on further simplification gives:
$$\mathbf{c_{k-K} = \frac{U_{K_1-K}\, c_{k-K_1}}{\epsilon-\epsilon^{\circ}_{k-K}} + \sum_{K'\ne K_1} \frac{U_{K'-K}\, U_{K_1-K'} \, c_{k-K_1}}{(\epsilon-\epsilon^{\circ}_{k-K})(\epsilon-\epsilon^{\circ}_{k-K'})} + \sum_{K'\ne K_1} \sum_{K''\ne K_1} \frac{U_{K'-K}\, U_{K''-K'}\, c_{k-K''}}{(\epsilon-\epsilon^{\circ}_{k-K})(\epsilon-\epsilon^{\circ}_{k-K'})}}$$
Now, if you look at the second and third terms in the RHS, it involves quadratic terms of $U_k$. In other words, in big O notation, $\mathcal{O}(U^2)$.
In this way, the author arrives at:
$$\mathbf{c_{k-K} = \frac{U_{K_1-K}\, c_{k-K_1}}{\epsilon-\epsilon^{\circ}_{k-K}} + \mathcal{O}(U^2) }$$
Since he is talking about weak potentials here, the author later neglects quadratic terms in U to quantify the effect of weak periodic potentials to create Wannier functions, leading to the formation of the s-band, p-band so on, for different overlap integrals.
Keep on reading Ashcroft and Mermin, it is a very good book for understanding the basics of solid-state physics and condensed matter physics.
Hope this helps you.


text:
Q: Drupal SMTP doesn't work for contact us page? I have installed a smtp module. and also test it with the test email id. it sends email to the test add.But doesn't work with the contact us page. it's not sending mail to admin. through the smtp or either php mail. as in drupal drupal_mail().
I just have configured smtp details in the admin section of the site.not anywhere else. though its working with test email so it should work with contact us page but it doesn't.
please help me.!!!!

A: The email in the site information should be the same as the email in SMTP authentication or
your mail goes nowhere!
Please check the demo over here...


text:
Q: Question mark usage/position when sentence ends with a declarative quotation?
Who said "I am hungry?"

The quotation is not a question, but do I put "my" question mark there anyway?

This is related to, but not the same as Position of question mark when sentence doesn't end with question

A: If you put the question mark inside the speech marks, the speech becomes a question. Your example is thus incorrect as 'I am hungry?' makes little sense as a question, unless the person has brain damage and is unaware of his hunger!
A more valid example might be:

He asked, "Which way to the museum?"

If you shift the ? outside the speech marks:

Who said, "I am hungry"?

Then the whole sentence is now the question: the speaker is asking who stated that they were hungry.
You only use one punctuation mark when using speech/quotation marks.


text:
Q: Get value from JMeter variable like varName_1, varName_2 in a loop I'm getting multiple rows from database through JMeter. I need to construct a string using those values.
I have a for loop that iterates from 1 to varName_#. How do I evaluate the values of varName_1, varName_2 etc.
I tried using ${__V(varName_${i})}, ${__eval(varName_${i})},${__evalVar(varName_${i})}
for(int i=1; i <= Integer.parseInt(vars.get("varName_#"); i++) {
    myString.append(newline);
    myString.append("{");
    myString.append(newline);
    myString.append("\"id\" : ").append(${__V(varName_${i})}).append(",");
    myString.append(newline);
    myString.append("\"version\" : 0").append(",");
    myString.append(newline);
    myString.append("\"children\" : []");
    myString.append(newline);
    myString.append("}");

    if(i != Integer.parseInt(vars.get("varName_#")) {
        children.append(",");
    }
}

A: Use vars to get value in index i:
 vars.get("varName_" + i);

In your code:
 myString.append("\"id\" : ").append(vars.get("varName_" + i));


text:
Q: SqfliteDatabaseException (DatabaseException(near ")": syntax error I have created a data table with sqflite. But it showed me a syntax error. Can you tell me please where is the syntax error here?
Future _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE $table (
            $columnId INTEGER PRIMARY KEY,
            $columnfid VARCHAR,
            $columnfname TEXT,
          )
          ''');
  }

Here is the error:
Exception has occurred.
SqfliteDatabaseException (DatabaseException(near ")": syntax error (code 1 SQLITE_ERROR): , while compiling: CREATE TABLE fid_table (
            id INTEGER PRIMARY KEY,
            fid VARCHAR,
            fname TEXT,
          )) sql '          CREATE TABLE fid_table (
            id INTEGER PRIMARY KEY,
            fid VARCHAR,
            fname TEXT,
          )
          ' args []})

A: The issue is with the trailing comma (,) of the SQL, i.e after the last TEXT.
Instead of
await db.execute('''
      CREATE TABLE $table (
        $columnId INTEGER PRIMARY KEY,
        $columnfid VARCHAR,
        $columnfname TEXT,
      )
      ''');

try
wait db.execute('''
      CREATE TABLE $table (
        $columnId INTEGER PRIMARY KEY,
        $columnfid VARCHAR,
        $columnfname TEXT
      )
      ''');

Also, the extra quotes are not required as well. So, you could write this as well.
wait db.execute('
      CREATE TABLE $table (
        $columnId INTEGER PRIMARY KEY,
        $columnfid VARCHAR,
        $columnfname TEXT
      )
      ');


text:
Q: How can I interpret "energy" in signals? I am learning about various signal processing methods in my university course, and I can't seem to grasp what 'energy' in signals represent. I mean, I know that it is the integral of the absolute value of energy squared (side question: why is absolute value needed?), but I don't know the meaning of what this energy is. Is there an intuitive way to think about these energies? Thanks a lot.

A: I try to give an explanation in the time and frequency domains, as normaly
used in Telecomunication Systems.
If you have a physical process described in the time by an oscillating
signal $s(t)$ such as an electrical voltage or current, the description
in the frequency domain is given by its spectrum
$$\overrightarrow{S}(\omega )=\frac{1}{%
2\pi }\int_{-\infty }^{\infty }s(t)e^{-i\omega t}dt$$
The signal is $$%
s(t)=\int_{-\infty }^{\infty }\overrightarrow{S}(\omega )e^{-i\omega
t}d\omega ,$$
where $\omega =2\pi f=\frac{2\pi }{T}$ is the angular frequency.
The function $\overrightarrow{S}(\omega )$ is the Fourier Transform of $s(t)$ and $s(t)$ is the inverse transform. Note: a definition of the pair $(s(t),\overrightarrow{S}(\omega ))$  with different constant factors is possible.
The "energetic activity" during the infinitesimal time interval $%
\delta t$ is $\delta E=s^{2}(t)\delta t$ (excluding a constant with physical
dimensions, see note below). The instantaneous power is $$p(t)=\underset{\delta t\rightarrow 0%
}{\lim }\frac{\delta E}{\delta t}=s^{2}(t).$$
Therefore the "energy" of the full process is
$$E=\int_{-\infty }^{\infty }s^{2}(t)dt=2\pi \int_{-\infty }^{\infty
}S^{2}(\omega )d\omega ,$$
where $S(\omega )=\left\vert \overrightarrow{S}(\omega )\right\vert $ and $\overrightarrow{S}(\omega )=S(\omega )e^{i\psi (\omega )}$ is the
distribution or spectrum with the properties $S(-\omega )=S(\omega )$, $\psi
(-\omega )=\psi (\omega ).$ The equality between both integrals is known as the Parseval's Theorem.
Note on the  physical dimensions. e.g. in electrical circuits the product of a voltage $V$ by a current $I$ is a power  (energy/time).  By the Ohm's law, in d.c. circuits, $V=RI$ and $VI=RI^2=\dfrac{1}{R}V^2$; in a.c. circuits $| \overrightarrow{V}|| \overrightarrow{I}|=R |\overrightarrow{I}|^2$.
From the Wikipedia:

"The power spectral density (PSD)
  (...) describes how the power of a
  signal or time series is distributed
  with frequency. Here power can be the
  actual physical power, or more often,
  for convenience with abstract signals,
  can be defined as the squared value of
  the signal, that is, as the actual
  power dissipated in a load if the
  signal were a voltage applied to it."

A: The energy is the energy carried in the signal.
The absolute value is probably because signal amplitudes are often represented by phasors, especially in the context of electromagnetic radiation or in the context of processing via Fourier analysis. And since it uses complex numbers, and the square of a complex number $z^2$ is not the same as its 'absolute value squared' $|z|^2$ (simplest case, take $z = -i$, the imaginary unit, then the former is -1 and the latter 1$), in the formla it is customary to write an absolute value.
That we associate energy with the square of the wave amplitude is due to the mechanical model of small amplitude waves of d'Alembert. Essentially the wave medium is thought of as a bunch of springs coupled together. For springs, with Hooke's law we have that the mechanical energy is proportional to the square of the amplitude of displacement. The analogy that the displacement of the media due to the wave should be well approximated by a simple spring leads us to take the infinitesimal mechanical energy associated to an infinitesimal chunck of the medium to be the square of the wave amplitude. So adding them all up you get an integral.

A: The electrical power in a resistive circuit is given by $P = I V$. Frequently one has a fixed resistance (or more in general, impedance), so that voltage and current are variable; taking voltage as independent variable, we have $P = V^2/R$. This gives the instantaneous power (energy over time unit), and hence also gives the average power (or energy over some finite time interval) if the voltage is constant (DC current). When the voltage varies peridocally in time (for example, AC current), the above equation applies to each instant of time ($ P(t) = V(t)^2/R $) , so that, for getting the average power over a period one must integrate (see here). That's why AC energy is typically measured in RMS units: a 120V power outlet gives a sinuosid of approx. 170V peak voltage: that sinusoid has the same energy as  a constant 120V voltage.
This is the case of electric signals, but the analogy applies in other fields.
Another (related) motivation comes from the Parseval's theorem


text:
Q: How to remove 'label' decorator from Zend 2 form I have the simple Radio element:
$form->add([
            'name' => 'account_type',
            'type' => 'Zend\Form\Element\Radio',
            'options' => [
                'label' => 'Account type',
                'value_options' => [
                    1 => 'Employer',
                    2 => 'Performer'
                ]
            ]
        ]
    );

But in my view I get this html:

  Account type

      <input type="radio" name="account_type" class="account_type" value="1">Employer

      <input type="radio" name="account_type" class="account_type" value="2">Performer

How I can to remove this empty label wrapper around an radio element? Or how I can to insert some tag after radio element? Thanks.

A: I extended standard view helper:
<?php
   namespace Application\Form\View\Helper;

   use Zend\Form\View\Helper\FormRadio;
   use Zend\Form\Element\Radio as RadioEl;

   class FormRadioElement extends FormRadio
   {
       protected function renderOptions(RadioEl $element, array $options, array $selectedOptions, array $attributes)
       { ...

... and set template in helper like:
$template  = '%s%s';

Then I declared it in my bootstrap:
public function getViewHelperConfig() {
    return [
        'invokables' => [
            'formRadioHelper' => 'Application\Form\View\Helper\FormRadioElement',
        ]
    ];
}

... and called in my view like:
<?php echo $this->formRadioHelper($form->get('account_type'))?>


text:
Q: Error: Can't find npm module 'moment' I have a Meteor app that runs perfectly on localhost, but when I deploy it to a remote heroku server, I get the following errors.
(I am implementing this)
Any ideas how to fix this please?
2016-09-09T13:26:02.533532+00:00 heroku[web.1]: Starting process with command `.meteor/heroku_build/bin/node .meteor/heroku_build/app/main.js`
2016-09-09T13:26:06.806440+00:00 heroku[web.1]: Process exited with status 1
2016-09-09T13:26:06.813921+00:00 heroku[web.1]: State changed from starting to crashed
2016-09-09T13:26:06.704013+00:00 app[web.1]: /app/.meteor/heroku_build/app/programs/server/node_modules/fibers/future.js:280
2016-09-09T13:26:06.704027+00:00 app[web.1]:                        throw(ex);
2016-09-09T13:26:06.704028+00:00 app[web.1]:                        ^
2016-09-09T13:26:06.704029+00:00 app[web.1]:
2016-09-09T13:26:06.704030+00:00 app[web.1]: Error: Can't find npm module 'moment'. Did you forget to call 'Npm.depends' in package.js within the 'modules-runtime' package?
2016-09-09T13:26:06.704031+00:00 app[web.1]:     at Object.Npm.require (/app/.meteor/heroku_build/app/programs/server/boot.js:198:17)
2016-09-09T13:26:06.704032+00:00 app[web.1]:     at options.fallback (packages/modules-runtime/modules-runtime.js:21:1)
2016-09-09T13:26:06.704032+00:00 app[web.1]:     at require (packages/modules-runtime/.npm/package/node_modules/install/install.js:88:1)
2016-09-09T13:26:06.704033+00:00 app[web.1]:     at meteorInstall.server.main.js (server/main.ts:1:19)
2016-09-09T13:26:06.704035+00:00 app[web.1]:     at require (packages/modules-runtime/.npm/package/node_modules/install/install.js:82:1)
2016-09-09T13:26:06.704035+00:00 app[web.1]:     at server/main.ts:65:4
2016-09-09T13:26:06.704036+00:00 app[web.1]:     at /app/.meteor/heroku_build/app/programs/server/boot.js:292:10
2016-09-09T13:26:06.704036+00:00 app[web.1]:     at Array.forEach (native)

If I heroku run bash to log onto heroku. In /app/typings/globals I see the following:
es6-collections  es6-promise  google-maps  google.maps  meteor  moment

This seems to match what is on the Windows localhost:

Moments also exist in node_modules

Here is my node_modules\moment\package.js:
var profile = {
    resourceTags: {
        ignore: function(filename, mid){
            // only include moment/moment
            return mid != "moment/moment";
        },
        amd: function(filename, mid){
            return /\.js$/.test(filename);
        }
    }
};

My package.json:
{
  "dependencies": {
    "@angular/common": "^2.0.0-rc.4",
    "@angular/compiler": "^2.0.0-rc.4",
    "@angular/core": "^2.0.0-rc.4",
    "@angular/forms": "^0.2.0",
    "@angular/http": "^2.0.0-rc.4",
    "@angular/platform-browser": "^2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "^2.0.0-rc.4",
    "@ionic/cloud-angular": "^0.4.0",
    "angular2-meteor": "^0.6.2",
    "angular2-moment": "^0.8.2",
    "es6-shim": "^0.35.0",
    "ionic-angular": "^2.0.0-beta.11",
    "ionic-native": "1.3.2",
    "ionicons": "3.0.0",
    "meteor-client-side": "^1.3.4",
    "moment": "^2.14.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "socket.io": "^1.4.8",
    "zone.js": "^0.6.12"
  },

snippet from logs when deploying:
remote: -----> Building Meteor app with ROOT_URL: https://git.heroku.com/remote-thewhozoo.git
remote: server/collections.ts (1, 21): Cannot find module 'meteor/mongo'.
remote: server/collections.ts (2, 29): Cannot find module 'api/models'.
remote: server/methods.ts (1, 22): Cannot find module 'meteor/meteor'.
remote: server/methods.ts (2, 28): Cannot find module 'meteor/check'.
remote: server/main.ts (1, 25): Cannot find module 'moment'.
remote: server/main.ts (2, 22): Cannot find module 'meteor/meteor'.
remote:
remote: Unable to resolve some modules:
remote:
remote:   "moment" in /tmp/build_29ec6195d953bd56c0670f7d9ee489a4/server/main.js
remote: (os.linux.x86_64)
remote:
remote: If you notice problems related to these missing modules, consider running:
remote:
remote:   meteor npm install --save moment
remote:
remote: -----> Moving built slug to /tmp/build_29ec6195d953bd56c0670f7d9ee489a4/.meteor/heroku_build/app
remote: -----> Installing npm production dependencies on built slug
remote:
remote: > fibers@1.0.13 install /tmp/build_29ec6195d953bd56c0670f7d9ee489a4/.meteor/heroku_build/app/programs/server/node_modules/fibers
remote: > node build.js || nodejs build.js
remote:
remote: `linux-x64-v8-4.5` exists; testing
remote: Binary is fine; exiting
remote:
remote: > meteor-dev-bundle@0.0.0 install /tmp/build_29ec6195d953bd56c0670f7d9ee489a4/.meteor/heroku_build/app/programs/server
remote: > node npm-rebuild.js
remote:
remote: {
remote:   "meteor-dev-bundle": "0.0.0",
remote:   "npm": "3.10.6",
remote:   "ares": "1.10.1-DEV",
remote:   "http_parser": "2.7.0",
remote:   "icu": "56.1",
remote:   "modules": "46",
remote:   "node": "4.5.0",
remote:   "openssl": "1.0.2h",
remote:   "uv": "1.9.1",
remote:   "v8": "4.5.103.37",
remote:   "zlib": "1.2.8"
remote: }

index.d.ts
declare module 'moment' {
    var moment: moment.MomentStatic;
    export = moment;
}

I do have symbolic links in the root of the meteor project:

UPDATE
I have found the problem I think, but I am not 100% sure how to solve it yet.
The issue is that the symbolic links are pointing to directories that exist locally, but not on the remote server.

UPDATE
I remove all symbolic links, and have the files there instead, deploy, and I still get the same error when the server tries to start:
2016-09-11T15:23:06.155551+00:00 heroku[web.1]: State changed from crashed to starting
2016-09-11T15:23:09.146909+00:00 heroku[web.1]: Starting process with command `.meteor/heroku_build/bin/node .meteor/heroku_build/app/main.js`
2016-09-11T15:23:13.712742+00:00 heroku[web.1]: State changed from starting to crashed
2016-09-11T15:23:13.640003+00:00 app[web.1]: /app/.meteor/heroku_build/app/programs/server/node_modules/fibers/future.js:280
2016-09-11T15:23:13.640048+00:00 app[web.1]:                        throw(ex);
2016-09-11T15:23:13.640073+00:00 app[web.1]:                        ^
2016-09-11T15:23:13.640075+00:00 app[web.1]: Error: Can't find npm module 'moment'. Did you forget to call 'Npm.depends' in package.js within the 'modules-runtime' package?
2016-09-11T15:23:13.640076+00:00 app[web.1]:     at Object.Npm.require (/app/.meteor/heroku_build/app/programs/server/boot.js:198:17)
2016-09-11T15:23:13.640077+00:00 app[web.1]:     at options.fallback (packages/modules-runtime/modules-runtime.js:21:1)
2016-09-11T15:23:13.640078+00:00 app[web.1]:     at meteorInstall.server.main.js (server/main.ts:1:19)
2016-09-11T15:23:13.640079+00:00 app[web.1]:     at require (packages/modules-runtime/.npm/package/node_modules/install/install.js:82:1)
2016-09-11T15:23:13.640079+00:00 app[web.1]:     at server/main.ts:65:4
2016-09-11T15:23:13.723869+00:00 heroku[web.1]: Process exited with status 1

Any Ideas please?
I have run: meteor npm install --save
I have found this in boot.js, but I am not sure what the author was doing.
    try {
      return require(name);
    } catch (e) {
      // Try to guess the package name so we can print a nice
      // error message
      // fileInfo.path is a standard path, use files.pathSep
      var filePathParts = fileInfo.path.split(files.pathSep);
      var packageName = filePathParts[1].replace(/\.js$/, '');

      // XXX better message
      throw new Error(
        "Can't find npm module '" + name +
          "'. Did you forget to call 'Npm.depends' in package.js " +
          "within the '" + packageName + "' package?");
      }

UPDATE
I removed the .gitignore of node_modules/, and I don't get any errors now.

However, I am new to Meteor, so not sure how to test this. But when I try invoke the app with http://remote-thewhozoo.herokuapp.com/ or https://remote-thewhozoo.herokuapp.com/ I get a 404 error:
2016-09-11T16:20:15.183895+00:00 heroku[router]: at=info method=GET path="/sockjs/info?cb=jwgw2yuvgl" host=remote-thewhozoo.herokuapp.com request_id=a49fafb2-9708-46d2-8117-2c789bfa6a3e fwd="105.186.215.147" dyno=web.1 connect=1ms service=2ms status=404 bytes=132

I do check the Mongo Database, and it has got the collections created by my app. So Meteor must be running, I just don't know how to access it.

Any ideas please?

A: Make sure this line:"moment": "^2.14.1" is your package.json
then run npm install

A: Can you try meteor npm install in your project root?
If moment didn't appear in that list, can you try meteor npm install --save moment?
Otherwise, could you please post your package.js - it should be in app/programs/server/

A: I think it's a problem with your buildpack. Try following this guide - https://meteorcoder.wordpress.com/2016/09/24/how-to-deploy-meteor-apps-with-heroku/

A: I ran: npm install moment react-moment
& it worked. The official npm site has two different ways of installing this & they both gave me errors.

A: To solve the error "Cannot find module 'moment'", make sure to install the moment package by opening your terminal in your project's root directory and running the following command: npm i moment and restart your IDE and development server.


text:
Q: $m\bar a = \bar m \cdot \bar a$ in the ring $\mathbb Z/n \mathbb Z$ Let $n\geq 1$ be an integer and consider the quotient ring $\mathbb Z/n \mathbb Z$. Let $\bar a$ be one of its element (i.e., an equivalence class).
Consider $m\in \mathbb Z$ and remember that $m\bar a$ is the notation for repeated addition of $\bar a$: if $m\geq 1$, $m\bar a = \bar a+\ldots+\bar a$.
I want an "abstract algebra" argument for the equality $$m\bar a = \bar m \cdot \bar a.$$
I have a pedestrian proof: induction on $m$ proves the equality for all $m\geq 0$, and for $m\leq 0$ we have $$m\bar a = -((-m)\bar a) = -(\overline{- m} \cdot \bar a) =\bar m \cdot \bar a.$$
I'm looking for a shorter proof, possibly using some adequate morphism.

A: Because $\mathbb{Z}$ is a commutative ring one has that quotients by all ideals form rings, i.e. $\mathbb{Z}/n\mathbb{Z}$ is a ring where the ring strucutre is inherited from $\mathbb{Z}$. Let me specify:
Let $A$ be any commutative ring with a unity element $1$. Let $\mathfrak{a}\subset A$ be an ideal. Then $A/\mathfrak{a}$ is a ring with the following operations:

*

*$(a+\mathfrak{a})+(b+\mathfrak{a}) = (a+b) + \mathfrak{a}, \ \forall a,b\in A$

*$(a+\mathfrak{a})\cdot (b+\mathfrak{a}) = (ab) + \mathfrak{a}, \ \forall a,b\in A$
and one cheks once that these operations are well defined etc. but these are simple tasks. Furthermore one gets a canonical ring homomorphism $\phi:A\to A/\mathfrak{a}, x\mapsto x+\mathfrak{a}$ (that this indeed is a ring homomorphism is easily checked) and it holds that $\ker \phi = \mathfrak{a}$.
Back to the concrete example we thus get a canonical ring homomorphism $\mathbb{Z}\to \mathbb{Z}/n\mathbb{Z}, x \mapsto x+n\mathbb{Z}$.
Now clearly every ring is an algebra over $\mathbb{Z}$ (there is a canonical ring homomorphism from $\mathbb{Z}$ into any commutative ring with $1$). Therefore we get an induced homomorphism of $\mathbb{Z}$-modules where we define the $\mathbb{Z}$-module strucutre of $\mathbb{Z}/n\mathbb{Z}$ as $(m\cdot (k+n\mathbb{Z})):= mk + n\mathbb{Z}$ (this again is the module structure given by the fact that $\mathbb{Z}/n\mathbb{Z}$ is an algebra over $\mathbb{Z}$).
Hence we get $m\cdot(k+\mathbb{Z}) = mk+n\mathbb{Z}$. As desired.
The point I am trying to make is that the formula you are trying to prove has nothing to do in particular with the ring $\mathbb{Z}/n\mathbb{Z}$, rather it holds for any 'ol commutative ring by the fact that we get canonical morphisms from $\mathbb{Z}$ into any ring (this can be rephrased in the language of category theory: $\mathbb{Z}$ is an inital object in the category of commutative unitary rings).

A: Hint:
Let $R$ be a commutative ring.
Define the multiple of a ring element $r\in R$ inductively as follows:
$0\cdot r = 0$, $(m+1) \cdot r = m\cdot r +r$ for $m\geq 0$ and $m\cdot r = (-m)\cdot (-r)$ for $m<0$.
Then for each $m>0$, $m\cdot r = r+\ldots+r$, the $m$-fold of $r$, and for each $m<0$, $m\cdot r = (-r)+\ldots+(-r)$, $-m>0$ times $-r$.
Example: $2\cdot r = r+r$ and $(-2)\cdot r = (-r)+(-r)$.
Now the left-hand side of your equation has the rigorous definition $m\cdot \bar a$ given as the $m$-fold of $\bar a$.
In view of the right-hand side, $\bar m = \bar 1+\ldots +\bar 1$, the $m$-fold of $\bar 1$, if $m>0$, $\bar m= \bar 0$ if $m=0$, and $\bar m =-\bar 1 +\ldots + (-\bar 1)$ if $m<0$.
Example: $\bar 2\cdot \bar a = (\bar 1 + \bar 1)\cdot \bar a$ and $\overline{-2}\cdot \bar a = ((-\bar 1) + (-\bar 1))\cdot \bar a$.
To extend the example to your equation:
$2\cdot \bar a= \bar a + \bar a$ and $\bar 2\cdot \bar a= (\bar 1 + \bar 1)\cdot \bar a = \bar a + \bar a$.


text:
Q: choosing Fernet encryption algorithm I'm using Fernet, and confused with cipher algorithms..  how can i try AES, DES, Twofish, RC4 or other algorithms while generating my key.
(sorry if messed up:| just new to cipher :)
>>> from cryptography.fernet import Fernet
>>> key = Fernet.generate_key()
>>> f = Fernet(key)
>>> token = f.encrypt(b"my deep dark secret")
>>> token
b'...'
>>> f.decrypt(token)
b'my deep dark secret'

A: you can not use other encryption algorithms with Fernet as in Fernet Dosc says, you can only AES.


text:
Q: Ember Simple Auth - logout when session is invalidated I set up ember simple auth using oauth2 authentication/ Bearer authorization with an express server. The flow works as intended: access/refresh tokens are issued and refreshed on schedule. When the user logs out, the tokens are revoked on the server and the session is invalidated. Now in the instance that I manually deleted the refresh token on the server, ember will log 'The authenticator "authenticator:oauth2" rejected to restore the session - invalidating…' in the console the next time it requests a refresh. At this point, if I try to reload the page, the session is invalidated and I will then be redirected to the login page.
I would like to invalidate the session/log user out as soon as the token refresh fails, without having to first refresh the page. I thought this was the normal behavior, but I must be wrong/missing something.

A: ember-simple-auth doesn't know your session is invalid unless you say so. Depending on how you're requesting refresh tokens, you should either:

*

*call session.invalidate() on failed refresh

*if you're refreshing via an authenticator hook somehow (restore, authenticate, invalidate), return a rejected promise

That will tell ember-simple-auth to redirect to its configured login route.
Note: ember-simple-auth does react to changes to its browser-side session store. That's probably what you're thinking of.


text:
Q: MySQL limpeza de logs Em meu servidor MySQL o arquivo myaccess.log localizado em MySQL/logs/ está com um tamanho grande, em torno de 30GB. Gostaria se possível zerar este arquivo, porém preciso ter certeza que não irá comprometer informações do banco de dados. Se alguém puder me ajudar com procedimentos, eu agradeço.
Obrigado.

A: Eu utilizo um programa para edição de arquivos com tamanhos muito grandes, assim como o seu. Se chama PilotEdit, exise versão paga e free, que vai te atender.
Segue as instruções dos comentários, faz um backup, altera o arquivo, e sobe.


text:
Q: Generating File in Javascript for Firefox OS I'm developping a Firefox OS application and i'm looking for generate a files with Javascript.
I know how to use DeviceStorage API and I also know that a file has property of Blob.
But I would like to generate files to full device memory. For example I would like to generate 1 file of 1Megabytes. But I have no idea how to do that.
Someone has an idea ?
Thanks

A: For a 1mB file you will need to fill an array with 1000000 bytes.
Then by using the constructor:
var typedArray = new ArrayBuffer(1000000);
var blob = new Blob([typedArray], {type: 'application/octet-binary'});

You will end up with a 1mB blob of binary data that could be saved to a file using standard api.


text:
Q: PCL (point-cloud-library) range image too small I downloaded a sample pcap for the velodyne-32E lIDAR and saved 1 of the frames as a csv file. Using PCL, I want to visualise the point cloud as a range image as well as interacting with it for further processing purposes (camera-lidar calibration). So far, I followed the tutorials and set the vertical/horizontal angular resolution to .16 and 1.33 degrees respectively. The point cloud seemed fine, but the generated image is so small that I don't really think I can see anything.
Since I'm using RangeImageVisualiser and not PCLVisualiser, I don't really seem to be given any controls here. Any idea how I can make my image more viewable?
ifstream file (argv[1]);
float x,y,z;

pcl::PointCloud<pcl::PointXYZ> pointCloud;

while (file >> x >> y >> z){
    pcl::PointXYZ point;
    point.x = x;
    point.y = y;
    point.z = z;

    pointCloud.points.push_back(point);
    //cout << "X: " << x;
    //cout << "Y: " << y;
    //cout << "Z: " << z;
}

cout << "they are " << pointCloud.points.size() << " points\n";
pointCloud.width = (uint32_t) pointCloud.points.size();
pointCloud.height = 1;

//float angularResolution = (float) (  1.0f * (M_PI/180.0f));  //   1.0 degree in radians
float angularResolution_x = (float) (  0.16f * (M_PI/180.0f));  //   1.0 degree in radians
float angularResolution_y = (float) (  1.33f * (M_PI/180.0f));  //   1.0 degree in radians
float maxAngleWidth     = (float) (360.0f * (M_PI/180.0f));  // 360.0 degree in radians
float maxAngleHeight    = (float) (180.0f * (M_PI/180.0f));  // 180.0 degree in radians
Eigen::Affine3f sensorPose = (Eigen::Affine3f)Eigen::Translation3f(0.0f, 0.0f, 0.0f);
pcl::RangeImage::CoordinateFrame coordinate_frame = pcl::RangeImage::LASER_FRAME;
float noiseLevel=0.00;
float minRange = 0.0f;
int borderSize = 1;

//pcl::RangeImage rangeImage;
pcl::RangeImageSpherical rangeImage;
rangeImage.createFromPointCloud(pointCloud, angularResolution_x, angularResolution_y, maxAngleWidth, maxAngleHeight, sensorPose, coordinate_frame, noiseLevel, minRange, borderSize);
cout << rangeImage << "\n";

//visualize point cloud
boost::shared_ptr<pcl::RangeImage> range_image_ptr(&rangeImage);
pcl::PointCloud<PointType>::Ptr point_cloud_ptr (&pointCloud);

pcl::visualization::PCLVisualizer viewer ("3D viewer");
viewer.setBackgroundColor(1,1,1);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointWithRange> range_image_color_handler (range_image_ptr, 0, 0, 0);
viewer.addPointCloud(range_image_ptr, range_image_color_handler, "range image");
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "range image");

//viewer.addCoordinateSystem(1.0f);
//pcl::visualization::PointCloudColorHandlerCustom<PointType> point_cloud_color_handler (point_cloud_ptr, 150, 150, 150);
//viewer.addPointCloud (point_cloud_ptr, point_cloud_color_handler, "original point cloud");

viewer.initCameraParameters();
setViewerPose(viewer, rangeImage.getTransformationToWorldSystem());

pcl::visualization::RangeImageVisualizer widget("please work");
widget.showRangeImage(rangeImage);
widget.setSize(500, 500);

while (!viewer.wasStopped()){
    widget.spinOnce();
    viewer.spinOnce();
    pcl_sleep(.01);
}

A: To me it looks like your image is just fine. If you set the resolutions to .16 and 1.33 degrees, you get an image that is equal to the number of lasers in a ring: 360 / 0.16 = 2250px  by the number of lasers in a vertical stripe, approximately 40 / 1.33 = 30px.
That is because the view of the velodyne 32 is 360 x 40 degrees as is stated in the data sheet. There is really no way to having that image to look differently, unless, you want your pixel to be non-square.


text:
Q: Composer Uninstaller Freezes I am trying to uninstall Composer in Windows 10 and the GUI hangs with the status bar not moving.  I have let it set for several hours which makes me think it is hanging on to some dependency which does not allow it to move forward.
I installed using Composer-Setup.exe, v4.10.0.0.
Has anyone encountered this?
I've performed a whole lot of web searches.  I found some posts about removing the composer.phar and AppData, but there are registry entries that would have to be taken into account.
I reran the installer then tried uninstalling with no change in behavior.  Wondering if this is a bug with version 4.10.0.0.
Also tried a hail-mary by manually running the C:\Program Files (x86)\ComposerSetup\unins000.exe, to no avail.
Also tried a clean reboot followed by the uninstaller with no change.


text:
Q: Saltar 2 datos al leer un archivo en C++ Tengo un codigo que lee un archivo de texto el cual contiene solo datos enteros, y los une en una lista doble, pero tengo que saltarme los 2 primeros datos, es decir, si tengo los siguientes datos en el archivo |1234|, solo deberia leer desde el 3, lo cual no he podido lograr.

Datos Txt
Lista

1 2 3 4 5 6
3 4 5 6

9 10 3 7 8 0
3 7 8 0

void leermostrar(){ //Leer mostrar lista

ifstream archivo;
archivo.open("entrada.txt",ios::in);
if(archivo.fail()){
    cout << "No se pudo abrir el archivo" << endl;
    exit(1);
}
while(!archivo.eof()){
    p=(nodo *) malloc (sizeof(struct nodo));
    archivo>>p->n;
    if(cab==NULL){
        p->ant=p->sig=NULL;
        cab=ult=p;
     }
    else{
        p->sig=cab;
        p->ant=NULL;
        cab->ant=p;
        cab=p;
    }
}
}

A: Para recorrer un archivo desde cierta posición en C++ , encontre la funcion archivo.seekg(3); , de esta forma comenzaria a leer el archivo desde el tercer valor, esta linea se pone antes del while, ;)


text:
Q: Не работает часть скрипта JavaScript Подключаю к проекту следующие файлы:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery-1.4.min.js" ></script>

Есть ли какой-то способ, один из них работать только для одного вставленного скрипта? Если оставлять первый, то не работают клики по создающимся вкладкам:

  $('#tabs a.tab').live('click', function() {
                // Get the tab name
                var bannername = $(this).attr("id") + "_banner";

                // hide all other tabs
                $("#banner > div").hide();
                $("#tabs li").removeClass("current");

                // show current tab
                $("#" + bannername).show();
                $(this).parent().addClass("current");
            });

Если оставлять второй, то вкладки работают, но пропадает другая часть функций.

A: В версии 3.3.1 метод live уже удалён и не будет работать. Вместо live нужно использовать on
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 $('#tabs a.tab').on('click', function() {
            // Get the tab name
            var bannername = $(this).attr("id") + "_banner";

            // hide all other tabs
            $("#banner > div").hide();
            $("#tabs li").removeClass("current");

            // show current tab
            $("#" + bannername).show();
            $(this).parent().addClass("current");
        });


text:
Q: Counting in assembly I have to write in a file('text.txt') all the numbers that are in 's',but from the end to the first number (87654321).
My question is: mov si,len = 8 , dec si =7 and why mov dl,byte ptr s+si-1 is correct? s+si-1 is 6 (0+7-1) and this means the number 5 from 's'(in little-endien).How does it takes the number 8 from 's'?
assume cs:code, ds:data
data segment
    fileName db 'text.txt',0
    s dw '12','34','56','78'

    len equ $-s
    s2 db len dup(?)

    fileHandle dw ?
    openErrorMsg db 'File can not be opened','$'
    writeErrorMsg db 'An error occured when writing','$'
data ends
code segment
start:
    mov ax,data
    mov ds,ax
    ;open the file
    openFile:
        mov ah,3dh
        mov al,1
        mov dx,offset fileName
        int 21h
        jc openError
        mov fileHandle,ax

    mov cx,len
    mov si,len
    dec si
    mov di,0
    jcxz final
    ;make the new array
    formare:
        mov dl,byte ptr s+si-1       ;HERE
        mov s2[di],dl
        inc di
        mov dl,byte ptr s+si
        mov s2[di],dl
        inc di
        sub si,2
        dec cx
        loop formare

    ;write into the file
    writeToFile:
        mov al,0h
        mov ah,40h
        mov bx,fileHandle
        mov cx,len
        mov dx,offset s2
        int 21h
        jc writeError
    jmp final

    openError:
        mov ah,09h
        mov dx,offset openErrorMsg
        int 21h

    writeError:
        mov ah,09h
        mov dx,offset writeErrorMsg
        int 21h
    final:
        mov ax, 4c00h
        int 21h
code ends
end start

A: s dw '12','34','56','78'

(EDIT: wait a second... NASM will compile these 100% sure in the "reversed" order, like db '1', '2', so strings definitions will make sense. What assembler do you use, if it does compile it literally like numeric value? MASM? And it will compile it as string only when " are used? This smell... please, check the memory content in debugger, to avoid some nasty surprise... in the answer below I operate with assumption, that dw '12' == dw 0x3132, but it seems unlikely to me)

compiles into bytes 32 31 34 33 36 35 38 37, with addresses in table:
 addr | hexa byte
------+-----------
 s+0  | 32
 s+1  | 31
 s+2  | 34
 s+3  | 33
 s+4  | 36
 s+5  | 35
 s+6  | 38
 s+7  | 37

So "s+6" does indeed point to '8'.
Maybe checking the memory content in debugger can help you, if you are not 100% sure how the data were encoded into machine code.
(I didn't check rest of your code, only the data definition, which is IMO answering your question fully?)


text:
Q: Reading in file - input missing I was trying to help this user with an answer, but reading in the file isn't working as I expected.
If I create a file with just the OPs first two lines:

Learning Java - William Lane -12.00 - Wiley - 0811234561
- William Stalling - 25.00 - Prentice Hall - 1304086641

The output is as expected:
Learning Java - William Lane -12.00 - Wiley - 0811234561
- William Stalling - 25.00 - Prentice Hall - 1304086641

But when I add the third line:

Learning Java - William Lane -12.00 - Wiley - 0811234561
- William Stalling - 25.00 - Prentice Hall - 1304086641
OOP programming - Graham Winter - 32.50 – O'Reilly - 0471974555

The output is blank.
My code is straight forward, just to test it. I copied and pasted the file contents directly from the linked question above. Is there a special character on that line, and if so, how to find it? And why would it not print the other lines?
Scanner sc = new Scanner(new File("myfile"));
        while (sc.hasNextLine()) {
            String nameLine = sc.nextLine();
            System.out.println(nameLine);
        }

I ran it through a debugger and sc.hasNextLine returns false and the program ends.
Edit:
I'm using Notepad basically to test this, and noticed (on the browser) that the dash between 32.50 and O'Reilly is slightly elongated. So I removed this dash and saved and the program works as expected. When I put it back in and save and re-run the program, it doesn't display anything. I can produce this every time.
I then tested in Notepad++ and all worked smoothly. Happy days.
So I did a comparison between the two files with WinMerge; it basically says the only difference is that dash, and on Notepad++, it's – but on Notepad, it's –.
Anyone any ideas?

A: THis might probably because of difference in file encoding/character set. Try reading the file as UTF-8 mode and check.

A: You may try these changes to see if it works for you. In your post i copied your 3 lines put it to notepad and saved and then opened in notepad++. It never gave issue.


text:
Q: Solving cauchy riemann equations, finding all analytic functions I need someone to check my work! I tried doing this as properly as possible, but I have no way to check whether this is correct.
Find $\textit{all}$ analytic functions $f = p(x,y) +iq(x,y) $ such that $p+q = xy$
(I'm using p's and q's since u's and v's look too similar. It gets messy quickly).
We have $$p_x + q_x = y \qquad p_y + q_y = x $$
$f$ is to be analytic so by Cauchy-Reimann we have $p_x = q_y$ and $p_y = -q_x$, thus we have:
$$y- q_x = x - p_y \qquad y+p_y = x- p_y$$
so
$$ p_y = \frac{x-y}2$$
Thus $$p = \frac{xy}{2} - \frac{y^2}{4} + h(x)$$
Since $q = xy - p$ we have
$$ q = xy - \frac{xy}{2} + \frac{y^2}{4} - h(x) = \frac{xy}{2}+ \frac{y^2}{4} - h(x) $$
Again, since $p_x = q_y$ we have
$$\frac{y}2 + h'(x) = x - \frac{x}2 + \frac{y}2 = \frac{x}2 + \frac{y}2$$
so we have:
$$h(x) = \frac{x^2}4 + C $$
Putting it all together:
$$ f = p+iq = \frac{xy}{2} - \frac{y^2}{4} + \frac{x^2}4 + C + i\left( \frac{xy}{2}+ \frac{y^2}{4} - \frac{x^2}4 - C \right)$$
If we would like to rewrite this, we have:
$$f(z) = \frac{z^2}4 + C - i\left( \frac{z^2}4 + C \right) = (1-i)\left( \frac{z^2}4 + C \right)  $$
Now I would like to claim that for $C \in \mathbb{R}$, these are all solutions. Can I truly be sure of this? Did I make some mistake somewhere?
Thanks in advance.

A: It is of course possible that I overlooked a mistake, but since the result is correct, and I didn't see any error, I'm reasonably convinced that your work is correct.
Here, as in many situations, we can solve the task in an easier way if we apply a certain transformation to the problem. It is advisable to try to look for such simplifications. Not only does it save work when one spots them, it is also less likely to make mistakes in simpler situations.
With $f = p + iq$, note that $(1+i)f = (p-q) + i(p+q)$, so $xy$ is the imaginary part of $g = (1+i)f = u + iv$. Now the Cauchy-Riemann equations make it easy to find $u$, since
$$u_x = v_y = x \quad \text{and}\quad u_y = -v_x = -y,$$
so $u(x,y) = \frac{1}{2}(x^2 - y^2) + c$ for some $c\in \mathbb{R}$. Writing $g$ as a function of $z = x+iy$, we find
$$g(z) = \frac{z^2}{2} + c$$
for some (arbitrary) $c\in \mathbb{R}$. Since $(1-i)(1+i) = 2$, we then obtain
$$f(z) = \frac{1-i}{2} g(z) = \frac{1-i}{4} z^2 + \frac{1-i}{2}c,$$
with an arbitrary real $c$. (My $\frac{c}{2}$ corresponds to your $C$.)


text:
Q: Retrieve directory Structure on my Android phone I have this requirement to retrieve the phone's complete directory structure (Similar to what comes up when we connect our Android device to DDMS and then click on File Explorer). Is there any API's in Android or java that will help me retrieve this directory listing ?

A: Try this:
File f = new File("/");
File file[] = f.listFiles();
for (int i=0; i < file.length; i++)
{
    Log.d("Files", "FileName:" + file[i].getName());
}

A: Did you tried simply call something like this?
File f = new File("/");
File[] files = f.listFiles();

But anyway, you can't get access to folders with non-public read permissions without root, such as /data.

A: If "complete" is the key word here, then no. An app only has access to its allocated "data" folder, as well as "external" (SD) shared storage.
(Note that the story is different on rooted devices, such as emulators, but that is generally not an option.)


text:
Q: Put DataView into Panel I created 3 panels: Panel 1, Panel 2 and Panel 3 in Extjs. Please go to the below fiddle link:
https://fiddle.sencha.com/#view/editor&fiddle/1s0l
I also created a DataView with a static store here (fiddle link): https://fiddle.sencha.com/#view/editor&fiddle/1s0t
Now I wanted to show the above DataView in each of the above panels (Panel 1, Panel 2 and Panel 3). But I am not able to do that. I tried it by giving 'id' to panels and calling that 'id' to show DataView in that panel.
Any approach? How to mege these codes to get that DataView in each Panel?
Thanks!

A: Achieved it with calling DataView in panel by 'alias' !! See https://fiddle.sencha.com/#view/editor&fiddle/1s1q


text:
Q: Cant find desired archetype when creating new Maven project I am trying to create a new Maven project in the terminal, using the following command:
mvn archetype:generate -DgroupId=com.my.domain -DartifactId=myproject -DarchetypeArtifactId=wildfly-javaee7-webapp-archetype -DinteractiveMode=false

So I am trying to use the Wildfly archetype wildfly-javaee7-webapp-archetype.
I am getting the following error...
[INFO] Generating project in Batch mode
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/wildfly-javaee7-webapp-archetype/1.0/wildfly-javaee7-webapp-archetype-1.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17.860 s
[INFO] Finished at: 2016-03-31T14:35:27+02:00
[INFO] Final Memory: 16M/188M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2.4:generate (default-cli) on project standalone-pom: The desired archetype does not exist (org.apache.maven.archetypes:wildfly-javaee7-webapp-archetype:1.0) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

... which means, that Maven is trying to download the archetype at https://repo.maven.apache.org which is not correct, because the archetype is provided by http://mvnrepository.com/artifact/org.wildfly.archetype.
How can I change the source or how can I add additional sources? Or am I missing something different?

A: You need to define the archetypeGroupId, otherwise, it will default to groupId of Maven default archetypes. Also, you need to define the archetypeVersion.
In this case, you need to have archetypeGroupId=org.wildfly.archetype and archetypeVersion=8.2.0.Final (for example).
Thus, you should have:
mvn archetype:generate -DgroupId=com.my.domain -DartifactId=myproject -DarchetypeGroupId=org.wildfly.archetype -DarchetypeArtifactId=wildfly-javaee7-webapp-archetype -DarchetypeVersion=8.2.0.Final -DinteractiveMode=false

As a side-note, repo.maven.apache.org and mvnrepository.com both are Maven Central and contain the same artifacts.

A: If anybody else is having problems following the accepted answer try to decrement the version to -DarchetypeVersion=8.1.0.Final


text:
Q: Focusing an input field in a React component – getting type error trying to create a ref I have a React component that contains a text <input> element. When the component is mounted, I want the text cursor to be set in the input field, i.e. I want the text input element to have the focus.
In a "traditional" JavaScript React component, I would get the input field's DOM element through a ref and then call its focus method.
I've read this documentation that explains how to use refs in Reason-React: https://github.com/reasonml/reason-react/blob/master/docs/react-ref.md
Alas, the code sample contained on this page is for refs of custom component, it only mentions that it also works on React DOM elements.
So I've tried to convert the example code to a React DOM element, here is what I've tried so far:
type state = {
  text: string,
  inputElement: ref(option(Dom.element))
};

let valueFromEvent = (evt) : string => (
  evt
  |> ReactEventRe.Form.target
  |> ReactDOMRe.domElementToObj
)##value;

let component = ReasonReact.reducerComponent("EditTodoField");

let setInputElement = (theRef, {ReasonReact.state}) =>
  state.inputElement := Js.Nullable.to_opt(theRef);

let make = (~initialText, ~onSubmit, _) => {
  ...component,
  initialState: () => {text: initialText, inputElement: ref(None)},
  reducer: (newText, state) => ReasonReact.Update({...state, text: newText}),
  render: ({state: {text}, reduce, handle}) =>
    <input
      value=text
      _type="text"
      ref=(handle(setInputElement))
      placeholder="Todo description"
      onChange=(reduce((evt) => valueFromEvent(evt)))
      onKeyDown=(
        (evt) =>
          if (ReactEventRe.Keyboard.key(evt) == "Enter") {
            onSubmit(text);
            (reduce(() => ""))()
          } else if (ReactEventRe.Keyboard.key(evt) == "Escape") {
            onSubmit(initialText);
            (reduce(() => ""))()
          }
      )
    />
};

The error message I get is this:
We've found a bug for you!
/Users/pahund/git/todo-list-reason-react/src/EditTodoField.re 21:11-35

19 ┆ value=text
20 ┆ _type="text"
21 ┆ ref=(handle(setInputElement))
22 ┆ placeholder="Todo description"
23 ┆ onChange=(reduce((evt) => valueFromEvent(evt)))

This has type:
  ReasonReact.Callback.t(Js.Nullable.t(Dom.element)) (defined as
    (Js.Nullable.t(Dom.element)) => unit)
But somewhere wanted:
  (Js.null(Dom.element)) => unit

The incompatible parts:
  Js.Nullable.t(Dom.element) (defined as Js.nullable(Dom.element))
  vs
  Js.null(Dom.element)

I know that the problem probably lies within how I define the type of the state at the beginning of the code, it's different for DOM elements than it is for custom components.
What would be the correct type definition here to fix the bug?
The full project can be found here on GitHub: https://github.com/pahund/todo-list-reason-react/tree/ref-problem

A: I think your reason-react dependency is out of date. refs were changed from Js.null(Dom.element) to Js.nullable(Dom.element) in 0.3.0. See https://github.com/reasonml/reason-react/blob/master/HISTORY.md#030
If for some reason you can't or refuse to upgrade, you can just use Js.Null.to_opt instead though :)
(Also, if you do upgrade, you can use Js.toOption as a nice shortcut in place of Js.Nullable.to_opt)


text:
Q: increase eclipse IDE font size I am using Eclipse
Spring Tool Suite

Version: 3.9.4.RELEASE
Build Id: 201804120921
Platform: Eclipse Oxygen.3a (4.7.3a)

I would like to increase the font size of the IDE, not just the font of the editor. Is there any way I can do that? I haven't been able to find a solution for this yet.

A: you can try the combination of Ctrl+Shift+'+'. That will enlarge the fonts of the text areas. Ctrl+Shift+'-' will reduce the fonts size, respectively.

A: You can define most of the font sizes in Eclipse/STS via the preferences. In addition to that some font sizes are controlled by the operating system (for example the font that is used for tree views on macOS). Changing those font sizes typically require some OS-specific settings, e.g.: https://apple.stackexchange.com/questions/24621/how-to-increase-font-size-of-eclipse-globally

A: From the URL @MartinLippert provided I found this solutions https://apple.stackexchange.com/a/309209/293897 that changed the fonts in the entire UI except for menus.


text:
Q: Specific Histogram R How to do this kind of histogram in R?

I tried
plot(df$Value, type = 'l')
polygon(df$Value,  col='red')

But the result is not needful

A: Just to offer another possible approach, you can build this plot fairly easily using base R graphics. I usually prefer to build plots manually using base R graphics because it allows precise control over all aspects of the plot. Furthermore, I think that when you spend time contemplating exactly how these kinds of plots need to be built up from primitive graphics elements, it completely demystifies them, by which I mean you develop the understanding that they really are quite simple in terms of conceptual and graphical structure. In this particular case, we can create the primary graphical element (referring to the histogram bars themselves) using a single vectorized call to segments().
## generate data
set.seed(5468L);
N <- 7700L;
df <- data.frame(Value=round(cumsum(c(0.07,runif(N-1L,-0.001,0.001))),5L));

## precompute plot parameters
xlim <- c(1L,N);
ylim <- c(-0.08,0.1);
xticks <- seq(xlim[1L],xlim[2L],276L);
yticks <- seq(ylim[1L],ylim[2L],0.02);

## plot
plot(NA,xlim=xlim,ylim=ylim,xaxs='i',yaxs='i',axes=F,ann=F); ## set range, nothing else
abline(h=yticks,col='lightgrey'); ## horizontal grid lines
segments(seq_len(N),0,y1=df$Value,lwd=0.3,col='#5599CC'); ## histogram bars
text(xticks,-0.005,xticks,adj=c(1,0.5),col='#666666',srt=90,xpd=T); ## custom x-axis in plot
mtext(yticks,2L,0.5,at=yticks,adj=1,las=1L,col='#666666'); ## custom y-axis on margin

A: Two solutions with ggplot2
a <- arima.sim(list(ar=.9), n = 200)#simulated data
df <- data.frame(x = 1:200, a = as.vector(a))

require(ggplot2)
ggplot(df, aes(x = x, y = a)) + geom_area()
ggplot(df, aes(x = x, y = a)) + geom_bar(stat = "identity", width = 1, position  = "dodge")


text:
Q: queryset vs filter_backends in django rest framework I am new to DRF. I went through the example of filtering queryset at http://www.django-rest-framework.org/api-guide/filtering/#filtering-and-object-lookups
This link contains description about queryset filtering, as well as DjangoFilterBackend. As far as I am able to understand, they are serving the same purpose. But it's not clear when to use any one of them. In some of the cases, both queryset and filter_backends are used :-
class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('username', 'email')

Can anyone let me know, what's the difference between these two ?which one of these two have to be used, in which situations, we must prefer one over another ?
Thanks in advance

A: DjangoFilterBackend provides ready to use implementation for filtering. Think of it same as api_view vs generic ListApiView.
Filtering backend allow you to achieve various filtering (search, ordering etc.) with writing just a line of code (that is enabling the filter backend). You could achieve the same result by not using any filter backend and instead filtering yourself using the query parameter.
Later could look something like this:
for q_key in request.query_params.keys():
        if q_key == 'from_ts':
            from_timestamp = int(request.query_params[q_key])
        elif q_key == 'to_ts':
            to_timestamp = int(request.query_params[q_key])
        elif q_key == 'location':
            location_id = (request.query_params[q_key])
        elif q_key == 'from_rating':
            rating_low = int(request.query_params[q_key])
        elif q_key == 'to_rating':
            rating_high = int(request.query_params[q_key])

And filter using these parameters:
snippets = ParResponse.objects.filter(
        device__location__id=location_id,
        owner_user=request.user,
        timestamp__gte=end_date,
        timestamp__lte=from_date,
        overall_rating__lte=rating_high,
        overall_rating__gte=rating_low,
        ).order_by('-timestamp')


text:
Q: Using automatic as parameters #include <stdio.h>

void foo(auto int i); // line 3

int main()
{
    foo(10);
}

void foo(auto int i) // line 13
{
    printf("%d\n", i );
}

What is wrong in this code?
This program is not compiling.
Errors I am seeing are as follows:
main.c:3:27: error: storage class specified for parameter 'i'
     void foo(auto int i);

main.c:13:27: error: storage class specified for parameter 'i'
     void foo(auto int i)

A: auto is a storage class specifier. This is used for local variables(automatic local variables) You can't put it in the declaration of function parameter.
On compiling you should get the error:
[Error] storage class specified for parameter 'i'

In C, You are not allowed to put a storage class specifier in the parameter declaration (except register)

A: The only storage class specifier that is valid in a parameter declaration is register, we can see this from the draft C99 standard section  6.7.5.3 Function declarators (including prototypes) paragraph 2 which says:

The only storage-class specifier that shall occur in a parameter declaration is register.

this is section 6.7.6.3 in C11.
the storage class specifiers from section 6.7.1 Storage-class specifiers are as follows:
typedef
extern
static
auto
register


text:
Q: Awk to print each file I have about 50 files in  a directory
Have
File1: 1|2|3

File2: 3|4|5

File3: A|B|C

WANT
File1: A|1|2|3

File2: A|3|4|5

File3: A|A|B|C

I'll appreciate if anyone can solve it with awk command. I'm open to other solutions in linux. Also, I want to run it once an perform edits on all files in a directory.
The solution (see below) I have will require me to run it on each file one at a time and I don't think that's efficient
awk '{print "A|"$0}' File1

A: Try the below sed command,
sed -i 's/^/A|/' file1 file2 file3

To make it work on all the files in the current directory,
sed -i 's/^/A|/' *

A: With GNU awk for -i inplace:
gawk -i inplace '{print "A|"$0}' file1 file2 file3


text:
Q: UL style attribute is changed to display:block from display:none but this happens in fraction of second unable to take list of li elements from ul Dropdown - On clicking on div,Ul style attribute is changed to display:block from display:none but this happens in fraction of second unable to take list of li elements from ul

    Active Clinic Patients  ▼

            My Active Patients

            Active Clinic Patients

            Inactive Patients

Initial :
On page load, i am having dropdown of above code where - UL tag is having attribute style="display: none; , so all li elements are hidden . Only span value i.e. default selected value is displayed.
In this case, for dropdown on page load - Active Clinic Patients is displayed.
On Click of dropdown :
Once i click on dropdown, UL attribute is changed to style="display: block;"
and li elements are visible.
Problem Faced :
On clicking on span , dropdown values are displayed for fraction of second - so unable to handle Ul style attribute changes and selecting value from li.
I am struggling for this, it would be great if anyone can provide some solution.
Thanks in advance.
Tried Code Snippet :
private IWebElement parentFilter => driver.FindElement(By.XPath("//div[@id='main_filter'][1]/span"));

public void SelectFilter(string filterOption)
        {
            IWebElement elementToShow = driver.FindElement(By.XPath("//ul[@class='dropSelect']"));
            ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style='display: block;'", elementToShow);
            IWebElement option = elementToShow.FindElement(By.XPath("//li/span[contains(text(),'" + filterOption + "')]"));
            Actions action = new Actions(driver);
            action.ClickAndHold(parentFilter).MoveToElement(option).Click().Build().Perform();
    }

A: It looks like your code is attempting to directly modify the style using ExecuteScript.  Instead, the code should emulate what a user does by executing a Click() method on elementToShow.  This should open the list, allowing you to find your target option.


text:
Q: Why am I getting a "PHP Fatal error: Call to a member function bind_param() on a non-object" while using transactions and prepared statements? Like the title says, I am attempting to use both PHP/MySQLi transactions and prepared statements, but I keep getting the "PHP Fatal error:  Call to a member function bind_param() on a non-object" error, and I cannot figure out why.
<?php
    $dbConnection = new mysqli($hostname,$username,$password,$database);

    $query01 = "delete from model where make_id = ?";
    $query02 = "delete from make where id = ?";

    if($stmt01 = $dbConnection->prepare($query01) && $stmt02 = $dbConnection->prepare($query02)){
        if($stmt01->bind_param('i',$id) && $stmt02->bind_param('i',$id)){
            if($stmt01->execute()){
                if($stmt02->execute()){
                    $dbConnection->commit();
                    $dbConnection->commit();
                }
                else{
                    $dbConnection->rollback();
                    $dbConnection->rollback();
                }
            }
            else{
                $dbConnection->rollback();
            }
        }
        else{
            // do something ...
        }
    }
    else{
        // do something ...
    }
?>

What I was doing when I got the error, was testing the rollback should an error occur. I replaced the prepare "if" statement with "false", and everything worked great. I replaced the bind "if" statement with "false", and everything worked out great. However, when I replaced the $stmt01->execute() "if" statement with a "false", this is where I got the error. The weird thing is that I got the error on the bind "if" statement line (the line above where I just tested with "false") and not the line itself.
Thank you for your help.


text:
Q: How can i get Bootstrap datatable to work with javascript automatic refresh? I am using using a script to call a html table that refreshes every 5 seconds.
The following successfully refreshes my HTML table every 5 seconds and loads the table from table.html on the index.html page:
table.html

TEST

index.html

I am trying to implement the following, with a bootstrap datatable, my bootstrap datatable works when the table is included in the index.html page, however when i add the refresh script and place the table inside table.html the table fails to load and produces no console errors:
table.html:

                                                    Name
                                                    Position
                                                    Office
                                                    Age
                                                    Start date
                                                    Actions

                                                    Tiger Nixon
                                                    System Architect
                                                    Edinburgh
                                                    61
                                                    2011/04/25

index.html:
(Large HTML output removed)

When i remove the refresh script, and insert the table between:

It works, so i can't figure out why it will not work.
How can i fix this?


text:
Q: Creating links with words in a string I am storing tags in my database for a specific item using commas.
For example the tags for a person might be.
$tags = "tall, fun, cool";

I am trying to create each word into a link and remove the comma.
So far I've got,
$tags = str_replace(",", "", $tags);

I would like the links to be similar to this
tall fun, etc...

I'm stuck on the creating a link part though, looking for some help please.

A: foreach (array_map('trim', explode(',', $tags)) as $tag) {
  echo "$tag";
}

*

*Split the string at , into an array (explode())

*Remove all leading and trailing whitespaces (trim()) from every array element (array_map())

*Just iterate and output.


text:
Q: How to execute a function from a Python script (with parameters) in PHP? I've recently been working on a web crawler with PHP and as a newish PHP coder, I'm not the most advanced. I also know a decent bit of Python and there are a few things I am able to do in Python yet not in PHP.
Is there any way for me to run a Python function with parameters inside a PHP script? Please be specific in your answers as I'm not amazing at PHP.

A: Run the Python script using php's shell_exec function
Think of shell_exec as basically running commands in your terminal. So if you normally run your python script from the shell like this:
/python-scripts/myscript.py "here is an argument"

You would pass the same command into shell_exec, like this:
$output = shell_exec("python-scripts/myscript.py 'here is an argument'");

Note: shell_exec will return the output of the command you run, so save it to a variable if you want to use the output from the python program in your PHP script.
Edits: fixed syntax issues, provided a more specific example