Q:

Phantom zipalign

I'm trying to run zipalign from freshly installed android sdk on Ubuntu. Although you can clearly see zipalign in proper directory, running it yields "no such file or directory". I can open it in hex editor. I can list its contents with cat, but still... no such file?!
qus@Ubuntu:~/Dev/android-sdk-linux/build-tools/22.0.1$ ls -al
total 65400
drwxrwxr-x 4 qus qus     4096 kwi  8 19:42 .
drwxrwxr-x 3 qus qus     4096 kwi  8 19:42 ..
-rwxrwxr-x 1 qus qus  1264873 kwi  8 19:42 aapt
-rwxrwxr-x 1 qus qus   268935 kwi  8 19:42 aidl
-rwxrwxr-x 1 qus qus  3570836 kwi  8 19:42 arm-linux-androideabi-ld
-rwxrwxr-x 1 qus qus    33826 kwi  8 19:42 bcc_compat
-rwxrwxr-x 1 qus qus   473812 kwi  8 19:42 dexdump
-rwxrwxr-x 1 qus qus     2577 kwi  8 19:42 dx
-rwxrwxr-x 1 qus qus  3570836 kwi  8 19:42 i686-linux-android-ld
-rw-rw-r-- 1 qus qus  8632399 kwi  8 19:42 jack.jar
-rw-rw-r-- 1 qus qus  2948562 kwi  8 19:42 jill.jar
drwxrwxr-x 2 qus qus     4096 kwi  8 19:42 lib
-rwxrwxr-x 1 qus qus   303373 kwi  8 19:42 libbcc.so
-rwxrwxr-x 1 qus qus   802678 kwi  8 19:42 libbcinfo.so
-rwxrwxr-x 1 qus qus 15699200 kwi  8 19:42 libclang.so
-rwxrwxr-x 1 qus qus  1311060 kwi  8 19:42 libc++.so
-rwxrwxr-x 1 qus qus 22195804 kwi  8 19:42 libLLVM.so
-rwxrwxr-x 1 qus qus  1838328 kwi  8 19:42 llvm-rs-cc
-rwxrwxr-x 1 qus qus     4137 kwi  8 19:42 mainDexClasses
-rw-rw-r-- 1 qus qus      885 kwi  8 19:42 mainDexClasses.rules
-rwxrwxr-x 1 qus qus  1919720 kwi  8 19:42 mipsel-linux-android-ld
-rw-rw-r-- 1 qus qus   727899 kwi  8 19:42 NOTICE.txt
drwxrwxr-x 5 qus qus     4096 kwi  8 19:42 renderscript
-rw-rw-r-- 1 qus qus       17 kwi  8 19:42 runtime.properties
-rw-rw-r-- 1 qus qus    16509 kwi  8 19:42 source.properties
-rwxrwxr-x 1 qus qus  1228769 kwi  8 19:42 split-select
-rwxrwxr-x 1 qus qus    98040 kwi  8 19:42 zipalign
qus@Ubuntu:~/Dev/android-sdk-linux/build-tools/22.0.1$ ./zipalign
bash: ./zipalign: No such file or directory

A:

OK, once again for anyone who happens to stumble with same problem:
sudo apt-get install libstdc++6:i386 libgcc1:i386 zlib1g:i386 libncurses5:i386
And it works! And to think some time ago Linux users were laughing at non-descriptive Windows error messages...


Q:

Counting number of jobs for each month

I'm running this query to get the delivery date for jobs. Each job has a leader and I'm running this query to display all jobs for each leader and the delivery date for each job.
SELECT job_num,
       firstname,
       lastname,
       extra_date
FROM view_job_info
INNER JOIN view_leader_users ON view_job_info.mm_id = view_leader_users.id
  WHERE (DATEDIFF(NOW(), latest_workorder_date) < 200  //This is a check for active jobs
     OR (DATEDIFF(NOW(), posted_date) < 200))          //Same as above
     AND job_num > 2000 AND firstname LIKE 'mike'
     ORDER BY mm_id, deliverydate DESC

Sample output:

So how can I get the number of jobs for each month for Mike.
So if you look at the table, there are 4 jobs for February and I'm trying to display this on the page as
Jobs for user Mike Easter:

January  : 4
February : 4
March    : 1

I tried using count() on extra_date but that just gives me the total number of rows for Mike.

A:

You need to use a group by with your count. Something like:
select name, count(*) from view_job_info
  where name = 'mike'
  group by MONTH(extra_date)


Q:

Find the occurrence of entries for every one hour

I have a excel sheet with a large data. Approximately around 1000 rows and 25 columns. I just need the entries to be calculated per hour.

I would really appreciate your help. This would make my work a lot easier.

A:

You can do this with COUNTIFS():
=COUNTIFS($A:$A,">="&"6/30/2016 9:56",$B:$B,"<="&"6/30/2016 10:56")


Q:

Why does the STL/Boost C++ coding style differ so much from everyone elses?

I'm a fairly rookie C++ programmer, but in my limited experience with the language, most standard C++ style guidelines (e.g. Google C++ Style Guidelines) go against what is implemented in the stl and boost libraries.
For example, class names in the C++ standard library and Boost are always lower case, with underscores separating words (e.g. std::vector, boost::unordered_map, std::map::const_iterator), whereas most style guides I've seen for C++ tend towards a CamelCase style (e.g. TcpConnection or Int32).
The same applies to methods too. The standard library and Boost use the same style for methods and functions as they do for classes (e.g. std::map<>::get_equal("foo")), whereas most style guides advocate pascalCase or CamelCase.
If we contrast this with a language like Ruby, where most users will adhere to the conventions used in the core libraries, it seems odd that there'd be such a difference between the standard C++ libraries and everyone else's code.
Does anyone know why this is?
EDIT: Just to clarify, I'm talking simply about the superficial textual style (casing, use of underscores, etc) rather than actual implementation style.

A:

underscores and lowercase was the style perferred by Bjarne Stroustrup in "The C++ Programming Language". If I recall correctly he had made a statement along the lines that underscores in names were to be preferred because it was more readable to an international community where english is not the primary language. I have no idea if his opinion is true or not, but I'm guessing that's the origin.
Here's a link to his FAQ where he discusses this very topic:
http://www.stroustrup.com/bs_faq2.html#Hungarian
Snippet explaining what you were interested in in particular:

I prefer to use underscores to separate words in an identifier (e.g, element_count) rather than alternatives, such as elementCount and ElementCount. Never use names with all capital letter (e.g., BEGIN_TRANSACTION) because that's conventionally reserved for macros. Even if you don't use macros, someone might have littered your header files with them. Use an initial capital letter for types (e.g., Square and Graph). The C++ language and standard library don't use capital letters, so it's int rather than Int and string rather than String. That way, you can recognize the standard types.

A:

There is a good reason beside Bjarne Stroustrup one. When using functors you want them to look like a functions.
But with CamelCase style guides you distinguish Classes from Methods and Functions by using Capitals on the first char of Classes name and LowerCase on the first char of a method.
This is not consistent with c++ algorithm style programming. As there is no reason to distinguish a functor from a function, it's preferable to use c++ and stl coding styles when you want to use functors (and usually you want).

A:

The only rules that truly are needed are those designed to prevent known problems:

Use ALL_CAPS (plus underscores and digits) for preprocessor names, and only for preprocessor names. It can be tough chasing down problems caused by collisions between a (supposedly) non-preprocessor identifier and a preprocessor name, tougher yet to fix them.
Never start an identifier with an underscore, and don't have a double underscore anywhere inside an identifier. Those are reserved for the implementation.

Beyond this, be consistent, and don't be too picky. Coding standards should be mindful of rule #0, which is "Don't sweat the small stuff." Far too many coding standards sweat the small stuff.
As far as Google's C++ standard goes, it's not the best. It's more of a C plus or minus standard. It prohibits pass by non-constant reference, for example.


Q:

Stanford CoreNLP in R: Spanish language not working

I'm starting to use Stanford CoreNLP package in R in order to do some text analysis in Spanish. So, I try the following:
R

R version 3.2.2 (2015-08-14) -- "Fire Safety"
Copyright (C) 2015 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> install.packages("coreNLP")
Installing package into ‘/home/ach/R/x86_64-pc-linux-gnu-library/3.2’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---
trying URL 'https://cran.rediris.es/src/contrib/coreNLP_0.4-1.tar.gz'
Content type 'application/x-gzip' length 17392 bytes (16 KB)
==================================================
downloaded 16 KB

* installing *source* package ‘coreNLP’ ...
** package ‘coreNLP’ successfully unpacked and MD5 sums checked
** R
** data
*** moving datasets to lazyload DB
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
* DONE (coreNLP)

The downloaded source packages are in
    ‘/tmp/RtmpO3q77z/downloaded_packages’
> library(coreNLP)
> downloadCoreNLP(type="base")
trying URL 'http://nlp.stanford.edu/software//stanford-corenlp-full-2015-04-20.zip'
Content type 'application/zip' length 360824440 bytes (344.1 MB)
==================================================
downloaded 344.1 MB

[1] 0
>
> downloadCoreNLP(type="spanish")
trying URL 'http://nlp.stanford.edu/software//stanford-spanish-corenlp-2015-01-08-models.jar'
Content type 'application/x-java-archive' length 25007256 bytes (23.8 MB)
==================================================
downloaded 23.8 MB

> initCoreNLP()
Searching for resource: config.properties
Adding annotator tokenize
TokenizerAnnotator: No tokenizer type provided. Defaulting to PTBTokenizer.
Adding annotator ssplit
Adding annotator pos
Reading POS tagger model from edu/stanford/nlp/models/pos-tagger/english-left3words/english-left3words-distsim.tagger ... done [0.7 sec].
Adding annotator lemma
Adding annotator ner
Loading classifier from edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz ... done [3.5 sec].
Loading classifier from edu/stanford/nlp/models/ner/english.muc.7class.distsim.crf.ser.gz ... done [1.2 sec].
Loading classifier from edu/stanford/nlp/models/ner/english.conll.4class.distsim.crf.ser.gz ... done [2.3 sec].
Initializing JollyDayHoliday for SUTime from classpath: edu/stanford/nlp/models/sutime/jollyday/Holidays_sutime.xml as sutime.binder.1.
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/defs.sutime.txt
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/english.sutime.txt
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/english.holidays.sutime.txt
Adding annotator parse
Loading parser from serialized file edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz ... done [0.4 sec].
Adding annotator dcoref
Adding annotator sentiment
> > sInes <- "Hola padre. Acabo de llegar a casa. Tengo ganas de cenar"
> annotation <- annotateString(sInes)
> token <- getToken(annotation)
> token[token$sentence==2,c(1:4,7)]
  sentence id  token  lemma POS
4        2  1  Acabo  Acabo NNP
5        2  2     de     de NNP
6        2  3 llegar llegar NNP
7        2  4      a      a  DT
8        2  5   casa   casa  FW
9        2  6      .      .   .

Everything seem to work fine (no errors can be seen, as far as I can see), but it does not work. For example, "casa" is tagged as Foreign Word (FW) which is not correct.
So, does anyone have any idea on this?
Thanks a lot
Agustin

A:

You need to not only download Spanish, but set the tokenizer to Spanish as well:
props.setProperty("tokenize.language", "es");

A:

The author of the package recently made updates that make it a breeze to change language settings.
# update to newest version of the package
devtools::install_github("statsmaths/coreNLP")

# download base library (mandatory):
coreNLP::downloadCoreNLP()

# download desired language library:
coreNLP::downloadCoreNLP(type="spanish")

# attach package
library(coreNLP)

# run initCoreNLP specifying your language of choice
initCoreNLP(type="spanish")


Q:

C# DateTime is always 01/01/0001 when passed through method parameters

I'm trying to check if a DateTime is greater than another DateTime in a method, but when I try to pass it through the paramaters it says that one of the DateTime is 01/01/0001 even though I didn't pass it through as such.
Method:
int monthsCount2(DateTime date, DateTime birthday, int yOld)
            {
                int count = 0;
                if (birthday.Date >= date.Date)
                {
                    count++;
                    if (!(yOld == 0))
                        count += (yOld - 1);
                }
                else
                    count += yOld;
                return count;
            }

Using the method:
Console.WriteLine("You have lived through {0} christmases.",
monthsCount2(christmas, birthDay, (int)yearsOld));

christmas variable:
DateTime christmas = new DateTime(25 / 12 / 2017);

birthDay variable:
try
                {
                    Console.WriteLine("Please enter your Birthdate. (dd/MM/yyyy)");
                    string input = Console.ReadLine();
                    birthDay = DateTime.Parse(input);
                    if (birthDay > DateTime.Now)
                        throw new FormatException();
                }

yearsOld variable:
TimeSpan secondsTimeSpan = DateTime.Now - birthDay;
                double secondsOld = Math.Round(secondsTimeSpan.TotalSeconds);
                double minutesOld = Math.Round(secondsOld / 60);
                double hoursOld = Math.Round(minutesOld / 60);
                double daysOld = Math.Round(hoursOld / 24);
                double weeksOld = Math.Round(daysOld / 7);
                double monthsOld = Math.Round(weeksOld / 4.34524);
                double yearsOld = Math.Round(monthsOld / 12, 1);

Input - Console:
Console - Imgur
Locals Debug:
Locals - Imgur
All Code:
Code - Github

A:

The correct syntax to initialize a datetime instance is this:
var christmas = new DateTime(2017, 12, 25);

The constructor is documented here.
And the reason why your approach did not work:
You are dividing 25 by 12, then dividing the result of that by 2017. as an integer, this will be zero, as a date this will be DateTime.MinValue which is 01/01/0001.
So why does the compiler not reject your attempted date literal? Because there is a constructor which takes an Int64 that fits the division expression. It has altogether different semantics though, it represents the

number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar


Q:

Create objects based on date and time

I have an Event model, and each event will have different shows.
class Event(models.Model):
    title = models.CharField(max_length=200)

class Show(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    date_time = models.DateTimeField(unique=True)

I have another Ticket model. Each ticket should be unique. Meaning each ticket will be unique and relate to a Show and a Seat.
class Ticket(models.Model):
    show = models.ForeignKey(Show)
    seat = models.ForeignKey(Seat)

    class Meta:
        unique_together = ('show', 'seat')

I need to create shows based on the start date and end date provide by the user. Suppose this is a JSON post:
{
    "event_id": 1,
    "start_date": "2018-02-16",
    "end_date": "2018-02-20",
    "time_list": ["11:00 AM", "8:00 PM"]
}

From the above JSON example, I need to create Show starting like this:
# Start with the start_date as the date, and for each time from the time_list
Show.objects.create(
    event = 1,
    date_time = datetime.strptime('2018-02-16 11:00 AM', "%Y-%m-%d %I:%M %p")
)
Show.objects.create(
    event = 1,
    date_time = datetime.strptime('2018-02-16 8:00 PM', "%Y-%m-%d %I:%M %p")
)
# Next date after the start_date, i.e., 16+1 = 17
Show.objects.create(
    event = 1,
    date_time = datetime.strptime('2018-02-17 8:00 PM', "%Y-%m-%d %I:%M %p")
)
.
.
.
# Create Show objects till the end_date and for each time from the time_list
Show.objects.create(
    event = 1,
    date_time = datetime.strptime('2018-02-20 8:00 PM', "%Y-%m-%d %I:%M %p")
)

Right now this is how I am creating Show objects:
def create_show_by_datetime(self, request):
    event_id = request.data['event_id']
    try:
        event = Event.objects.get(id=event_id)
    except Event.DoesNotExist:
        return Response(
            {'error': 'event with id: %s does not exist.' % event_id},
            status=status.HTTP_400_BAD_REQUEST
        )

    start_date = request.data['start_date']
    end_date = request.data['end_date']
    time_list = request.data['time_list']
    date_format = '%Y-%m-%d'
    time_format = "%I:%M %p"
    try:
        datetime.strptime(start_date, date_format)
        datetime.strptime(end_date, date_format)
        for i in range(len(time_list)):
            time = datetime.strptime(time_list[i], time_format)
    except ValueError as e:
        return Response(
            {'error': 'Time was not in a supported format. %s' % e},
            status=status.HTTP_400_BAD_REQUEST
        )

    delta_days = datetime.strptime(end_date, date_format).date() - datetime.strptime(start_date, date_format).date()
    delta_days = delta_days.days + 1
    dt = None
    try:
        with transaction.atomic():
            for i in range(delta_days):
                day = datetime.strptime(start_date, date_format) + timedelta(days=i)
                for i in range(len(time_list)):
                    hrs = datetime.strptime(time_list[i], time_format).hour
                    mins = datetime.strptime(time_list[i], time_format).minute
                    dt = day + timedelta(hours=hrs, minutes=mins)
                    show = Show.objects.create(
                        event=event,
                        date_time=dt
                    )
            return Response({"data": 'Post succesfull'}, status=status.HTTP_201_CREATED)
    except IntegrityError as e:
        return Response(
            {
                'error': "event with date and time already exsits. %s-%s-%s at %s:%s" % (
                    dt.day, dt.month, dt.year, dt.hour, dt.minute),
                'detail': str(e)
            }, status=status.HTTP_400_BAD_REQUEST

But I am hoping there's much more elegant way than how I am doing. I am using python 3, django 2 and django rest frameowork. How can I create Shows with the event, and date_time based on the event_id, start_date, end_date and the time_list?

A:

My approach is a little bit different. You said in the question tag that you are using django-rest-framework.. So where are the serializers? :)
Lets create two serializers, one for user data validation (Because we don't trust the USER!) and one for multi data insert.
I haven't checked the code! But you can use it was an example...
class ShowEventSerializer(serializers.Serializer):
    event_id = serializers.IntegerField()
    start_date = serializers.DateField(required=True)
    end_date = serializers.DateField(required=True)
    time_list = serializers.ListField(
        child=serializers.TimeField()
    )

    class Meta:
        fields = ('event_id', 'start_date', 'end_date', 'time_list')

class ShowSerializer(serializers.Serializer):
    date_time = serializers.DateTimeField()

    class Meta:
        model = Show
        fields = ('event', 'date_time')

Now, with the serializers, we are going to validate the user data and then to create a json data object:
def create_show_by_datetime(self, request):

    show_event_serializer = ShowEventSerializer(data=request.data)
    if not show_event_serializer.is_valid():
        return Response({'error': show_event_serializer.errors},status=status.HTTP_400_BAD_REQUEST)

    event_id = show_event_serializer.data['event_id']
    try:
        event = Event.objects.get(id=event_id)
    except Event.DoesNotExist:
        return Response({'error': 'event with id: %s does not exist.' % event_id},status=status.HTTP_400_BAD_REQUEST)

    start_date = show_event_serializer.data['start_date']
    end_date = show_event_serializer.data['end_date']
    time_list = show_event_serializer.data['time_list']
    date_format = '%Y-%m-%d'
    time_format = "%I:%M %p"

    try:
        datetime.strptime(start_date, date_format)
        datetime.strptime(end_date, date_format)
        for i in range(len(time_list)):
            time = datetime.strptime(time_list[i], time_format)
    except ValueError as e:
        return Response(
            {'error': 'Time was not in a supported format. %s' % e},
            status=status.HTTP_400_BAD_REQUEST
        )

    delta_days = datetime.strptime(end_date, date_format).date() - datetime.strptime(start_date, date_format).date()
    delta_days = delta_days.days + 1
    dt = None
    show_data = []
    for i in range(delta_days):
        day = datetime.strptime(start_date, date_format) + timedelta(days=i)
        for i in range(len(time_list)):
            hrs = datetime.strptime(time_list[i], time_format).hour
            mins = datetime.strptime(time_list[i], time_format).minute
            dt = day + timedelta(hours=hrs, minutes=mins)
            show_data.append({
                "event": event,
                "date_time": dt
            })

    try:
        with transaction.atomic():
            show_serializer = ShowSerializer(data=show_data, many=True)
            if show_serializer.is_valid():
                show_serializer.save()

            return Response({"data": 'Post succesfull'}, status=status.HTTP_201_CREATED)
    except IntegrityError as e:
        return Response(
            {
                'error': "event with date and time already exsits. %s-%s-%s at %s:%s" % (
                    dt.day, dt.month, dt.year, dt.hour, dt.minute),
                'detail': str(e)
            }, status=status.HTTP_400_BAD_REQUEST

So this code is basically the same as yours, with the difference of the way the objects are saved using the DRF. Look the show_data variable.
This solution is just a different way of looking at the question.
GOOD LUCK!
http://www.django-rest-framework.org/api-guide/serializers/
http://www.django-rest-framework.org/api-guide/fields/

A:

Then your Show model should look like
from django.contrib.postgres.fields import ArrayField

class Show(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    start_date = models.DateField(blank=True, null=True)
    end_date = models.DateField(blank=True, null=True)
    board = ArrayField(
        models.TimeField(blank=True, null=True),
        size=10, # specify max array size
    )

so you'll have model Show with specified DateFields and array of TimeFields.
django docs: Array Field, Time Field, Date Field

A:

There are some tools in the datetime library that can give you a more streamlined approach to generating your times. You can use toordinal to turn a date into an integer and fromordinal to turn an integer back into a date; this makes a nice way to create a range of dates. And you can use combine to merge a date object and a time object into a datetime. I'd create the following function:
from datetime import datetime, date

def get_showtimes(post):
    start = datetime.strptime(post['start_date'], '%Y-%m-%d')
    end = datetime.strptime(post['end_date'], '%Y-%m-%d')
    times = [datetime.strptime(t, '%I:%M %p').time() for t in post['time_list']]
    for ordinal in range(start.toordinal(), end.toordinal() + 1):
        date = date.fromordinal(date)
        for time in times:
            yield datetime.combine(date, time)

then, in your code, replace the second try: except: block and what follows it with:
try:
    showtimes = list(get_showtimes(post))
except ValueError as e:
    return Response(
        {'error': 'Time was not in a supported format. %s' % e},
        status=status.HTTP_400_BAD_REQUEST
    )

try:
    with transaction.atomic():
        for showtime in showtimes:
            show = Show.objects.create(event=event, date_time=showtime)
except IntegrityError as e:
    # etc.


Q:

How to create a latex table in R with significance stars?

I have a latex table generated as following in R:
\documentclass[12pt,econ]{authesis}
\usepackage{natbib}  % natbib citation style
    \usepackage{url}     % added 2015-067-06 bc the example .bib uses url
    \usepackage{graphicx}
    \usepackage{amsmath}
    \usepackage{authblk}
    \usepackage{placeins}
    \usepackage{booktabs}
    \usepackage{ragged2e}
    \usepackage{array, tabularx,multirow, makecell}
    \usepackage{multicol}
    \usepackage{commath}
    \usepackage{dcolumn}
    \setcellgapes{3pt}
    \usepackage{hyperref}
    \usepackage{cleveref}
    \usepackage{subfig}  % to construct sub figures
    \usepackage{anysize}  % for page margins
    \usepackage{adjustbox}
    \usepackage{rotating} %to rotate tables
    \usepackage{pdflscape}

\begin{document}
    \begin{table}[ht]
    \centering
    \begin{tabular}{}
      & myEstVector.cf\_10 & myEstVector.cf\_25 & myEstVector.cf\_50 & myEstVector.cf\_75 & myEstVector.cf\_90 \\
     1 & 14.486 & 18.951 & 23.784 & 34.117** & 44.131** \\
      2 & (1.23) & (1.512) & (2.015) & (2.784) & (3.56) \\
      3 & -1.108 & -1.863 & -2.475 & -3.361* & -3.993* \\
      4 & (-0.846) & (-1.198) & (-1.671) & (-2.041) & (-2.537) \\
      5 & 0.504*** & 0.482*** & 0.425*** & 0.348*** & 0.292** \\
      6 & (4.77) & (5.507) & (4.846) & (4.136) & (3.07) \\
      7 & -0.808** & -0.434 & -0.129 & 0.027 & -0.023 \\
      8 & (-2.792) & (-1.412) & (-0.501) & (0.136) & (-0.119) \\
      9 & 0.001 & -0.001 & -0.002 & -0.003 & -0.003*** \\
      10 & (0.105) & (-0.129) & (-2.645) & (-4.392) & (-4.41) \\
      11 & -0.01 & -0.001 & 0.031 & 0.009 & -0.026 \\
      12 & (-0.237) & (-0.042) & (1.089) & (0.244) & (-0.728) \\
      13 & -0.108 & -0.14** & -0.087 & -0.052 & -0.016 \\
      14 & (-1.965) & (-2.545) & (-1.776) & (-1.394) & (-0.416) \\
      15 & -0.789** & -0.99** & -1.445*** & -1.424*** & -1.948*** \\
      16 & (-2.809) & (-3.079) & (-3.892) & (-4.021) & (-4.893) \\
      \end{tabular}
    \end{table}
\end {document}

When I run it in the TexShop, I get this error
Package array Error: Empty preamble : `l' used.
See the array package documentation for explanation. Type H <return> for immediate help.
...
l.393 \begin{tabular}{}
?

I am using Texshop and compiling this under pdflatex.  Can anyone please give a suggestion to solve the problem?
Note: The R code to create the table above is as follows:
ltxtable=xtable(myNewTable,align=rep("",ncol(myNewTable)+1))
print(ltxtable, floating=TRUE, hline.after=NULL, include.rownames=TRUE, include.colnames=TRUE)

A:

Change
ltxtable=xtable(myNewTable,align=rep("",ncol(myNewTable)+1))

to
ltxtable=xtable(myNewTable,align=rep("l",ncol(myNewTable)+1))


Q:

Please explain this PHP Function Definition

*Please change the title into something that refer into this question since i didn't know what is this should be.
When i read some tutorial i see script like this
function testArray(array $categories) {
var_dump($categories);
}

testArray(array('string'));

The array in function definition make the parameter strict must be array, which i love it.
Then i test this script
function testString(string $string) {
    var_dump($string);
}

testString('test');

Why did i get error like this Catchable fatal error: Argument 1 passed to testString() must be an instance of string, string given ....?
I'm pretty sure the parameter is string.

A:

You are talking about Type Hinting.
PHP type hinting can only be used in objects and arrays.
String is a scalar type which does not supports type hinting
More on type hinting
http://php.net/manual/en/language.oop5.typehinting.php


Q:

excel VBA Overflow error when it shouldn't

Sub TestFunction()
     Dim var As Double
     var = 25 * 24 * 23 * 22 * 21 * 20
End Sub

I am receiving an overflow error for this vba operation. when i run it in a cell with functions i get 127,512,000
what could possibly be an error for this? this should be well below the size limit for this data type right?

A:

VBA annoyingly converts the first term to an Integer because in your case, it is small enough.
Amend this line, that it is converted explicitly to a double:
var = CDbl(25) * 24 * 23 * 22 * 21 * 20


Q:

argmax of homogeneous function

EDITS APPEAR IN BOLD
We want to compute
$$
p^\star = \text{argmin}_{p\in \mathbb{R}^n} \quad 1/2f(p)^2- p\cdot g(p)
$$
where $f: \mathbb{R}^n\mapsto \mathbb{R}$  is a (smooth) norm and
$g: \mathbb{R}^n\mapsto \mathbb{R}^n$ is smooth.
So the objective function can be written in the form
$$
1/2f(p)^2- f(p) \left(\frac{p}{f(p)}\cdot g(p)\right)
$$
We introduce
$$
\pi^\star = \text{argmax}_{\pi | f(\pi)=1} \quad  \pi\cdot g(\pi)
$$
Then
$$
p^\star = \left(\pi^\star \cdot g(\pi^\star)\right) \pi^\star
$$
I don't understand the result, especially why is it natural to introduce $\pi^\star$ ?
We can easily get convinced in dim 1 = n.
Thanks for your enlightenment

A:

With $f(p) = p$ you obtain $\pi^*=1$ and $p^* = g(1)$. So, the claim is that:
$$\text{argmin}_{p} 1/2p^2 - p g(p) = g(1).$$
This is not necessarily true, for example when $g(p) = -(p-1)$:
$$\text{argmin}_{p} 1/2p^2 + p(p-1) = \frac{1}{3} \neq 0 = g(1).$$


Q:

Past tense (past subjunctive) used after "as if" to indicate a non-habitual action in the past

Question:

Can the past tense used after as if indicate an individual (non-habitual), or in other words, isolated action that is unreal, or might be true?

Let me explain the question:
I have seen the past tense used after as if often conveys a habitual action or a condition or a state that is unreal or that might be true.
For example, knowing something is a state,

(1) She laughed at the question as if she knew how to solve it.

And when describing an individual (non-habitual) action in the past which is hypothetical or might be true, I feel like using past perfect is more natural.
For example, solving something is an action happening only at a particular timing, so I use past perfect in the below sentence (could simple past be used in this case?).

(2) She laughed at the question as if she had solved it.

And I feel weird about the sentence below and I don't know why:

(3) She laughed at the question as if she solved it.

A:

In every one of your constructions, the phrase following "as if" is not a hypothetical. It is a comparison being used as an adjective. Most of the time I would say it doesn't even imply that the phrase might be true, instead implying that it is strictly not true, however if the perspective of the narrator is one of limited knowledge (e.g. first person or third-person limited), then it is possible that the writer used that phrase because the narrator does not know whether she knows the answer or not. I would not expect that sentence construction if that were the case, but it is possible.
In my experience "as if" in that sense is typically used to indicate that the thing after is not true, but is a good comparison/descriptor for the situation. As Jason Bassford said in his comment, you can replace "as if" with "like" in those examples and the sentence has the same meaning. I could say "The skater glided across the ice as if carried by an angel," and the sentence in no way implies that the skater was actually carried by an angel. Instead, "as if carried by an angel" is a comparison used as an adjective to describe the gracefulness with which the skater skated. The sentence "The skater glided across the ice like she was carried by an angel" has the same meaning and works just as well.
To put it simply: The construction "as if [phrase]" is used to compare the action before the "as if" to the phrase after. It does not imply the habitualness of the phrase and only sometimes implies truthfulness. If the narrator is 3rd-person omniscient, it is a fact that the phrase after "as if" is untrue and is merely being used for comparison. If the narrator has a limited perspective, the phrase is still being used primarily for comparison, but may be true (however in most cases I suspect it is not). Either way, it is best to think of the construction "as if [phrase]" as an adjective-phrase describing the verb-phrase that preceded it.


Q:

CSS for Aligning TextBox and Label

I'm trying to take my Form layout away from tables and entering the world of div's and css.
I'm having difficulty though in my layout.  I'd like to order the elements where a label is positioned directly above an input.
Here's what it currently looks like:

I'd like the District Label and Textbox to be vertically aligned, but they seem to be forming a stair pattern.
Here's the css:
#content
{
    position: absolute;
    top: 110px;
    left: 350px;
    width: 775px;
    height: 605px;

}

#content label
{
    display:inline;
    margin-right:4px;
    vertical-align:top;
}

#content input
{
    float:left;
    margin:1px 20px 1px 1px;
}

and the HTML:

        Request Id
        <input id="txt_RequestId" type="text" />

        District
        <input id="txt_District" type="text" />

A:

nest the input elements in the labels so the text label and field are grouped.
this usage is specified in the HTML4 spec:
To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control.

        Request Id

        <input id="txt_RequestId" type="text" />

        District

        <input id="txt_District" type="text" />

CSS:
#content
{
    position: absolute;
    top: 110px;
    left: 350px;
    width: 775px;
    height: 605px;
}

#content label
{
    display:inline;
    float:left;
    margin-right:4px;
    vertical-align:top;
}

example
Then apply display:inline and float:left to the s (or use display:inline-block instead if you don't have to worry about older browsers example)


Q:

java.lang.classnotfoundexception org.springframework.web.servlet.dispatcherservlet

I am trying to run a sample Spring MVC application with the following resources
IDE : eclipse(indigo)
Server : Tomcat7
Build Tool : No build tool (Trying to run manually)
and it is giving me the following exception:
**INFO: Marking servlet spring as unavailable
16 May, 2014 12:23:20 AM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /Spring3MVC threw load() exception
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:529)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:511)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:139)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1148)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5210)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5493)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)**

Please help me in resolving this issue.
I am posting my web.xml and spring configuration file below:
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

    <display-name>ShopManagement</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

Spring Configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan
        base-package="shop.mgmt.web" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/message" />
        <property name="cacheSeconds" value="3000" />
    </bean> -->
</beans>

I have all the jars related to Spring MVC in WEB-INF\lib folder and also in build path.
please help me in resolving this.

A:

In Eclipse IDE right click on project choose properties, choose Deployment Assembly make sure source and deploy path right, also any libs that you use out side web/inf must be deploy in WEB-INF/lib. After that try clean project and clean tomcat server and publish web application again.
Check this post hope it can help you eclipse web application and maven dependency issues


Q:

Split Names in column

I'm fairly new to python and working with a DataFrame in pandas & numpy from The Movie Database. One of the columns notes the main cast of each movie separated by the pipe symbol (|). I'm trying to find a way to split each individual cast member and list it in its own row with the movie title. I've attached a snippet below of the results I get.
tmdb_data = pd.read_csv('tmdb-movies.csv')
cast_split = tmdb_data[['original_title', 'cast']]
df = pd.DataFrame(cast_split)
df.head()

Movie Title & Cast
Expected Output:
    original_title                 cast
0  Jursassic World           Chris Patt
1  Jursassic World  Bryce Dallas Howard
2  Jursassic World          Irrfan Khan

A:

Use pop + split + stack + rename + reset_index for new Series and then join to original:

tmdb_data = pd.DataFrame({'movie':['Jursassic World', 'Insurgent'],
                           'cast':['Chris Patt|Bryce Dallas Howard|Irrfan Khan',
                                   'Shailene Woodley|Theo James']},
                         columns=['movie', 'cast'])

print (tmdb_data)
             movie                                        cast
0  Jursassic World  Chris Patt|Bryce Dallas Howard|Irrfan Khan
1        Insurgent                 Shailene Woodley|Theo James

df1 = (tmdb_data.join(tmdb_data.pop('cast').str.split('|', expand=True)
                               .stack()
                               .reset_index(level=1, drop=True)
                               .rename('cast'))
                               .reset_index(drop=True))

print (df1)

             movie                 cast
0  Jursassic World           Chris Patt
1  Jursassic World  Bryce Dallas Howard
2  Jursassic World          Irrfan Khan
3        Insurgent     Shailene Woodley
4        Insurgent           Theo James


Q:

C++ print template container error (error: ambiguous overload for 'operator<<') understanding?

I want to write template function which can print container like std::vector, std::list.
Below is my function, just overload <<.
template<typename Container>
std::ostream& operator<<(std::ostream& out, const Container& c){
    for(auto item:c){
        out<<item;
    }
    return out;
}

Test code as below:
int main(){
    std::vector<int> iVec{5, 9, 1, 4, 6};
    std::cout<<iVec<<std::endl;
    return 0;
}

ouput:
59146

And I want to add a space string in each value(output like 5 9 1 4 6), so I change the function to:
template<typename Container>
std::ostream& operator<<(std::ostream& out, const Container& c){
    for(auto item:c){
        out<<item<<" ";
    }
    return out;
}

Then it get error:
merror: ambiguous overload for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'const char [2]')
         out<<item<<" ";

I know << can output common type like.
int a = 0;
double f = 0.3;
std::string s = "123";
std::cout<<a<<f<<s<<std::endl;

So Why get the above error ? And is there any way to solve it?
I have see this question Ambiguous overload for ‘operator<<’ in ‘std::cout << but I still can't understand clearly.
All code:
#include <iostream>
#include <vector>

template<typename Container>
std::ostream& operator<<(std::ostream& out, const Container& c){
    for(auto item:c){
        out<<item;
        // out<<item<<" "; // error
    }
    return out;
}

int main(){
    std::vector<int> iVec{5, 9, 1, 4, 6};
    std::cout<<iVec<<std::endl;
    return 0;
}

A:

Declaring template<typename Container> could be dangerous as this template includes 'all' variable types int, char etc. Due to this compiler does not know which operator<< to use.
In order to take only container type variables use template of templates.
Here is working code for you
template<typename T, template <typename, typename> class Container>
std::ostream& operator<<(std::ostream& out, const Container<T, std::allocator<T>>& c) {
    for (auto item : c) {
        out << item << " ";
    }
    return out;
}

int main()
{
    cout << "Hello world" << endl;
    int arr[] = { 0,3,6,7 };
    vector<int> v(arr, arr+4);
    cout << v << endl;
    return 0;
}

A:

@miradham explained the issue very well.
but this a more generic solution using SFINAE to make the overload considered only for types on which the range-based for loop can be used, what ever their template arguments can be.
type coming form std::basic_string were ignored to prevent ambiguity with the standard operator << to display strings
c-style array will not be displayed using this overload even though they could because they are decayed to pointers and displayed with the standard operator <<
#include <iostream>
#include <vector>
#include <type_traits>
#include <array>
#include <string>

template<template<typename...> typename From, typename T>
struct is_from : std::false_type {};

template<template<typename...> typename From, typename ... Ts>
struct is_from<From, From<Ts...> > : std::true_type {};

template <typename...>
using void_t = void;

template <typename T, typename = void>
struct is_input_iterator : std::false_type { };

template <typename T>
struct is_input_iterator<T,
    void_t<decltype(++std::declval<T&>()),
           decltype(*std::declval<T&>()),
           decltype(std::declval<T&>() == std::declval<T&>())>>
    : std::true_type { };

template<typename Container,
typename std::enable_if<is_input_iterator<decltype(std::begin(std::declval<Container>()))>::value &&
                        is_input_iterator<decltype(std::end(std::declval<Container>()))>::value &&
                        !is_from<std::basic_string, Container>::value, int>::type = 0>
std::ostream& operator<<(std::ostream& out, const Container& c){
    for(const auto& item:c){
        out << item << " ";
    }
    return out;
}

int main(){

    std::array<int, 6> arr{0, 1, 2, 3, 4, 5};
    std::vector<int> vec{5, 9, 1, 4, 6};

    std::cout << vec << std::endl;
    std::cout << arr << std::endl;
    std::cout << std::string("test") << std::endl;
    return 0;
}

A:

The problem is that the templated type Container can match any type, not just containers.  That includes the " " you are trying to print.
If you look at the error message from a different compiler: https://godbolt.org/g/3YKtca
<source>:5:15: note: candidate function [with Container = char [2]]

std::ostream& operator<<(std::ostream& out, const Container& c){

Perhaps you want a partial specialization of vector<T> to only take vectors.   Determining if a type is a container is a more complicated problem.
#include <iostream>
#include <vector>

template<typename E, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<E, A>& c){
    for(auto item:c){
        out<<item;
        out<<item<<" "; // error
    }
    return out;
}

int main(){
    std::vector<int> iVec{5, 9, 1, 4, 6};
    std::cout<<iVec<<std::endl;
    return 0;
}

https://godbolt.org/g/NJNwmN


Q:

Extreme points of the set of two probability measures with same marginals

I am interested in the extreme points of the set $S$ of pairs of probability measures on $[0, 1]^2$ having the same marginals. More specifically, $(\mu_1, \mu_2) \in S$, where $\mu_1$ and $\mu_2$ are two probability measures on $[0, 1]^2$, if:
$$\mu_1(A\times[0,1]) = \mu_2(A\times[0,1]), \forall A \in \mathcal{B}([0, 1]) \\
\mu_1([0,1] \times B) = \mu_2([0,1] \times B), \forall B \in \mathcal{B}([0, 1]).$$
This set is a convex set and I would like to characterize it's extreme points. My hypothesis is that the extreme points of this set are made of a finite number of Dirac measures.
It's clear that measures such as $(\delta_{a_1, b_1}, \delta_{a_1, b_1})$ for $(a_1, b_1) \in \mathbb{R}^2$, where $\delta_{a_1, b1}$ denotes the Dirac measure supported at $(a_1, b_1) \in [0, 1]^2$, are extreme points but you can also find more exotic ones such as:
$$\left( \frac{1}{2} (\delta_{a_1, b_1} + \delta_{a_2, b_2}), \frac{1}{2} (\delta_{a_1, b_2} + \delta_{a_2, b_1}) \right), ~\text{for}~a_1, a_2, b_1, b_2 \in [0, 1]^4.$$
You can construct extreme measures similar as this one with $n$ Dirac measures for all $n \in \mathbb{N}$. For a given $n$, they are equivalent to:
$$\left( \frac{1}{n} \sum_{k=1}^n \delta_{a_k, b_k}, \frac{1}{n}( \sum_{k=1}^{n-1} \delta_{a_k, b_{k+1}} + \delta_{a_n, b_1})\right), ~\text{for}~a_1, \ldots, a_n, b_1, \ldots, b_n \in [0, 1]^{2n}$$
Let's denote the set made of all extreme probability measures with a finite number of Dirac measures $A$. I've been able to prove that the convex hull of $A$ is dense in $S$. From Milman theorem it follows that the extreme points are included in the closure, but I'm unable to conclude from there.
Is there a way to conclude or to disprove my hypothesis ? I've looked at some elements of the closure but they are not extreme points.

A:

I could be misinterpreting your question/hypothesis, but this seems to be a counterexample:
Let $\mu_1$ be the "uniform" probability measure on the line $L_1 \subset [0, 1)^2$ given by $y = x$ and let $\mu_2$ be the "uniform" probability measure on the line $L_2 \subset [0, 1)^2$ given by $y = x + \alpha$ (mod $1$), where $\alpha$ is some irrational number. Specifically, for measurable $E \subset [0, 1]^2$ we have
\begin{align*}
\mu_1(E) &= \mu(\{x \in [0, 1) \mid (x, x) \in E\}) \\
\mu_2(E) &= \mu(\{x \in [0, 1) \mid (x, T(x)) \in E\}),
\end{align*}
where $\mu$ is the Lebesgue measure on $[0, 1)$ and $T : [0, 1) \to [0, 1)$ is the irrational rotation given by $x \mapsto x + \alpha \text{ (mod $1$)}$. Note the marginals $\mu_{1x}, \mu_{1y}, \mu_{2x}, \mu_{2y}$ are all equal to $\mu$, so $(\mu_1, \mu_2) \in S$.
Suppose we had $(\mu_1, \mu_2) = \lambda(\mu_1', \mu_2') + (1-\lambda)(\mu_1'', \mu_2'')$ for some other $(\mu_1', \mu_2'), (\mu_1'', \mu_2'') \in S$ and $0 < \lambda < 1$. Then since $\mu_i([0, 1]^2 - L_i) = 0$, we must have $\mu_i'([0, 1]^2 - L_i) = \mu_i''([0, 1]^2 - L_i) = 0$ as well, hence $\mu_i', \mu_i''$ are supported on the line $L_i \subset [0, 1)^2$ for $i = 1, 2$.
Now since $\mu_1'$ is supported on $L_1$, we must have $\mu_{1x}' = \mu_{1y}'$ because for any measurable $A \subset [0, 1)$, $\mu_{1x}'(A) = \mu_{1y}'(A) = \mu_1'(\{(a, a) \mid a \in A\})$. Similarly, since $\mu_2'$ is supported on $L_2$, we must have
$$\mu_{2x}'(A) = \mu_2'(\{(a, T(a)) \mid a \in A\}) = \mu_{2y}'(T(A))$$
hence $\mu_{2x}' = \mu_{2y}' \circ T$. But because $(\mu_1', \mu_2') \in S$, we have $\mu_{1x}' = \mu_{2x}'$ and $\mu_{1y}' = \mu_{2y}'$, hence
$$\mu_{1x}' = \mu_{1y}' = \mu_{2y}' = \mu_{2x}' \circ T^{-1} = \mu_{1x}' \circ T^{-1}$$
so $\mu_{1x}'$ is invariant under $T$. It's a standard result that the unique invariant measure under $T$ is the Lebesgue measure $\mu$ (see e.g. Example 4.11 of Einsiedler and Ward's Ergodic Theory), hence $\mu_{1x}' = \mu$, and thus $\mu_{1y}', \mu_{2x}', \mu_{2y}' = \mu$ as well. But since they're supported on $L_1$ and $L_2$ respectively, each of $\mu_1', \mu_2'$ is completely determined by either of its marginals, so $(\mu_1', \mu_2') = (\mu_1, \mu_2)$ (and the same holds for $(\mu_1'', \mu_2'')$). This means $(\mu_1, \mu_2)$ is an extreme point.


Q:

how to display Dictionary values to Data Grid View in window forms

public static Dictionary<int, Account> accSavingList = new Dictionary<int,Account>();

[Dictionary][1]I have created a Dictionary<int, Account> acc which stores a value as a following :
int(Account number): takes a value from windows form
Account(account class data type): takes  3 values (account name, balance,minimum balance ).
Now i want to display dictionary values to data grid view which has 4 columns:
'account no' 'account name' 'balance' 'minimum balance'.
i have used:
gridView.DataSource=Account.accSavingList;

But that is not working

A:

Whether or not the grid will display the values correctly depends on how you have configured your grid and it's column bindings, but here is how you can flatten your dictionary into a proper datasource (I am guessing at property names so you will not be able to directly copy this code) :
//a.Value is the Account class instance from each dictionary entry
var acclist = accSavingList.Select( a => new {
    AccountNo = a.Key,
    AccountName = a.Value.AccountName,
    Balance = a.Value.Balance,
    MinimumBalance = a.Value.MinimumBalance
}).ToList();

gridView.DataSource = acclist;


Q:

PixlUI not getting fonts in android

I am trying to use PixlUI and have custom fonts working with it. I am not able to get it working on Android Studio. I have followed every step on there site.
I still get
Asset not found: fonts/Roboto-Regular.ttf (2 similar errors not shown)

assets/fonts folder has ttf files.

and I am using:
<com.neopixl.pixlui.components.textview.TextView
        android:id="@+id/labelattributetext"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Specification"
        android:textColor="@drawable/text_selector_listview"
        pixlui:copyandpaste="false"
        style="@style/TextRoboto.t1"
        pixlui:clearclipboardcontent="true"/>

And styles.xml has the follow
style name="TextRoboto.t1" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="typeface">Roboto-Regular.ttf</item>
        <item name="android:textSize">16sp</item>
    </style>

What could be wrong here?

A:

Asset not found: fonts/Roboto-Regular.ttf (2 similar errors not shown)

If you get this error in the Android Studio Layout Editor, this is normal, please use PixlUI 1.1.0 and use the 23 target preview:

And so all will be ok
About Asset, be sure your asset folder is recognized by Android Studio (don't create folder by yourself) and put your fonts like this:

And in the XML style file:


Q:

Do uninitialized objects exist in C++?

If all objects have at least one constructor be it default c'tor defined by the compiler or user defined then how can objects be uninitialized.

A:

It is possible to declare objects on which no initializations are performed. These objects do exist, they have an indeterminate value, and using this value is undefined behavior (there is an exception to this rule for chars).
Such object can be created by default-intialization.
This is stated in the c++ standard, (§11.6 Initializers)[dlc.init]:

To default-initialize an object of type T means:
(7.1) — If T is a (possibly cv-qualified) class type (Clause 12), constructors are considered. The applicable
  constructors are enumerated (16.3.1.3), and the best one for the initializer () is chosen through overload
  resolution (16.3). The constructor thus selected is called, with an empty argument list, to initialize the
  object.
(7.2) — If T is an array type, each element is default-initialized.
(7.3) — Otherwise, no initialization is performed.

Nevertheless, static objects are always zero-initialized. So any built-in with dynamic or automatic storage duration may not be initialized, even if it is a suboject;
int i; //zero-initialized

struct A{
  int i;
  };

struct B
  {
  B(){};
   B(int i)
    :i{i}{}
  int i;
  int j;
  };
A a; //a.i is zero-initialized

int main()
  {
   int j;             //not initialized
   int k{};           //zero-initialized
   A b;               //b.i not initialized
   int* p = new int;  //*p not initialized
   A*   q = new A;    //q->i not initialized
   B ab;              //ab.i and ab.j not initialized
   B ab2{1};          //ab.j not initialized
   int xx[10];        //xx's element not initialized.

   int l = i;    //OK l==0;
   int m = j;    //undefined behavior (because j is not initialized)
   int n = b.i;  //undefined behavior
   int o = *p; //undefined behavior
   int w = q->i; //undefined behavior
   int ex = x[0] //undefined behavior
   }

For member initialization [class.base.init] may help:

In a non-delegating constructor, if a given potentially constructed subobject is not designated by a mem-
  initializer-id (including the case where there is no mem-initializer-list because the constructor has no
  ctor-initializer), then
  — if the entity is a non-static data member that has a default member initializer (12.2) and either
(9.1.1) — the constructor’s class is a union (12.3), and no other variant member of that union is designated
  by a mem-initializer-id or
(9.1.2) — the constructor’s class is not a union, and, if the entity is a member of an anonymous union, no
  other member of that union is designated by a mem-initializer-id,
  the entity is initialized from its default member initializer as specified in 11.6;
(9.2) — otherwise, if the entity is an anonymous union or a variant member (12.3.1), no initialization is
  performed;
(9.3) — otherwise, the entity is default-initialized (11.6)

Members of a trivial anonymous union may also not be initialized.

Also one could ask if an object life-time could begin without any initialization, for exemple by using a reinterpret_cast. The answer is no: reinterpret_cast creating a trivially default-constructible object


Q:

How to use Team: Signin with VSCode

I am running into an error message which I don't understand while trying the following commande:
Team: Signin
It used to work back then but now I have an error message.
Error message picture

Info:

Version: 1.44.2 (user setup)
Commit: ff915844119ce9485abfe8aa9076ec76b5300ddd
Date: 2020-04-16T16:36:23.138Z
Electron: 7.1.11
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Windows_NT x64 10.0.18363

I can provide more informations if needed, thank you in advance.

A:

According to the tag of the question, you are using TFVC version control. With TFVC, the extension uses information about the current workspace to determine how to connect to Azure DevOps Services (or your Team Foundation Server). Workspaces can be created using the Visual Studio IDE, Eclipse or with the JetBrains IDEs (e.g, Android Studio, IntelliJ).
Note: At this time, you will need to have a local TFVC workspace already available on your local machine. More information about the difference between the two types (and how to determine which one you're using) can be found here.
In order to provide TFVC support in Visual Studio Code, the extension relies on the use of a TF command line client. Therefore, you will need to have one already installed and configured. TFVC support will not work without an available command line client.
About sign in ：  In order for the extension to be activated, a repository folder must be opened. The extension won't be activated if only a single file in the repository is opened.
You can refer to Team Foundation Version Control (TFVC) Support for details.
In addition, here is a detailed guide that describes how to solve the error you encountered. In this guide, the old version of the azure repo extension(Visual Studio Team Services) is used. Please view step 16.


Q:

Windows 7 system image: Previous increment not visible in Explorer

I tried out the backup tool built into Windows 7 Pro x64. In the help text, it says: "If you're saving your system images on an internal or external drive, or on CDs or DVDs, you can keep several versions of system images."
What I did as a test:

Attached a USB 3 HDD with ca. 600 GB of free space.
Using Windows 7's Backup and Restore, created a system image of the ca. 200 GB
system drive. This includes the two standard Windows 7 partitions: (C:) and System
Reserved:

Made a small change, adding text in a file, which would allow me later to compare
different increments.
Made another system backup using Backup and Restore.

Now, when I look at the USB drive, I only find one .vhd file per partition, with time stamp of the backup from step 4:

Does this mean that no increment has been created, i.e. the first backup has been overwritten? Can there perhaps be only one increment per day?

A:

I have found the answer in a 2009 TechNet article
“Learn more about system image backup”:

During the first backup, the backup engine scans the source drive and copies
  only blocks that contain data into a .vhd file stored on the target, creating
  a compact view of the source drive. The next time a system image is created,
  only new and changed data is written to the .vhd file, and old data on the
  same block is moved out of the VHD and into the shadow copy storage area.
  Volume Shadow Copy Service is used to compute the changed data between
  backups, as well as to handle the process of moving the old data out to the
  shadow copy area on the target. This approach makes the backup fast (since
  only changed blocks are backed up) and efficient (since data is stored in a
  compact manner). When restoring the image, blocks will be restored to their
  original locations on the source disk. If you want to restore from an older
  backup, the engine reads from the shadow copy area and restores the
  appropriate blocks.

In a nutshell: Only the last backup is displayed in Windows Explorer. Previous
increments are stored in the shadow copy storage area on the backup medium.
How VHDs from previous increments can be accessed for attaching using Windows
7’s Disk Management is not clear to me.


Q:

How to take in account children for :nth-child

I have some simple html

row1

row2

row3

row4.1

row4.2.1

row4.2.2

row4.3

row4.4

row5

and css file
div:nth-child(even)
{
   background-color:green;
}

I want to make all odd rows green and to not take care of hierarchy. But in result I have  this

What am I doing wrong? how to make green rows 2, 4.1, 4.2.2 and 4.4. All other shoud be white.
Is it possible without javascript by css only?

A:

Unfortunately, what you're describing is strictly not possible with CSS selectors.
The :nth-child selector (like :nth-of-type) only operates within the context of a single isolated group of children (not descendants). And indeed, that is exactly what you're seeing: the even children of each parent being highlighted. As you've written that selector, it will match rows 2, 4 (i.e. the parent of all rows 4.x), 4.2 (i.e. the parent of all rows 4.2.x), and 4.4, because they are each even-indexed children of their parents.
I'm afraid your options are (as I see it):

Flattening the DOM so that all of the rows are children of the same parent element. I suspect this might not be possible in your application.
Manually specifying whether a row is highlighted using JS and some sort of .highlighted CSS class. Not hard, but also kinda annoying to keep up to date if rows are added/removed/moved. Can be easily accomplished in jQuery by adding a .row CSS class to each row and using $('.row:even').addClass('highlighted');. See this jsfiddle. The jQuery-less method is more verbose but also quite simple.
Creating a vertically-repeating background image (or set of evenly-spaced divs) for the line highlights. If you know the height of each line beforehand, you can simply create a 1px-wide image with twice the height of the row. Highlight the bottom half of the image and set the background image to repeat. On the one hand, this can be done entirely in CSS (especially with inline base64-encoded images). On the other hand, it can't handle variable-height rows.


Q:

Compartir variable de sharedpreferences ubicada en MainActivity y una clase en android

Tengo una variable que se captura en el MainActivity y los guardó en un sharedpreference y la proxima vez que lanzo la app puedo usar el valor de  esta variable, pero necesito que esta misma variable también sea  leída en una clase llamada TcpClient pero esta clase no tiene constructor, alguien me puede decir como hacer esto, la variable que quiero compartir es "mconfigipaddress".
Aqui esta mi MainActivity
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

private TcpClient mTcpClient;

public static String SERVER_IP = "192.168.4.1";
public static String SERVER_PORT = "8888";
.
.
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );
.
.
sharedpreferences = getSharedPreferences( mypreference,Context.MODE_PRIVATE );
if (sharedpreferences.contains( SERVER_IP )) {
    mconfigipaddress = sharedpreferences.getString( SERVER_IP, "");
}
if (sharedpreferences.contains( SERVER_PORT )) {
    mconfigport = sharedpreferences.getString( SERVER_PORT, "");
}

Aqui esta el codigo del TcpClient:
public class TcpClient {

private String  mconfigipaddress = ""; //your computer IP address
private String  mconfigport = ;
private String  mServerMessage;                        // message to send to the server
private OnMessageReceived mMessageListener = null;    // sends message received notifications
private boolean mRun = false;                         // while this is true, the server will continue running
private PrintWriter mBufferOut;                       // used to send messages
private BufferedReader mBufferIn;                     // used to read messages from the server

private String Modelox="";
public Boolean statusWIFIX = false;

/**
 * Constructor of the class. OnMessagedReceived listens for the messages received from server
 */
public TcpClient(OnMessageReceived listener) {
    mMessageListener = listener;
}

/**
 * Sends the message entered by client to the server
 * @param message text entered by client
 */
public void sendMessage(String message) {
    if (mBufferOut != null && !mBufferOut.checkError()) {
        mBufferOut.println(message);
        mBufferOut.flush();
    }
}

interface TcpListener
{
    void onReportStatusWIFIX(boolean statusWIFIX);
}

/**
 * Close the connection and release the members
 */
public void stopClient() {

    statusWIFIX = false;
    Log.e( "DEBUG-->", "Coneccion Cerrada: "+ statusWIFIX );
    sendMessage(Constants.CLOSED_CONNECTION+": " + Modelox);                // send message that we are closing the connection
    mRun = false;
    if (mBufferOut != null) {
        mBufferOut.flush();
        mBufferOut.close();
    }
    mMessageListener = null;
    mBufferIn = null;
    mBufferOut = null;
    mServerMessage = null;
}

public void run() {
    mRun = true;
    try {
        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);      //here you must put your computer's IP address.
        Log.e("TCP Client", "C: Connecting...");
        Socket socket = new Socket(serverAddr, SERVER_PORT);            //create a socket to make the connection with the server
        try {
            //sends the message to the server
            mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            //receives the message which the server sends back
            getDeviceName();
            mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            sendMessage(Constants.LOGIN_NAME+": "+ Modelox);                   // send login name

            statusWIFIX = true;
            while (mRun) {                                              //in this while the client listens for the messages sent by the server
                mServerMessage = mBufferIn.readLine();
                if (mServerMessage != null && mMessageListener != null) {
                    mMessageListener.messageReceived(mServerMessage);   //call the method messageReceived from MyActivity class
                }
            }
            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
        } catch (Exception e) {
            Log.e("TCP", "S: Error", e);
        } finally {
            socket.close();                                             //the socket must be closed. It is not possible to reconnect to this socket
                                                                        // after it is closed, which means a new socket instance has to be created.
        }

    } catch (Exception e) {
        Log.e("TCP", "C: Error", e);
    }
}

public interface OnMessageReceived {                                    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    public void messageReceived(String message);                        //class at on asynckTask doInBackground
}

A:

Para hacer mejor manejo de las preferencias, puedes crear una clase aparte donde crees los métodos de guardar y obtener los valores que guardes en las preferencias, de esta forma se te hará mas fácil llamarlas desde donde necesites hacerlo, ejemplo:
public class preferencias {

private static final String PREFERENCES = "preferences";

public static void SetStringValue(Context context, String key, String save) {
        SharedPreferences sharedPref  = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref .edit();
        editor.putString(key, save);
        editor.apply();
    }
}

public static String GetStringValue (Context context, String key) {
        SharedPreferences sharedPref  = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
        return sharedPref .getString(key, null);
    }

Con esos dos métodos puedes guardar u obtener las preferencias, con uno guardas el String que desees, y con el otro obtienes el mismo, en caso de no tener nada guardado, retorna nulo. Ojo, esto es un ejemplo, no necesariamente debe ser así, pero te puede ayudar con orden al código y acceder a las mismas sin problema alguno. Luego para llamarlas de ser necesario, ya sea para guardar o para obtener seria algo como:
Para guardar el valor:
Desde fragment:
preferencias.SetStringValue(getContext(), "KEY-GUARDADA", stringguardado);

Desde Activity:
preferencias.SetStringValue(Activityname.this, "KEY-GUARDADA", stringguardado);

Desde Adapter de RecyclerView (Quizás sea esto lo que necesites aplicar):
//Declaras
private Activity activity;
//Luego lo pasas en el contexto
preferencias.SetStringValue(activity, "KEY-GUARDADA", stringguardado);

Para obtener el valor:
Desde fragment:
String stringguardado = preferencias.GetStringValue(getContext(), "KEY-GUARDADA");

Desde Activity:
String stringguardado = preferencias.GetStringValue(Activityname.this, "KEY-GUARDADA");

Desde Adapter de RecyclerView (Quizás sea esto lo que necesites aplicar):
//Declaras
private Activity activity;
//Luego lo pasas en el contexto
String stringguardado = preferencias.GetStringValue(activity, "KEY-GUARDADA");

Como mencione anteriormente, es una forma de hacerlo, de igual forma puedes aplicar la que usas.
//Declaras
    private Activity activity;

y se lo pasas como contexto cuando necesites acceder a ellas (preferencias).


Q:

Httpclient deprecated

I'm developing an app using HTTPclient for datatransfer. Since HTTPClient is deprecated, I want to port the network part to URLConnection.
ConectionHttpClient.java
package conexao;

import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;

public class ConexaoHttpClient {
    public static final int HTTP_TIMEOUT = 30 * 1000;
    private static HttpClient httpClient;
    private static HttpClient getHttpClient(){
        if (httpClient == null){
            httpClient = new DefaultHttpClient();
            final HttpParams httpParams = httpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParams, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(httpParams, HTTP_TIMEOUT);
        }return httpClient;

    }

public static String executaHttpPost(String url, ArrayList<NameValuePair> parametrosPost) throws Exception{
    BufferedReader bufferedReader = null;
    try{
        HttpClient client = getHttpClient();
        HttpPost httpPost = new HttpPost();
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parametrosPost);
        httpPost.setEntity(formEntity);
        HttpResponse httpResponse = client.execute(httpPost);
        bufferedReader = new BufferedReader(new InputStreamReader(httpPost.getEntity().getContent()));
        StringBuffer stringBuffer = new StringBuffer(" ");
        String line = " ";
        String LS = System.getProperty("line.separator");
        while ((line = bufferedReader.readLine()) != null){
            stringBuffer.append(line + LS);
        }bufferedReader.close();

    String resultado = stringBuffer.toString();
    return resultado;
}finally{
    if (bufferedReader != null){
        try{
            bufferedReader.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

}
}

MainActivity.java
package com.app.arts;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import conexao.ConexaoHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public cla`enter code here`ss MainActivity extends Activity {

    EditText editEmail, editSenha;
    Button btnEntrar, btnEsqueciSenha, btnCadastrar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    editEmail = (EditText)findViewById(R.id.editEmail);
    editSenha = (EditText)findViewById(R.id.editSenha);
    btnEntrar = (Button)findViewById(R.id.btnEntrar);
    btnEsqueciSenha = (Button)findViewById(R.id.btnEsqueciSenha);
    btnCadastrar = (Button)findViewById(R.id.btnCadastrar);

    btnEntrar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v){

        String urlPost="http://192.168.25.5/arts/admin/login.php";
        ArrayList<NameValuePair> parametrosPost = new ArrayList<NameValuePair>();
        parametrosPost.add(new BasicNameValuePair("email", editEmail.getText().toString()));
        parametrosPost.add(new BasicNameValuePair("senha", editSenha.getText().toString()));
        String respostaRetornada = null;
        try{
         respostaRetornada = ConexaoHttpClient.executaHttpPost(urlPost, parametrosPost);
         String resposta = respostaRetornada.toString();
         resposta = resposta.replaceAll("//s+", "");
         if (resposta.equals("1"))
           mensagemExibir("Login", "Usuario Valido");
         else
           mensagemExibir("Login", "Usuario Invalido");
        }catch(Exception erro){
          Toast.makeText(MainActivity.this, "Erro: " +erro, Toast.LENGTH_LONG);
         }
       }
         public void mensagemExibir(String titulo, String texto){
      AlertDialog.Builder mensagem = new AlertDialog.Builder(MainActivity.this);
      mensagem.setTitle(titulo);
      mensagem.setMessage(texto);
      mensagem.setNeutralButton("OK", null);
      mensagem.show();

     }

    });
}
}

A:

This is the solution that I have applied to the problem that httpclient deprecated in this version of android 22
Metod Get
 public static String getContenxtWeb(String urlS) {
    String pagina = "", devuelve = "";
    URL url;
    try {
        url = new URL(urlS);
        HttpURLConnection conexion = (HttpURLConnection) url
                .openConnection();
        conexion.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
        if (conexion.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conexion.getInputStream()));
            String linea = reader.readLine();
            while (linea != null) {
                pagina += linea;
                linea = reader.readLine();
            }
            reader.close();

            devuelve = pagina;
        } else {
            conexion.disconnect();
            return null;
        }
        conexion.disconnect();
        return devuelve;
    } catch (Exception ex) {
        return devuelve;
    }
}

Metodo Post
 public static final String USER_AGENT = "Mozilla/5.0";

public static String sendPost(String _url,Map<String,String> parameter)  {
    StringBuilder params=new StringBuilder("");
    String result="";
    try {
    for(String s:parameter.keySet()){
        params.append("&"+s+"=");

            params.append(URLEncoder.encode(parameter.get(s),"UTF-8"));
    }

    String url =_url;
    URL obj = new URL(_url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "UTF-8");

    con.setDoOutput(true);
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
    outputStreamWriter.write(params.toString());
    outputStreamWriter.flush();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + params);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine + "\n");
    }
    in.close();

        result = response.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }finally {
    return  result;
    }

}


Q:

Will this compare arrays in JavaScript?

I am trying to compare long string numbers. The number length is between 1 and fifty.  Comparing the length of the strings worked well but if they were equal length it was a bit harder.  I decided to make the strings into arrays, and compare values until they were different.  I think this is a formatting error, but I'm not sure.
function compareIntegers(a, b) {
  //coding and coding..
  var aSplit = a.split("")
  var bSplit = b.split("")

if (a.length > b.length){
    return "greater";
}
        if (b.length > a.length){
            return 'less';
        }
if (a.length == b.length){
        for (i=0; aSplit.length; i++){
            if (bSplit.indexOf(aSplit[i] ===-1) {
                if (aSplit[i] > bSplit[i]){
                    return 'greater';
                    }
        if (aSplit[i] < bSplit[i]){
            return 'less';
            }
     else return 'equal';
         }
     }
}

}
describe("Basic Tests", function(){
it("It should works for basic tests.", function(){

Test.assertEquals(compareIntegers("12","13"),"less")

Test.assertEquals(compareIntegers("875","799"),"greater")

Test.assertEquals(compareIntegers("1000","1000"),"equal")

Test.assertEquals(compareIntegers("999","1000"),"less")

Test.assertEquals(compareIntegers("123","122"),"greater")

Test.assertEquals(compareIntegers(
    "1000000000000000000000000000000000",
    "1000000000000000000000000000000001"),
    "less"
)
Test.assertEquals(compareIntegers(
    "1000000000000000000000000000000002",
    "1000000000000000000000000000000001"),
    "greater"
)

Test.assertEquals(compareIntegers(
    "10000000000000000000000000000000000",
    "1000000000000000000000000000000001"),
    "greater"
)

})})

A:

There's no reason to split the strings into arrays, you can easily access the single characters using an index property or .charAt(). And there's no reason to do this character-by-character comparison by yourself at all (and making mistakes like bSplit.indexOf(aSplit[i])), when that is just the default behaviour of comparing two strings. So I'd write
function compareIntegerStrings(a, b) {
  a = a.replace(/^0*/, ""); // strip leading zeroes
  b = b.replace(/^0*/, "");

  if (a.length > b.length){
    return 1;
  } else if (b.length > a.length){
    return -1;
  } else { // a.length == b.length
    if (a > b) {
      return 1;
    } else if (b > a) {
      return -1;
    }
  }
  return 0;
}
function comparisonToString(c) {
  return ['less', 'equal', 'greater'][Math.sign(c)];
}

You can also shorten that comparison pyramid in compareIntegerStrings to
return Math.sign(a.length - b.length) || +(a>b) || -(a<b);


Q:

¿Se puede usar sizeof dentro de una funcion para calcular el tamaño de un array?

No comprendo porque al tratar de calcular el tamaño dentro de la funcion size retorna 1 y al hacerlo desde el main, si me retorna el tamaño normal de 5.
#include<iostream>
using namespace std;

int size(int A[]){

    int _size=sizeof(A)/sizeof(A[0]);
    return _size;
}

int main(){
    int A[5];

    cout<<"Tamaño de A(FuncionSize): "<<size(A)<<endl;
    cout<<"Tamaño de A(Normal)"<<sizeof(A)/sizeof(A[0])<<endl<<endl;
    system("pause");
    return 0;
}

´´´

A:

El problema es que en C los arrays se pasan por referencia. Es decir, cuando llamas a la función size(A), no se está copiando el array completo al interior de la función, sino tan sólo la dirección en la que el array está guardado.
Esto puedes verificarlo porque si dentro de la función alteras por ejemplo A[0], verás que el array del programa principal también resulta alterado ¡porque sólo hay un array! No hay una copia.
Esto implica que cuando haces sizeof(A) el resultado es diferente según dónde lo hagas:

En el programa principal A es un array de 5 elementos, cada uno de ellos de tipo int por lo que sizeof(A) te dará como resultado 5*sizeof(int)
En la función A es una referencia al array del programa principal. Tales referencias son en realidad punteros. Por tanto sizeof(A) te devolverá el tamaño del puntero. Habitualmente el tamaño de un puntero suele coincidir con el tamaño de un entero (puesto que en el fondo un puntero es un número entero, que representa la dirección de memoria en la que está otro dato). Por esto al dividir por sizeof(A[0]) te sale 1, aunque esto es casi  una casualidad. Si el tamaño del puntero fuese 64 bits, mientras que el tamaño del entero fuese 32, tu función size() habría retornado 2.

Y por si te lo estás preguntando, no, no hay forma de saber desde la función cuántos elementos tiene el array que le has pasado como parámetro. Todo lo que la función recibe es la dirección de memoria donde comienza el array, pero no la dirección en la que termina. Es por esto que la mayoría de funciones C que reciben como parámetro algún tipo de array (por ejemplo, un buffer), requieren un parámetro adicional, habitualmente llamado size, donde se les pasa cuántos elementos tiene ese array. Sin ir mas lejos, main() recibe dos parámetros: argc y argv, siendo el segundo un array de cadenas y el primero un entero que le dice cuántos elementos tiene el array.


Q:

"Proof" of a combinatorics problem

I request help on the following "proof":
$$\binom{n-1}{0}\cdot\binom{r}{1}+\binom{n-1}{1}\cdot\binom{r}{2}+...+\binom{n-1}{r-1}\cdot\binom{r}{r}=\binom{n+r-1}{r-1}.$$
My Attempt:
I wrote an MS Excel macro to check for many combinations.
Private Sub CommandButton1_Click()
Dim n, r, Sum, score As Integer, result As String

n = Range("A5").Value

r = Range("B5").Value

Range("C5").Value = Application.WorksheetFunction.Combin(n + r - 1, r - 1)

Sum = 0

For i = 0 To r - 1

    sum = sum + Application.WorksheetFunction.Combin(n - 1, i) * Application.WorksheetFunction.Combin(r, i + 1)

Next i

Range("D5").Value = Sum

End Sub

The cells C5 and D5 match for the examples I chose.
The equation just becomes ugly if I try to open it up. Maybe there is a way if I use induction. Could anyone provide a hint (some property of combinations that I can use here)?
Please advise.

A:

Perhaps you are familiar with the Vandermonde identity
$$\binom x0\binom yk+\binom x1\binom y{k-1}+\cdots+\binom xk\binom y0=\binom{x+y}k.$$
Setting $\ x=n-1,\ y=r,\ k=r-1\ $ we get
$$\binom{n-1}0\binom r{r-1}+\binom{n-1}1\binom r{r-2}+\cdots+\binom{n-1}{r-1}\binom r0=\binom{n+r-1}{r-1}$$
which is the same as the identity you are trying to prove.


Q:

Div transition triggered by a tags

I am playing around with this fiddle I found which is really close to what I am trying to do:
http://jsfiddle.net/5N3YK/20/
The only thing is that when I try to change the section tags to div tags it breaks, and also I want the div's to fade instead of slide.
Help is always greatly appreciated!

A:

Try - http://jsfiddle.net/UDt7q/21/
(function($) {
    $.fn.Fader = function() {
        this.each(function() {
            $('a').bind('click', function(e) {
                e.preventDefault();
                $( "#hello div" ).fadeOut();
                $( "#hello div" + $(this).attr('href') ).fadeIn();
            })
        });
    }
})(jQuery);


Q:

MS Access import and append type conversion fail on date field

I am trying to import data from a text file and append it to a table in an MS Access 2010 database. All data imports and appends properly, with the exception of a date field.
The date field is in the format: yyyy-mm-dd hh:mm:ss
I can import the text file into a new table without issue. This works if I specify the field as text or date/time with various foramts. Where it fails is when I try to append it to an existing table. It does not matter whether the destination field data type is text or date/time.
It isn't the end of the world if I have to import the text file into a new table. But I find it very strange that I cannot import data form a text file to a text field.
If anyone can shed some light on what is causing this issue I would be very grateful.

A:

I had the same issue last week and believe it or not it took me a full day to sort it out.
I was creating a link to an Excel document where I was importing records to a table through an import query. All good except the date field which Access had mapped it like Text (the first 80-100 records of the field were blank, then a date and then blanks again).
Long story short, I tried a number of different approaches but on all of them I was getting a datatype mismatch error so I ended up with the solution below.
In my import query:
IIF(IsNull([Date Field]),NULL,CDate([Date Field]))


Q:

Type of Differential Equation $y''''$

I'm doing some differential equations exercises where I found this equation:
$$ y'''' + 2y'' + y = \sin t $$
I wanted to know which type of equation is this one, I'm not asking for the solution just the type of equation so I can have an idea of what to do.
Thanks!
EDIT So, what I'm doing is that I find the homogenous solution, which is:
$$ F*\cos t + G*\sin t $$
Then I do the particular solution:
$$ A*t*\sin t + B*t*\cos t $$
I find the derivatives and then I replace in the original equation, but when I do this I get this:
$$ 0 = \sin t $$

A:

No, that is NOT the general solution to the homogeneous equation! $y''''+ 2y''+ y= 0$ has characteristic equation $r^4+ 2r^2+ 1= (r^2+ 1)^2= 0$.
That is a fourth degree equation so has 4 roots. It can be reduced to $r^2+ 1= 0$.  $r= i$ and $-i$ are double roots.  The general solution is $y(t)= F \cos(t)+ G \sin(t)+ P t\cos(t)+ Q t\sin(t)$.
In order to get the specific solution that makes $y''''+ 2y'+ y= \sin(t)$, let $y(t)= At^2 \cos(t)+ Bt^2 \sin(t)$.


Q:

Can one object create multiple threads in Java

I am new to multi threading and while practising I wrote the following code. I want to call the createThred method to create a new thread evrytime I call it. However, With the below given code, everytime the createThread method is called, i get the same thread running again and again. Is it possible to create a new thread using the same object? Appararently not but just wanted to confirm if there is a way I dont know of.
public class ThreadStartRunnable implements Runnable {

    private Thread t;
    /*
     ThreadStartRunnable(String name) {
         t = new Thread(this, name);
        t.start();
        }
     */
       private Thread createThread(String name){

         t = new Thread(this,name);
         t.start();
         return t;
     }

    /**
     * @Override run
     *
     */
    public void run() {

        for(int i=0;i<=5;i++)
        {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("The current Thread is " + t.getName() + " and thread ID is " + t.getId());
        }
    }
    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args)  {
        // TODO Auto-generated method stub

        Thread t = Thread.currentThread();
        //new ThreadStartRunnable("User 1");
        //new ThreadStartRunnable("User 2");
        //ThreadStartRunnable c = new ThreadStartRunnable();
        ThreadStartRunnable t1 = new ThreadStartRunnable();

        t1.createThread("Child 1");
        t1.createThread("Child 2");

        for(int i=0;i<=5;i++)
        {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("The cirrent Thread is " + t.getName()+ " and thread ID is " + t.getId());
        }

    }

}

OUTPUT:
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The cirrent Thread is main and thread ID is 1
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The cirrent Thread is main and thread ID is 1
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The current Thread is Child 2 and thread ID is 9
The cirrent Thread is main and thread ID is 1
The cirrent Thread is main and thread ID is 1
The cirrent Thread is main and thread ID is 1
The cirrent Thread is main and thread ID is 1

A:

The reason why it always says Child 2 is because you are printing the name of the Thread t member, which is the last thread created.
Replace:
System.out.println("The current Thread is " + t.getName() + " and thread ID is " + t.getId());
with
System.out.println("The current Thread is " + Thread.currentThread().getName() + " and thread ID is " + Thread.currentThread().getId());

Otherwise it's fine to use same runnable:
Initializing two threads with the same instance of a runnable

A:

Change you code in run method to display name of the current thread instead:
System.out.println("The current Thread is " + Thread.currentThread().getName() + " and thread ID is " + Thread.currentThread().getId());

Every time you create new Thread you override instance variable t, so it is not safe to use it to track thread name and ID.


Q:

What causes this weird sitar-like sound?

For a few weeks now I've been noticing  that when I play the 7th fret  on the 6th string a get a weird squeak mixing into the sound. Here is audio of me playing the 6th string up to the 7th fret and then some frets around it:

I haven't noticed anything l that on other frets and strings an upon visual inspection  neither the string nor fretboard appear in anyway different on that fret. What could be causing this?

A:

Fret buzz - the next fret up is high & the string is hitting it as you play. You could test with a hard steel rule to see if it rocks when placed edge-on to the fret-board.
A luthier could fix it...
...or if you're a) daring b) skilled or c) poor, you could try tapping it down with a small hammer & a piece of wood placed over the frets so as not to dent them, or d) adventurous, a file. [caveat emptor in all the above]
or you could lift the action, overall or just on that string, depending on your guitar bridge/saddle setup, but that would change how the guitar feels.


Q:

How to calculate weight of an object orbiting another object?

How do we calculate weight of an object which is orbiting another bigger object in the space?
For example, comparing the pair of Sun-Earth, Earth is orbiting Sun due to the force applied by Sun on Earth. Earth is undergoing non-uniform acceleration.
Does Earth has weight? I think it has weight, but no sensation of it since it is in free fall. Is the weight of Earth changing every moment? Why it is believed popularly that Earth doesn't have weight?

A:

Weight and mass are two different things:

The mass of an object is an intrinsic property of the object itself.  Mass does not have a direction. Mass is often expressed in kilograms. A person's body has the same mass whether that person is standing on the earth, standing on the moon, or falling off a roof.
The weight of an object depends on how it is moving, and weight has a direction. An object in free-fall is weightless. An object that is not in free-fall has weight. The amount of weight is has depends on how much the object is deviating from free-fall, and the direction of its weight depends on the direction in which it is deviating from free-fall. Weight is often expressed in pounds or Newtons. The same person's body has one weight when standing on the earth, a different weight when standing on the moon, and no weight at all when falling off a roof. (Please don't try this at home.) We can even say that the same person's body has different weights when standing on opposite sides of the earth — same magnitude, but different direction.

So, what about the earth?

The earth has an enormous mass. Many, many, many kilograms.
The earth, regarded as a single object, is in free-fall around the sun. Therefore, regarded as a single object, the earth is weightless.

For an explanation (with a nice picture) of why an orbiting object qualifies as a falling object, see this post.
If we used a giant rocket engine to push the earth out of its orbit, then the earth would have weight while it is being pushed by the rocket, because it is deviating from free-fall. The amount of weight it would have would depend on how hard the rocket is pushing, and the direction of the weight would depend on the direction in which the rocket is pushing.
We can also regard the earth as a being composed of lots of parts — mountains, oceans, magma, and so on. If we consider just one part of the earth, say just one mountain, then that mountain has a large weight. It has a large weight because the substrate underneath the mountain is pushing up on it  with just enough force to prevent the mountain from freely falling toward the center of the earth. The earth has a large mass, and mass creates gravity, so all the parts of the earth would fall toward the center if they were not prevented from doing so by pushing on each other. In this sense, each part of the earth has weight, because those individual parts are not in free-fall; the other parts underneath them (underneath = closer to the center of the earth) are pushing up on them (up = away from the center of the earth) just enough to prevent them from freely falling toward the center.
But when the earth is regarded as a single object in orbit (freely falling) around the sun, the earth is weightless overall.
The question mentioned the word "acceleration." This is worth clarifying. The word acceleration is used with two different meanings:

It is used to mean that the distance between the object and some other reference object (like the distance of a falling rock from the surface of the earth) is changing at a non-constant rate. This is sometimes called "relative" acceleration. It is undefined unless a reference is specified. When the word is used this way, the same object may be accelerating with respect to one reference and not accelerating with respect to a different reference. This has nothing to do with the object's weight.
It is used to mean that the object not in free-fall. (More technically: it is used to mean that an object is not following a geodesic in spacetime.) This does not depend on any external reference. If an object is accelerating in this sense, then it has weight.

If we carelessly use the same word with both meanings, we end up with crazy-sounding statements, kind of like this famous example: "Feathers are always light (opposite of heavy) even though sometimes they're not light (opposite of dark)."
In summary:

If the earth is regarded as a single object in orbit (freely falling) around the sun, the earth is weightless. We can rightly say that it weighs zero pounds (or zero Newtons). Individual parts of the earth (like individual mountains) have weight because they are not in free-fall, and their weights are in different directions depending on where they are located on the earth. But overall, the earth is weightless, because it is in free-fall overall when regarded as a single object.
Mass is simpler. The earth's overall mass is just the sum of the masses of all of its parts.  Mass does not have a direction and does not depend on how the object is moving. The earth has a very, very large mass — lots and lots of kilograms.


Q:

Permutations of dictionary in python

I have a dictionary like this -
{'A': 0, 'B': 0, 'C': 0, 'D': 4}

I want to generate a list like this -
[{'A': 1, 'B': 0, 'C': 0, 'D': 4},
 {'A': 0, 'B': 1, 'C': 0, 'D': 4},
 {'A': 0, 'B': 0, 'C': 1, 'D': 4},
 {'A': 0, 'B': 0, 'C': 0, 'D': 5}]

What is the most pythonic way to do this?

A:

You can use list comprehension and dictionary comprehension together, like this
d = {'A': 0, 'B': 0, 'C': 0, 'D': 4}
print [{key1: d[key1] + (key1 == key) for key1 in d} for key in d]

Output
[{'A': 1, 'B': 0, 'C': 0, 'D': 4},
 {'A': 0, 'B': 0, 'C': 1, 'D': 4},
 {'A': 0, 'B': 1, 'C': 0, 'D': 4},
 {'A': 0, 'B': 0, 'C': 0, 'D': 5}]

The idea is to generate a new dictionary for each key, and when the key matches the key of the dictionary being constructed with dictionary comprehension, then add 1 to it. (key1 == key) will evaluate to 1 only when both the keys match, otherwise it will be zero.


Q:

Alternative representation for Perron Frobenius Eigenvalue

While explaining the application of Geometric programming to Minimizing Spectral radius Boyd says that $\lambda_{pf}$ can also be characterized as:
$\operatorname{inf}\{\lambda|\exists{v}>0, Av\leq\lambda{v}\}$
According to my understanding Perron Frobenius Eigenvalue is the Eigenvalue with largest absolute value. These two definitions seems conflicting to me.
Can someone explain?

A:

Presumably $A$ is (entrywise) positive or it is both irreducible and nonnegative. By Perron-Frobenius theorem, the spectral radius $\rho(A)$ is an eigenvalue of $A$ and there exists a positive left eigenvector $u$ corresponding to the eigenvalue $\rho(A)$. Now, if $Av\le\lambda v$ for some positive $v$, then $\rho(A)u^Tv=u^TAv\le\lambda u^Tv$, i.e. $\rho(A)\le\lambda$. Therefore $\rho(A)\le\inf\{\lambda\mid\exists v>0,\,Av\le\lambda v\}$. However, as $Av=\rho(A)v$ for the (right) Perron vector of $A$, the inequality is sharp.