text:
Q: Why are arguments specific for one subcommand being required for my entire command line program to run? I am building a command-line program using the argparse module, and have been trying to design two separate, mutually exclusive groups of arguments that perform completely different tasks. I decided to use separate the two sets of arguments by creating subparsers, and I have tried to follow the formatting that is specified in the following link (https://pymotw.com/2/argparse/) as well as numerous stackoverflow threads, but whenever I try to run the script with one of the subparsers in the terminal, an attribute error is always yielded.
My code is set up in the following way (note: I have slightly condensed and simplified the following from my original code for the purpose of brevity):
import argparse

def check_input_file(filename):
    ###validates input file
    return validated_file

if __name__ == "__main__":
    parser = argparse.ArgumentParser(prog= "MyProg")
    parser.description= "This gives an overview of the two different workflows A and B, what they can do, and what arguments they require or can use."

    A_or_B_subparsers = parser.add_subparsers(help="A processes a certain input to create a .csv spreadsheet, B takes an existing .csv spreadsheet and sends out a certain number to be printed")

    A_parser= A_or_B_subparsers.add_parser("A", help= "A needs the name of an existing input file to make the .csv spreadsheet")

    A_parser.add_argument("-input", required= True, type= check_input_file, help= "validates input file as being suitable for creating the .csv spreadsheet")

    B_parser = A_or_B_subparsers.add_parser("B", help="B will tell the computer to print a certain number of existing spreadsheets in a certain format")

    B_parser.add_argument("-num", type= int, default= 4, help= "number of times to do print existing .csv spreadsheet")

    B_parser.add_argument("-csv", help= "specify the existing .csv spreadsheet that must be formatted and then printed)

    args= MyProg.parse_args()

    if args.A:
        input= open(args.input, 'r')
        ###create .csv spreadsheet of input file in working directory

    if args.B:
        x_number= args.num
        file= args.csv
        ###format existing .csv spreadsheet
        ###print .csv spreadsheet file x_number of times

Now, if I try to run this code in the terminal with, for example, the following commands, I get the following error:
$python MyProg_user_interface.py A -input someinputfilename.txt
AttributeError: 'Namespace' object has no attribute 'B'

How can I run my command line program so that only one subparser (and its required arguments) can run at a time?
UPDATE
After having found this source (https://allthingstechilike.blogspot.co.uk/2013/07/python-argparse-example-using-subparser.html), I decided to set dest= 'mode' in the line where A_or_B_subparsers = parser.add_subparsers(help="A processes a certain input blah blah blah blah") so that, depending on whether subcommand A or B was called in the command line, only the arguments required each subcommand would have to be typed into the command line.
I subsequently then modified my conditional tree after the line args= MyProg.parse_args() to look like this:
if args.mode == "A":
    input= open(args.input, 'r')
    ###create .csv spreadsheet of input file in working directory
elif args.mode== "B":
    x_number= args.num
    file= args.csv
    ###format existing .csv spreadsheet
    ###print .csv spreadsheet file x_number of times
else:
    argparse.ArgumentError("too few arguments")

However, this modification does not seem to amend the problem. Although subcommand A can run fine, subcommand B refuses to run at all. Does anyone know if this is because of how my code is set up or because of another internal problem?


text:
Q: WORLDPAY Integration using php Can any one please let me know is WORLDPAY payment gateway provides API for php stuffs? did any of you integrates this stuff? please advise me....

A: You can find complete documentation here: RBS WorldPay Technical Guides
A simple payment submission would look like this:
<form action="https://secure.wp3.rbsworldpay.com/wcc/purchase" method=POST>
    <input type=hidden name="instId" value="yourid">
    <input type=hidden name="cartId" value="cartid">
    <input type=hidden name="amount" value="9.99">
    <input type=hidden name="currency" value="GBP">
    <input type=submit value="Buy Now">
</form>

A: The documentation and detailed way of implementing worldpay is redirection is explained in worldpay integration techniques  and xml way or the api way of integrating is described in worldpay xml integration
like
<paymentService version="1.4" merchantCode="WPACC11112222">
<submit>
    <order orderCode="T021101078">
          <description>20 Tulip Bulbs from MYMERCHANT Webshops</description>
          <amount value="2600" currencyCode="EUR" exponent="2"/>
          <paymentDetails>
              <VISA-SSL>
                  <cardNumber>4444333322221111</cardNumber>
                  <expiryDate>
                      <date month="09" year="2015"/>
                  </expiryDate>
                  <cardHolderName>Akhilraj</cardHolderName>
                  <cvc>123</cvc>
                  <cardAddress>
                      <address>
                           <street>47A Queensbridge Rd</street>
                           <postalCode>CB94BQ</postalCode>
                           <countryCode>GB</countryCode>
                      </address>
                  </cardAddress>
               </VISA-SSL>
               <session shopperIPAddress="'.$_SERVER['SERVER_ADDR'].'" id="0215ui8ib1" />
          </paymentDetails>
          <shopper>
              <shopperEmailAddress>dfgdf@gmail.com</shopperEmailAddress>
              <browser>
                   <acceptHeader>'.$_SERVER['HTTP_ACCEPT'].'</acceptHeader>
                   <userAgentHeader>'.$_SERVER['HTTP_USER_AGENT'].'</userAgentHeader>
               </browser>
           </shopper>
    </order>

';

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to center items in a div without losing height of parent? I have a container div with 2 spans inside it. When I try to align-items: center i lose the height and border-radius of the spans. I'd like them to retain   their heights and border radius, while just being centered. How can I do this?
CSS of parent div:
const Container = styled.div`
  display: inline-flex;
  overflow: hidden;
  border-radius: 4px;
  margin: 0px 8px 10px 8px;
  height: 70px;
`;

CSS of child span:
const TextContainer = styled.span`
  padding: 8px 11px;
`;

Before align-items: center:

After align-items: center:

A: You can add display: flex to span and align items.

.container {
  display: inline-flex;
  overflow: hidden;
  border-radius: 4px;
  margin: 0px 8px 10px 8px;
  height: 70px;
}

span {
  display: flex;
  padding: 8px 11px;
  background: #f00;
  align-items: center;
}

  Match Rank

A: This is actually due to inline-flex setting a vertical align of baseline.
Removing the align-items would change it to stretch but you probably don't want to do that.
SOLUTION1
What happens if you use align-items: flex-start
SOLUTION2
Or you could try setting the vert align to top, that may fix it.
const TextContainer = styled.span`
    vertical-align: top;
    padding: 8px 11px;
`;

Can you try those and let me know how it turns out ?   Thanks


text:
Q: Angular UI-Grid Header Cell Template How do I set header with text and custom style keeping the functionality of sorting and filtering as it is.
For example:
headerCellTemplate: '
Stone Id *
'

Here is my plunker: http://plnkr.co/edit/vy4DjRuoZ48Ced0KfWRV?p=preview
Thanks.

A: Here you can find the default template for ui-grid header: default header cell template
So the only thing you have to do is to change as you want. Here is a plunker with what you want to achieve: http://plnkr.co/edit/i9EFvGecvJJD9LKUBbwT?p=preview
$scope.gridOptions = {
    columnDefs: [{
      displayName: 'Name',
      field: 'name',
      headerCellFilter: 'translate',
      headerCellTemplate: 'customTemplate.html',
      enableSorting: true,

    }, {
      displayName: 'GENDER',
      field: 'gender',
      headerCellFilter: 'translate'
    }, {
      displayName: 'COMPANY',
      field: 'company',
      headerCellFilter: 'translate',
      enableFiltering: false
    }]
  };

Custom header cell template

      {{ col.displayName CUSTOM_FILTERS }}*

       {{col.sort.priority + 1}}


text:
Q: Asymmetric distribution, Gauss curve I want to create a positive and negative asymmetric distribution, as shown in the image, it will be possible to include the data (values) one by one to give the desired curve.
The WME is
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}

\begin{document}

\newcommand\gauss[2]{1/(#2*sqrt(2*pi))*exp(-((x-#1)^2)/(2*#2^2))}
\begin{tikzpicture}[
every pin edge/.style={latex-,line width=1.5pt},
every pin/.style={fill=yellow!50,rectangle,rounded corners=3pt,font=\small}]
\begin{axis}[every axis plot post/.append style={
    mark=none,domain=-3.:3.,samples=100},
    clip=false,
    axis y line=none,
    axis x line*=bottom,
    ymin=0,
    xtick=\empty,]
    \addplot[line width=1.5pt,blue] {\gauss{0.}{1.}};
    \node[pin=270:{$X=M_e=M_o$}] at (axis cs:0,0) {};
    \draw[line width=1.5pt,dashed, red] (axis description cs:0.5,0) -- (axis description cs:0.5,0.92);
    \end{axis}
\end{tikzpicture}

\end{document}

A: This is only a partial answer since it is not clear to me what an asymmetric Gauss curve precisely is. This is more to discuss how to set this up in principle. So I am only going to discuss how to plot a deformed Gauss curve.
To this end, I'd like to convince you to use declare function rather than the definition you use. In the example below, I am going to use
declare function={Gauss(\x,\y,\z,\u)=1/(\z*sqrt(2*pi))*exp(-((\x-\y+\u*(\x-\y)*sign(\x-\y))^2)/(2*\z^2));

Here Gauss reduces to an ordinary Gaussian for \u=0, where \x is just the variable, \y defines the location of the maximum and \z the width. If you turn on a nontrivial \u, the Gaussian will get deformed.
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{height=4cm,width=8cm,compat=1.16}
\begin{document}

\begin{tikzpicture}[font=\sffamily,
declare function={Gauss(\x,\y,\z,\u)=1/(\z*sqrt(2*pi))*exp(-((\x-\y+\u*(\x-\y)*sign(\x-\y))^2)/(2*\z^2));},
every pin edge/.style={latex-,line width=1.5pt},
every pin/.style={fill=yellow!50,rectangle,rounded corners=3pt,font=\small}]
\begin{axis}[
    every axis plot post/.append style={
    mark=none,samples=101},
    clip=false,
    axis y line=none,
    axis x line*=bottom,
    ymin=0,
    xtick=\empty,]
    \addplot[line width=1.5pt,blue,domain=-1:3] {Gauss(x,0,0.6,-0.4)};
    \draw[line width=1.5pt,dashed, black] (0,0) -- (0,{Gauss(0,0,0.6,-0.4)});
    %\node[pin=270:{$X=M_e=M_o$}] at (axis cs:0,0) {};
    \draw[line width=1.5pt,dashed, red] (0.6,0) -- (0.6,{Gauss(0.6,0,0.6,-0.4)});
    \draw[line width=1.5pt,dashed, red] (-0.6,0) -- (-0.6,{Gauss(-0.6,0,0.6,-0.4)});
    \path (-0.6,0) coordinate (ML) (0.6,0) coordinate (MR) (0,0) coordinate (MM);
\end{axis}
\draw[latex-] (ML) to[out=-90,in=45] ++ (-0.6,-0.6) node[below left,inner
sep=1pt]{$\langle X\rangle-\Delta$};
\draw[latex-] (MR) to[out=-90,in=135] ++ (0.6,-0.6) node[below right,inner
sep=1pt]{$\langle X\rangle+\Delta$};
\draw[latex-] (MM) --++ (0,-0.6) node[below,inner
sep=1pt]{$\langle X\rangle$};
\end{tikzpicture}
\end{document}

A: Probably slightly overkill and certainly not efficient, but you could try an  approximate skew normal (central tendencies are omitted below):
\documentclass[border=5, tikz]{standalone}
\usetikzlibrary{math}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\tikzmath{%
  function h1(\x, \lx) { return (9*\lx + 3*((\lx)^2) + ((\lx)^3)/3 + 9); };
  function h2(\x, \lx) { return (3*\lx - ((\lx)^3)/3 + 4); };
  function h3(\x, \lx) { return (9*\lx - 3*((\lx)^2) + ((\lx)^3)/3 + 7); };
  function skewnorm(\x, \l) {
    \x = (\l < 0) ? -\x : \x;
    \l = abs(\l);
    \e = exp(-(\x^2)/2);
    return (\l == 0) ? 1 / sqrt(2 * pi) * \e: (
      (\x < -3/\l) ? 0 : (
      (\x < -1/\l) ? \e / (8 * sqrt(2 * pi)) * h1(\x, \x*\l) : (
      (\x <  1/\l) ? \e / (4 * sqrt(2 * pi)) * h2(\x, \x*\l) : (
      (\x <  3/\l) ? \e / (8 * sqrt(2 * pi)) * h3(\x, \x*\l) : (
      sqrt(2/pi) * \e)))));
  };
}
\begin{document}
\begin{tikzpicture}[line join=round, line cap=round]
\begin{axis}[
    width=4in, height=2in,
    every axis plot post/.append style={
        mark=none, domain=-3.5:3.5, samples=200, very thick
    },
    clip=false,
    axis y line=none,
    axis x line*=bottom,
    ymin=0, ymax=0.75,
    xtick=\empty,]
\addplot[red]    {skewnorm(x, -4)};
\addplot[green]  {skewnorm(x, -2)};
\addplot[gray]   {skewnorm(x,  0)};
\addplot[blue]   {skewnorm(x,  2)};
\addplot[orange] {skewnorm(x,  4)};
\legend{$\lambda=-4$,$\lambda=-2$,$\lambda=0$,$\lambda=2$,$\lambda=4$}
\end{axis}
\end{tikzpicture}
\end{document}

A: Another possible way (apart from @marmot's answer) is to plot the skewed distribution function is to exploit the chi-square distribution.
For instance:
\documentclass{standalone}
\usepackage{pgfplots}
%https://en.wikipedia.org/wiki/Chi-squared_distribution
%https://tex.stackexchange.com/questions/120441/plot-the-probability-density-function-of-the-gamma-distribution?rq=1
% the second link gives the numerical approximation of gamma function
\begin{document}
\begin{tikzpicture}[
    declare function={gamma(\z)=
    (2.506628274631*sqrt(1/\z) + 0.20888568*(1/\z)^(1.5) + 0.00870357*(1/\z)^(2.5) - (174.2106599*(1/\z)^(3.5))/25920 - (715.6423511*(1/\z)^(4.5))/1244160)*exp((-ln(1/\z)-1)*\z);},
    declare function={chipdf(\x,\k) = \x^(\k/2-1)*exp(-\x/2) / (2^(\k/2)*gamma(\k));}
]

\begin{axis}[
    axis lines=left,
    enlargelimits=upper,
]
\addplot [smooth, domain=0:20, blue] {chipdf(x,2)};
\addplot [smooth, domain=0:20, green] {chipdf(x,3)};
\addplot [smooth, domain=0:20, black] {chipdf(x,4)};
\addplot [smooth, domain=0:20, cyan] {chipdf(x,5)};
\addplot [smooth, domain=0:20, magenta] {chipdf(x,6)};
\end{axis}
\end{tikzpicture}
\end{document}

which will give you:

Using this, you can include your mean-median-mode as lines in the plot.


text:
Q: Autohotkey Control + Capslock issue I am using Autohotkey to make it so that you have to hit Shift + CapsLock in order to activate capslock. Then just pressing capslock gets you out of capslock. I love this script, however, when I switch tabs in chrome using Control + Tab, I sometimes end up hitting Contorl + Capslock, which activates capslock. Here is my code:
; Only allow capslock if it's shift-capslock
$SC03a::
GetKeyState,caps,CapsLock,T

if caps = D
    SetCapsLockState,Off
return

I don't know how to get around this. Any ideas?

A: Only allow capslock if it's shift-capslock:
   CapsLock::SetCapslockState AlwaysOFF
   +CapsLock::SetCapslockState AlwaysON


text:
Q: Upload failed when new APK file to Android Play store Error I already published my application in Play store, Again i want to Upload new version apk, its getting Problem.
i want to delete previous version apk or i want replace with new APK.
Problem :
1.After 99% Loading its Showing error message as,
Upload new APK to Production
Upload failed
You uploaded an APK that is signed with a different certificate to your previous APKs. You must use the same certificate. Your existing APKs are signed with the certificate(s) with fingerprint(s):
[ SHA1: 5B:68:A1:1E:89:F5:CD:B2:t1:6H:85:D1:8C:FD:01:]
and the certificate(s) used to sign the APK you uploaded have fingerprint(s):
[ SHA1: DB:BD:FE:53:2C:AA:JB:12:7L:BE:D6:6B:80:D6:E5: ]
Please any one help me to solve this problem.
else i want to delete previous version apk and i want replace with new APK

A: when upload app on Google play we need signed APK file. check this at that time we have to use on key store file.
so, once upload signed APK on Google play with key store. we must have to use that same keystore file whenever generate signed apk, after that Google play accept new APK file.
so, your already uploaded APK file and new APK both are generated using different key store file. use same key store for new apk.
in case you lost key store file then you are not able to upload new APK on Google play, in that case you have  to remove application from there and again upload app with different package name.
check my previous answer on this

Edit:

My Old Apk Keystore was Wrong, So only solution Need to change the package name in New APK. then UnPublish the Old APK?
you must have to delete application on Google play not just apk. then add new application on google play, change package name of your app, generate new signed apk, upload on google play(this time just save key store file at safe place for future uses)
Using that Keystore File can we generate SIgned Apk from any Other machine ?

*

*yes, you can use that key store file on different machine. just choose that key store file whenever generate new APK.


text:
Q: Disable Facebook Like/Comment functionality for app Facebook posts
Possible Duplicate:
Disabling comments or likes on a specific post made via the Facebook API

I'm creating an app which posts to Facebook through both actions and wall posts, and I would like to be able to disable the ability for Facebook users to like/comment on the posts. I see that "can_like" and "can_comment" fields exist if I query user actions, and by default are both set to true; is there a way to set them to false when posting?


text:
Q: Anyway to read a .plist from a firefox add-on? Is there a pre-existing XPCOM guy that will let me interrogate a .plist file from Javascript, or do I need to use nsIFile and parse the XML myself?
(For background, there is a version number in a directory structure I don't control that I need to read from a .plist in order to be future-proof.)

A: I don't know what a .plist is but I gather it's some sort of XML.
If you're parsing XML, don't use nsIFile directly, use this: Parsing and serializing XML. You might also like to use E4X.


text:
Q: Url query string in fetch api in javascript How to pass query string with fetch api javascript (https://github.com/github/fetch)?
var url = "http://www.abcd.com";
var query = {
    a: "test",
    b: 2
};

Above should be converted to http://www.abcd.com?a=test&b=2 when I pass some argument to fetch

A: var params = Object.keys(query)
                   .map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(query[key]))
                   .join("&")
                   .replace(/%20/g, "+");

fetch(url + "?" + params);

Or with the options object - but this will NOT work with GET and HEAD method:
fetch(url, {
    method: "POST",
    body: convertObjectToFormData(query)
}).then(...);

function convertObjectToFormData(obj) {
    var formData = new FormData();
    for (var key in obj) {
        formData.append(key, obj[key]);
    }
    return formData;
}


text:
Q: Why npm fails to install jqueryui package? I'm trying to install jqueryui and its typescript from npm. While jquery packages have been successfully installed, both packages for jqueryui has failed. Please note that I'm able to browse jqueryui packages if I visit site, npmjs.com
Debug data:
npm -v
3.10.10
Packages location:
https://www.npmjs.com/package/jqueryui
https://www.npmjs.com/package/@types/jqueryui
Comamnds:
npm install --save jqueryui
npm install --save @types/jqueryui
Error

*

*jqueryui' is not in the npm registry.

*@types/jqueryui' is not in the npm registry.

A: I just tried this and it works:
$ npm install --save jqueryui
npm-t1@1.0.0 /home/rsp/node/test/npm-t1
└── jqueryui@1.11.1

npm WARN npm-t1@1.0.0 No description
npm WARN npm-t1@1.0.0 No repository field.

$ npm install --save @types/jqueryui
npm-t1@1.0.0 /home/rsp/node/test/npm-t1
└─┬ @types/jqueryui@1.11.32
  └── @types/jquery@2.0.40

npm WARN npm-t1@1.0.0 No description
npm WARN npm-t1@1.0.0 No repository field.

(those warnings are because I don't have certain fields in the package.json of a test project that I just created.)
It seems that you may be using some other registry than the public one.
See:

*

*https://docs.npmjs.com/misc/registry

*https://docs.npmjs.com/cli/config

*https://docs.npmjs.com/misc/config


text:
Q: Replace a button that loads a prompt by its result I have a text. Inside, I want to ask the reader questions where answers will be inserted inside the text. And I want the questions to be prompted by a button and have the button disappear when the prompt is validated.
So what I have for now is this:
Once upon a time in <button onclick="prompt('Where do you live?')">Where do you live?</button>, a very beautiful place…

It gets me the button inside my text, the prompt I want, but how do I get the result of this prompt to replace the button when I close the prompt after clicking OK?

A: This onclick() does what I think you want.

Once upon a time in <button onclick="this.outerText = prompt('Where do you live?');">Where do you live?</button>, a very beautiful place…

Basically, it sets the value of the prompt to the outerText of the button.  outerText replaces the entire button, while innerText would place it inside the button, if you want that instead.  It would look like this:

Once upon a time in <button onclick="this.innerText = prompt('Where do you live?');">Where do you live?</button>, a very beautiful place…


text:
Q: Cakephp: add minutes to datetime object I am new to cakephp and i wish to do the following:
I have a dateTime object and i want to add and subtract 30 minutes to it.
Following is my code in controller :
$time = $this->request->data['Rideoffer']['DepartureTime'];
                    $date = new DateTime($time['hour'] . ':' . $time['min'] . ' ' . $time['meridian']);

                        $currentDate = strtotime($date['date']); // this line gives error
                        $futureDate = $currentDate+(60*30);
                        $formatDate = date("Y-m-d H:i", $futureDate);

when i debug $date i get the following result:
 object(DateTime) {
 date => '2013-03-08 05:54:00'
 timezone_type => (int) 3
 timezone => 'UTC'
}

i wish to extract date from this object. How do i do so?

A: solved it:
 $currentDate = strtotime($date->format('Y-m-d H:i:s'));

but i still dont get it that why cant i use $date['date'], i mean $date like an array.


text:
Q: Python list comparison to create trees I have data in the following format:
Group  Item-1  Item-2
0       7       13
0      10        4
1       2        8
1       3        1
1       4        3
1       6       28
1       8        6
...

I need Python 2.7 to output growing chains/trees/connections between Item-1 and Item-2 for each group.  So for Group 0 other than 7-13 and 10-4, there are no chains/connections, but for Group 1 the output would be something like:
1  (2, 8, 6, 28), (4, 3, 1)

A: This seems to be a case for the union-find, or disjoint-set algorithm. Here's an implementation I use to keep in my toolbox:
from collections import defaultdict

class UnionFind:
    def __init__(self):
        self.leaders = defaultdict(lambda: None)

    def find(self, x):
        l = self.leaders[x]
        if l is not None:
            l = self.find(l)
            self.leaders[x] = l
            return l
        return x

    def union(self, x, y):
        lx, ly = self.find(x), self.find(y)
        if lx != ly:
            self.leaders[lx] = ly

    def get_groups(self):
        groups = defaultdict(set)
        for x in self.leaders:
            groups[self.find(x)].add(x)
        return groups

And here how to apply it to your data:
# parse data
data = """Group  Item-1  Item-2
0       7       13
0      10        4
1       2        8
1       3        1
1       4        3
1       6       28
1       8        6"""
data = [[int(x) for x in line.split()] for line in data.splitlines()[1:]]

# get mapping {group_number: [list of pairs]}
groups = defaultdict(list)
for g, x, y in data:
    groups[g].append((x, y))

# for each group, add pairs to union find structure and get groups
for group, links in groups.items():
    union = UnionFind()
    for x, y in links:
        union.union(x, y)
    print group, union.get_groups().values()

Output is:
0 [set([10, 4]), set([13, 7])]
1 [set([1, 3, 4]), set([8, 2, 28, 6])]


text:
Q: Turn off encrypted backup on iPhone that has a profile without removing profiles I have iPhones that have profiles on them that were password protected profiles and those passwords have been lost.  So we need to wipe the iphones and was hoping to to a backup first and then restore without the profiles on there.  Problem is, it won't let me do a backup without encrypting first.  I have read that in order to not encrypt the backup you need to remove the profiles, but in this case we can't remove the profiles.
Is there any way to turn this encryption off??

A: When you have a profile that enforces encryption of backups, you really only have three options:

*

*Live with the encrypted backups and do nothing.

*Get someone to remove the profile (or wipe the device along with the profile and start over being careful to not allow profiles that force you into encrypted backups).

*Somehow exploit a bug or flaw in the security of iOS and bypass this lock. I would expect you to pay big money or have some assistance from NSA-like organization to accomplish this last item unless someone publishes a weakness in iOS that we could take advantage of to bypass the security your iPhone has configured.

As it stands, you will likely have to remove the profile to bypass the restriction that iOS has on not doing a backup in the manner you wish.

A: You can't access your old encrypted iPhone backups if you can't remember the password. However, iTunes can create a new backup of the iPhone without encrypting the backup, see here for details.
http://support.apple.com/kb/ht4946
Alternatively, you could use a 3rd party app to backup your iPhone without iTunes.

A: I had a similar issue and found an installed (provisioning) profile is not letting non-encrypted backups to be made, see my write-up here: https://wiitez.blogspot.sg/2016/12/how-to-disable-iphone-requiring-backup.html

A: There is software that basically spends all day guessing it. I had to do this once when I remembered most of the password but forgot exactly it (forget which one I used). You can put in perimeters o speed things up like 12 characters no numbers no special characters. And when it guesses it you pay for the program and can unhindered the password.


text:
Q: Careless Mailing Clerk Problem/Puzzle So, it goes like this:
After a typist has written ten letters and had addressed the ten corresponding envelopes, a careless mailing clerk inserted the letters in the envelopes at random, one letter per envelope. What is the probability that exactly nine letters were inserted in the proper envelopes?
The correct answer is supposed to be that the probability of "exactly nine letters were inserted/mailed correctly" is zero (0)?
I'm not sure how to get at this conclusion mathematically... probability was never my forte.
Intuitively, the Pr(exactly nine letters were mailed correctly) = 0 because "If nine letters are in the correct envelopes, the tenth must/will be also, so the probability is zero."
But does that mean that the probability distribution for this is discontinuous?
(Apparently this is an old problem from the "Mathematical Quickies" by C. W. Trigg, I don't have the book but found out online)

A: If there are exactly nine matches, then it means the remaining one is not-matched, but this is impossible. Thus, the required probability is 0.


text:
Q: Why don't databases create their own indexes automatically? I would have thought that databases would know enough about what they encounter often and be able to respond to the demands they're placed under that they could decide to add indexes to highly requested data.

A: They can analyse past queries and suggest/create indexes however this doesn't work optimally because indexes strike a balance to speed up what you want optimised at a cost and the server can not know your intentions.

A: Update
This is now implemented in SQL Server Azure. It generates recommendations

and index management can be configured to be automatic.

Enable automatic index management
You can set the SQL Database Advisor to implement recommendations
  automatically. As recommendations become available they will
  automatically be applied. As with all index operations managed by the
  service if the performance impact is negative the recommendation will
  be reverted.

Original Answer
Some databases do already (kind of) create indexes automatically.
In SQL Server the execution plan can sometimes include an Index Spool operator where the RDBMS dynamically creates an indexed copy of the data. However this spool is not a persistent part of the database kept in synch with the source data and it cannot be shared between query executions, meaning execution of such plans may end up repeatedly creating and dropping temporary indexes on the same data.
Perhaps in the future RDBMSs will have the capacity to dynamically drop and create persistent indexes according to workload.
The process of index optimisation is in the end just a cost benefit analysis. Whilst it is true that humans may have more information about relative importance of queries in a workload in principle there is no reason why this information could not be made available to the optimiser. SQL Server already has a resource governor that allows sessions to be classified into different workload groups with different resource allocations according to priority.
The missing index DMVs mentioned by Kenneth are not intended to be implemented blindly as they only consider the benefits to a specific query and make no attempt to take account of the cost of the potential index to other queries. Nor does it consolidate similar missing indexes. e.g. the output of this DMV may report missing indexes on A,B,C and A,B INCLUDE(C)
Some current issues with the idea are

*

*The quality of any automated analysis that does not actually create the index will be highly dependant upon the accuracy of the costing model.

*Even within the field of automated analysis an offline solution will be able to be more thorough than an online solution as it is imperative that an online solution should not add large book keeping overhead to the live server and interfere with its primary purpose of executing queries.

*The indexes created automatically in response to workload will necessarily be created in response to  queries that would have found them useful so will lag behind solutions that create the indexes in advance.

It is probably reasonable to expect the accuracy of costing models to improve over time but point 2 looks trickier to solve and point 3 is inherently insoluble.
Nevertheless probably the vast majority of installs are not in this idealised situation with skilled staff who continuously monitor, diagnose, and anticipate (or at least react to)  changes in workloads.
The AutoAdmin project at Microsoft Research has been running since 1996

The goal of this project is to make databases self-tuning and
  self-administering by exploiting knowledge of the workload

The project home page lists several intriguing projects. One is particularly relevant to the question here

Another interesting problem arises when there is no DBA available
  (e.g. an embedded database or a small business). In such scenarios, a
  low touch continuous index tuning approach may become important. We
  have explored solutions ...[in]  "An Online Approach to Physical Design Tuning" in ICDE
  2007.

The authors state

With increasingly common DBMS features like online indexes , it is
  appealing to explore more automatic solutions to the physical design
  problem that advance the state of the art.

The paper introduces an algorithm

Its main characteristics are:

*

*As queries are optimized, we identify a relevant set of candidate indexes that would improve performance. This feature allows query
  processing to continue in parallel with indexes that are built in the
  background.

*At execution time, we track the potential benefits that we
  lose by not having such candidate indexes and also the utility of
  existing indexes in the presence of queries, updates, and space
  constraints.

*After we gather enough "evidence" that a physical design change is beneficial, we automatically trigger index creations or deletions.

*The online nature of our problem implies that we will generally lag behind optimal solutions that know the future. However, by carefully
  measuring evidence, we ensure that we do not suffer from "late"
  decisions significantly, thus bounding the amount of incurred loss

The implementation of the algorithm allows for throttling in response to changes in server load and also can abort index creation if during creation the workload changes and expected benefit falls below the point that it is deemed worthwhile.
The conclusion of the authors on the topic of Online versus traditional physical tuning.

The online algorithms in
  this work are useful when DBAs are uncertain about the future behavior
  of the workload, or have no possibility of doing a comprehensive
  analysis or modelling. If a DBA has full information about the
  workload characteristics, then a static analysis and deployment by
  existing tools (e.g., [2, 3]) would be a better alternative.

The conclusions here are similar to those in another paper Autonomous Query-driven Index Tuning

Our approach cannot beat the index advisor if the whole workload is
  known in advance. However, in dynamic environments with evolving and
  changing workloads the query-driven approach produces better results.

A: The index design that you put in place is something more of an art than a science.  The RDBMS isn't smart enough to take common workloads and design a smart indexing strategy.  It is up to human intervention (read: DBA) to analyze workload and determine what is the best approach.
If there was no penalty of having indexes then it would be a shotgun approach to just add an infinite number of indexes.  But because data modification (INSERTS, UPDATES, and DELETES) have impact on the enabled indexes on a table then there is going to be that variable overhead of these indexes.
It takes human design and strategy to smartly create indexes that'll maximize read performance, while having the least amount of data modification overhead.

A: In fact, there are some databases that do this.  For example, Google's BigTable and Amazon's SimpleDB automatically create indices (though neither are RDBMS's).  There is also at least one MySQL RDBMS engine that does this.  SQL Server also keeps track of indices it thinks you should create, though it doesn't go so far as actually creating them.
The problem is surprisingly difficult to get correct, so it's no wonder that most databases don't automatically create them (BigTable/SimpleDB get away with it because they don't allow arbitrary joins, which makes things significantly easier).  Also, creating indices on the fly is a time-consuming process that requires exclusive access to the entire table - definitely not something you want happening while the table is on-line.
However, given the number of LAMP web applications out there that were written by amateurs who don't even know what an index is, I still think this feature would be beneficial for some people.

A: While there are some extensive answers already, they seem to skirt around the real answer: Indexes aren't always desirable.
With the car analogy mentioned in comments, you'd be better of saying why aren't all cars fitted with extreme sports packages? Partly it's expense, but it's also down to the fact that a lot of people don't need or want low profile tires and rock hard suspension; it's unnecessarily uncomfortable.
So maybe you have 1,000 reads for every insert, why not have an auto created index? If the table is wide and the queries are varied, why not have several? Maybe the commit is time critical and the reads aren't; in the circumstances it might be unacceptable to slow down your insert. Maybe you're working with limited disk space and you can't afford to have additional indexes eating into the space you've got.
The point is, indexes aren't automatically created because they aren't the answer to everything. Designing indexes isn't simply a case of saying "hey this will speed up my reads", there are other factors to consider.

A: They are not smart, they are a piece of code.
Every time you input new data to a database, it needs to find a new location to it and a map to find it when it is requested.
Indexing sounds easier than it is, you just give a new number to a new chunk of data?
Well, how about if the next query is not about the last chunk of data but about 36271 chuncks earlier? You can easily find it with your index, right? But what if the query includes a word like "fishing" to be found in the old 36271 chunk made in 1997? Ho? Not a word about fishing in the old article.
If data came to the database one by one, it could be indexed like that.
But simple indexing will have you wrong results and/or slow performance sooner or later...


text:
Q: Can I return the raw XML from SOAP::Lite without turning on debug? Debug is a nice feature, but what I'd like is to be able to return the "readable" raw xml from either the request or the response with a method. This way I can print them out in a note in my test framework. Can anyone tell me how I might do this?

A: Is the outputxml flag what you're after?

From the documentation:

outputxml()

Lets you specify the kind of output from all method calls. If true,
  all methods will return unprocessed, raw XML code. You can parse it
  with XML::Parser, SOAP::Deserializer or any other appropriate module.

A: A little late (hah!), but I was looking for the same and in the version of the library we're using I was able to do the following:
my $soap = SOAP::Lite->new()
    # ->uri(...)->proxy(...)->autotype(0)
    ;
my $header = SOAP::Header->name(...);
my $som = $soap->call('method' => $args, $header);
my $serializer = SOAP::Serializer->new;
my $xml = $serializer->serialize($som->dataof('//')); # includes a lot of attributes...
# or
my $xml = $serializer->serialize($som->valueof('//'));

This is not exactly the same, but might be complete enough for most uses.


text:
Q: command line argument in bash gives an error I want to write a bash script and one of the command line arguments is a string like A:
sh bash.sh file.in A

The script contains:
format=$2

if [$format = "A"]; then
    ...
else
    ...
fi

As a result I get this error:
bash.sh: line 20: [A: command not found

A: Try this:
#!/bin/bash

format="$2"

if [ "$format" = "A" ];then
   echo "Equal";
else
   echo "Not equal";
fi

(OR)
if [[ $format = "A" ]];then
    ...
else
    ...
fi

A: POSIX shell syntax requires a space between the [ ] brackets and the expression.
Try this:
if [ "$format" = "A" ]; then

...

else

...

fi

Also, if portability isn't a concern, you can use the more robust
[[ "$format" == "A" ]]

Additional info: Is [[ ]] preferable over [ ] in bash scripts?


text:
Q: Stacked bar-chart reversed I did stacked bar chart in d3 with your help in previous posts.. but now I have a problem. when I add another X point (like vanished user 44 in thie photo), it's still count the days from the last user. and I need to initialize this variable to 0 somewhere

this is the code:

var margin = {top: 80, right: 90, bottom: 30, left: 90},
    width = 1000 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var formatPercent = d3.format(".0%");
//יצירת X
//יאכלס את סוגי הרכב השונים
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
//יצירת ציר y
//יציג בר עבור מחיר הרכב המוצע לדילרים
var y = d3.scale.linear()
.range([height, 0]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

//יצירת ציר הY
//והצמדתו לצד שמאל
var yAxis = d3.svg.axis()
.scale(y)
.orient("left").ticks(4)

var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
  return "" + d.Current_Job + "
 " + d.TimeInRole + "";
})

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.call(tip);
//קליטת הטבלה והגדרת הטווחים על הצירים
d3.csv("Targil2.csv", type, function(error, data) {
  window.dataSet = data;
  x.domain(data.map(function (d) { return d.User_ID; }));
  y.domain([0, d3.max(data, function (d) { return d.TimeInRole * 5; })]);

  var stack = d3.layout.stack()
  .x(function (d) { return d.User_ID }) // tell d3 to use Type as x value
  .y(function (d) { return d.TimeInRole }); // tell d3 to use Sum as y value

  //הוספה של 2 הצירים
  svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

  svg.append("g")
  .attr("class", "y axis axisLeft")
  .attr("transform", "translate(0,0)")
  .call(yAxis)
  .append("text")
  .attr("y", 6)
  .attr("dy", "-2em")
  .style("text-anchor", "end")
  .style("text-anchor", "end")
  .text("Days");

  var stackSoFar = 0;

  //הוספת בר הנתונים
  svg.selectAll(".bar")
  .data(data)
  .enter().append("rect")
  .attr("x", function (d) { return x(d.User_ID); })
  .attr("width", x.rangeBand())
  .attr("y", function(d){
    d3.select(this)
    .attr("height", function(d2){
      var thisHeight = height - y(d.TimeInRole);
      stackSoFar += thisHeight
      return thisHeight
    });
    return (height - stackSoFar)
  })
  .style("fill", function(d){
    if (d.Current_Job == "Registered Users") { return "#1F77B4"; }
    if (d.Current_Job == "Super Users") { return "#AEC7E8"; }
    else return "#FF7F0E";
  })

  .on('mouseover', tip.show)
  .on('mouseout', tip.hide)

});

function type(d) {
  d.TimeInRole = +d.TimeInRole;

  return d;
}
body {
  font: 10px sans-serif;
  margin:auto;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.bar1 {
  fill: #00FF66;

}

.bar1:hover {
  fill: black ;
}

.x.axis path {
  display: none;
}

.d3-tip {
  line-height: 1;
  font-weight: bold;
  padding: 12px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  border-radius: 2px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  font-size: 10px;
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.8);
  content: "\25BC";
  position: absolute;
  text-align: center;
}

/* Style northward tooltips differently */
.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;
}

where should I reset the 'stackSoFar' variable?
this is example for the csv file:
2864,Vanished user 03,03/09/2010 18:22,Registered Users,460
2865,Vanished user 03,31/05/2009 19:31,Executives,22
2866,Vanished user 03,22/06/2009 18:02,Super Users,358
2867,Vanished user 03,15/06/2010 19:20,Super Users,83
2868,Vanished user 03,06/09/2010 18:09,Registered Users,653
2869,Vanished user 03,20/06/2012 08:02,Registered Users,733
28628,Vanished user 44,06/09/2010 18:09,Registered Users,653
28269,Vanished user 44,20/06/2012 08:02,Super Users,733

A: I think your problem comes from the fact that you are adding the height to the position to any of the rectangle you draw, while there are two separate bars :
var stack1SoFar = 0;
var stack2SoFar = 0;

svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("x", function (d) { return x(d.User_ID); })
      .attr("width", x.rangeBand())
      .attr("y", function(d){
        d3.select(this)
          .attr("height", function(d2){
              var thisHeight = height - y(d.TimeInRole);

            if (d.User_ID == Rdsmith4) {
                stack1SoFar += thisHeight;
            } else {
                stack2SoFar += thisHeight;
            }
            return thisHeight
          });
        if (d.User_ID == Rdsmith4) {
            return (height - stack1SoFar);
        } else {
            return (height - stack2SoFar);
        }
      })
      .style("fill", function(d){
          if (d.Current_Job == "Registered Users") { return "#1F77B4"; }
          if (d.Current_Job == "Super Users") { return "#AEC7E8"; }
          else return "#FF7F0E";
      })

If there is more than two bars, I think you should create an array of object (in a loop) looking like :
[{
    user_id: "Rdsmith4",
    stackSofar: 0,
}, {
    user_id: "Vanished",
    stackSofar: 0,
}]

Let me know if it works ! =)


text:
Q: a question on weyl group and its action on $\mathfrak{t}$ $\mathfrak{g}$ is a complex semisimple lie algebra which is a subalgebra of some $\mathfrak{g}l(n,\mathbb{C})$, we have chosen a compact real form $\mathfrak{l}$ of $\mathfrak{g}$ and let $K$ be the compact subgroup of $GL(n,\mathbb{C})$ whose lie algebra is $\mathfrak{l}$, we have chosen a maximal commutative subalgebra $\mathfrak{t}$ of $\mathfrak{l}$ and we work with associated cartan subalgebra $\mathfrak{h}=\mathfrak{t}+i\mathfrak{t}$, we have chosen inner product on $\mathfrak{g}$ that is invariant under the adjoint action of $K$ and that takes real values on $\mathfrak{l}$, Consider the subgroups: $$Z(\mathfrak{t})=\{A\in K: Ad_A(H)=H,\forall H\in \mathfrak{t}\}$$ $$N(\mathfrak{t})=\{Ad_A(H)\in \mathfrak{t},\forall H\in\mathfrak{t}\}$$
Define Weyl group, $W=N(\mathfrak{t})/Z(\mathfrak{t})$, I do not understand the action of weyl group on $\mathfrak{t}$ here is that:
 We can define an action of $W$on $\mathfrak{t}$ as follows . For each element $w\in W$ choose an element $A$ corresponding to equivalence class in $N(\mathfrak{t})$. Then for $H\in\mathfrak{t}$ we define the action $w.H$ of $w$ on $H$ by $w.H=Ad_A(H)$. could any one help me what is going on here possibly by an example?


text:
Q: How to simply read response from POST request via HttpClient? In my Service class I have variable a called token and I want to assign a value to it when a function is called. Let's suppose there is a method called login and it should only return the response from the containing post request:
login(email: string, password: string): Observable<Response> {
    return this.httpClient.post(url, {email: email, password: password})
          .pipe(
            catchError(error => of(error))
          );
}

The function could look something like that. Within it I now try to assign the value from the Response to this.token.
How I could solve this problem?

A: login(email: string, password: string): Observable<Response> {
    return this.httpClient.post(url, {email: email, password: password}).subscribe(data => {
        this.token = data.token;
    }, err => {
        console.log(err);
        return false;
    )
}

A: You can get the response and set this.token using this code:
/*
Your user model can be like this:
interface User {
  token: string;
}
*/
this.httpClient.post(url, {email: email, password: password}).pipe(
      tap(async (userInfo: User) => {
        // login successful if there's a jwt token in the response
        if (userInfo) {
          this.token = userInfo.token;
        }
        return userInfo;
      })
    );

You can also specify the type of model which are expecting as response like this:
this.httpClient.post<User>(url, {email: email, password: password})

Here how you can use it in your code:
login(email: string, password: string): Observable<Response> {
    return this.httpClient.post(url, {email: email, password: password}).pipe(
      tap(async (response: Response) => {
        // login successful if there's a jwt token in the response
        if (response) {
          this.token = response.token;
        }
        return response;
      })
    );
}

A: The easiest way in my opinion is to use RXJS, make everything simpler.
httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

private loginService(url, data) {
        try {
          return this._http.post(
            Url,
            data,
            this.httpOptions
          );
        } catch (e) {
          console.log(e);
        }
      }

The httpClient already returns an observable so no need to declare it.
Then you just subscribe to it:
    this.loginService(url, {email: email, password: password}).subscribe(
          (data) => {
            console.log('Login info');
          },
          (error) => console.log(error),
          () => {
            console.log('Complete);
          },
        );


text:
Q: Using 22pF load caps with 16MHz crystal on atmega328p fails to work I'm having a hard time figuring out why after attaching 22pF load caps to a 16 Mhz crystal on atmega328p my whole project (aka flashing leds) does not work. Once i remove the load caps everything works correctly (the leds flash faster ~), and avrdude detects the atmega. I'm using avrdude -P usb -c usbtiny -p m328p -U lfuse:w:0xE6:m to enable the crystal.
I'm following the atmega spec documentation (section 8.3).

A: Crystals are rated to drive some expected amount of capacitive load.  Your wiring and the internals of the microcontroller will also add their own load.  That, plus the load caps you add, need to be in the right range for the crystal, otherwise the oscillator won't start properly.
You could try smaller caps.  If you're in a breadboard, the breadboard itself will already add a bit of capacitance.

A: Check the quality of the caps. From what I've read, ceramic caps come in all sorts of flavors and qualities, and you should get caps that are designed for use with crystals.


text:
Q: Need guidance on setting up variables and arrays properly in my assembly source code file I'm told that there is "Absolute Assembly" and "Relocatable Assembler" choices when setting up my assembly code project in CodeWarrior. I'm not using the HCS12 microcontroller at the moment as I am just trying to get my code to assemble and step through correctly. I have chosen "Relocatable" because I believe it makes my code more readable and breaks it down into sections. However, I am having a hard time understanding how I need to set up variables and arrays properly.
I know that a variable has an address in RAM. Therefore I would think I would need to define this address. I'm also told that I need to define how big the variable is in other words if it is 1-byte or 2-bytes and so on.
I'm thinking the same applies to arrays. So I need to define location and size. I also need to fill up my array with values.
When I assemble the below code it tells me that there is no memory at the location I set for R1 and R2. I don't follow because I did up at the beginning of my programming using the EQU directive.
I don't understand when I'm suppose to use DC. or DS. and how that is different from using the EQU. It seems all the same and now i'm just confused in general on how to set up variables and arrays.
    ;************************PROGRAM HEADER******************
;   PROJECT NAME:
;   FILE NAME:
;   DEVELOPER:
;   DATE CREATED:
;   PROGRAM PURPOSE:
;   REVISIONS:
;********************************************************

;************************GLOBAL SYMBOLS******************
;   External Symbol Definitions
;   Internal Symbol Definitions
              XDEF      Entry, main
;********************************************************

;************************EQUATES (EQU)*******************
R1            EQU           $1000
R2            EQU           $1100
;********************************************************

;************************CODE SECTION********************
;   Section Start
MyCode:     SECTION
Entry:
main:
;   Initialize Stack Pointer
                LDS         #$2000
;   Initialize all I/O Devices
;   Initialize Variable Data
                    CLRA
                    CLRB
                LDAA        #4
                STAA        R1
                STAB        R2
                LDX         #List1
;   Start of Main Code
back                LDAA        R2        ;This is suppose to add up each
                ADDB        0, X      ;element in my array "List1". If
                INX                           ;there is a carry it branches out
                BCS         CARRY     ;to the carry loop, performs the
                LDAA                R1        ;carry operation and returns to
                DECA                          ;original start of first loop. My
                STAA                R1        ;variable R1 is the counter which
                BNE         back      ;is the size of my array "List1".

CARRY                   INCA
                STAA        R2
                LDAA        R1
                DECA
                STAA        R1
                BNE         back

                LDAA        R2
;************************END OF CODE*********************

;************************SUBROUTINES & FUNCTIONS*********
;********************************************************

;************************CONSTANT DATA SECTION (ROM)*****
;   Section Start
;   Data Definitions
;********************************************************

;************************VARIABLE DATA SECTION (RAM)*****
;   Section Start
MyData:     SECTION
;   Variable Data Storage Allocation
List1:      DC.B     $FF, $01, $FE, $02
;********************************************************

A: I'm not famailiar with the assembler you are using, but EQU simply assigns a value to a symbol. In your assembler, DC or DS would appear to define storage, where the label is defined as the start of the storage area.
DC.B would appear to assign bytes, so if you want R1 to be defined as a memory location containing the value $1000 I'd anticipate that
R1:  DC.W $1000
R2:  DC.W $1100

entered after List1: should logically reserve a WORD or storage containing the values nominated.
Naturally, yo'd need to delete your EQU definition, else the assembler will object to the double-definition.


text:
Q: Determining the optimal amount of unit tests? I think I may be writing -too- many unit tests.
For example, say I was doing a coursework management system, and I coded a feature for submitting coursework on behalf of a student. If invalid credentials are specified in the API call, a 401 forbidden is returned. If a student tries to submit a different student's coursework, a different error is returned. If a student sends in his own coursework, its accepted but in a 'pending' status, awaiting approval from staff. If a faculty member sends in coursework on behalf of a student, its automatically accepted and also put in 'approved' status automatically.
As you can see, there are about 4-5 different scenarios here, each with a different outcome.
I tend to write tests for each scenario. That means, it might take me 10-15 mins to code the feature, but then another 15 mins - an hour, to write and pass all the unit tests. May be even 2 hours.
Obviously this is making me slow, and I'm expected to deliver results much faster. But unless I write all those tests, it feels 'wrong', and that the code may not work as expected.
What's the solution here? What's the right amount of unit tests to write? For every 1 hour of coding, how much time, max, should be spent writing tests for that feature?

A: Every one of those outcomes that you described are valid testing scenarios.  The way you know that is that each behavior is tied to a different outcome.  That makes each one a prime candidate for testing.
From a Cyclomatic Complexity point of view, the fact that there are different outcomes for each test corresponding to different program states almost certainly means that your testing different paths through the code, which improves your testing code coverage.
If you were just repeatedly testing the same behavior over and over and asserting the same result, then I might be worried that you're writing too many tests.  But not if each test is testing a specific behavior and result.

A: "Hammer in a nail - if the wood splits you should have used a screw"
How do you know if you're not writing enough tests? If bugs appear further upstream that could have been caught at the unit test phase then you haven't written enough tests.
But this aside, I sense you're equally interested in the expended effort as heading off possible bugs. If you find yourself writing code to cover off ranges of parameters or combinations of the same, then frameworks such as NUnit can take a lot of the donkey work away. If however they're bona fide business cases then you just have to bite the bullet and code as many as you need. There is no rule of thumb for this really - some code can be extremely quick to write but difficult to test and vice versa.

A: There's always a trade-off between creation and testing, I could create a perfect product, just come back in 10 years and it'll be ready.. and no manager will ever accept that estimate (or the cost :) )
So you have to be pragmatic, unit tests do not catch all bugs, so you should not try to create unit testing environment that is 100% perfect with 100% code coverage. You can spend 20% of the time writing 80% of the tests, and spend the rest of the time writing the integration tests that you need to do as well.
However, there's one part of your question that stands out:

to write and pass all the unit tests.

Now, the time spent making the code work so it passes the tests should be considered time spent in the initial coding stage. You can crack out any old rubbish code and say "finished!" but it isn't really finished - you just deferred some coding time to later (when the bug is discovered) or on someone else (which is worse, fix your own mess). So never think that writing code is the end of it, the time spent fixing code that is highlighted by your tests counts as coding time, not testing time.
So, to answer your question. I prefer integration testing in the main, so I don;t unit test everything. I tend to unit test only those parts of the code that is complex or awkward. So I would not try to limit the time spent testing, but to prioritise what needs testing. A simple method can be visually inspected to be correct if its simple enough, its pointless writing a unit test just for a getter for example. Then you can spend more time giving the complex methods the testing they deserve, saving the time you spent testing the trivial and your overall quality and productivity should rise.


text:
Q: ImportHTML won't update data I'm trying to use ImportHTML in Google Spreadsheets to update data regularly. The standard ImportHTML-code updates once an hour which is too slow, so I found some Google Script to do it every minute. (I should mention I'm not a developer so I'm kinda operating blind)
However, the script doesn't replace the old data with the new data (which is the idea). I need to remove all data from the spreadsheet for it to update the information. It seems to me te script is executing, but simply doesn't overwrite when cells are already filled. This is the Script I'm using:
function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet();
  var r = "A1";
  var insertDataOption = 'overwrite';
  var f = '=ImportHTML("URL";"table";1)';
   sh.getRange(r).setFormula(f) .onChange;
}

I hope you can help, thankS

A: If you add the same formula it might not not trigger a IMPORTHTML update. To make it work, first you could to clear the cell holding the IMPORTHTML formula, in this case A1, force the spreadsheet update, then add the formula.
function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet();
  var r = "A1";
  var insertDataOption = 'overwrite';
  var f = '=ImportHTML("URL";"table";1)';
  var range = sh.getRange(r);
  range.clear();
  SpreadsheetApp.flush();
  range.setFormula(f);
}

By the other hand if you are already using Google Apps Script, instead of using IMPORTHMTL you could use the Fetch Service to to the same job. This will require more coding but you will have more control over how frequently is updated your spreadsheet.
Resources

*

*https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#flush
Related (More recent first)

*

*Google Sheets IMPORTHTML

*ImportHTML recalculation by the minute

*Script to refresh data with IMPORTHTML in Google Sheets

*Trigger importHTML in Google Apps Script

*Importing javascript table into Google Docs spreadsheet


text:
Q: Why do I need to set permissions when calling OpenFile? I understand what permissions mean for files and dirs stored in filesystem.
But why do I need to set permissions when calling os.OpenFile?
Does it update file permission on filesystem if opened successfully?
If not - what difference does it make to open same file with 0000 or 0777?
https://golang.org/src/os/file.go?s=8454:8520#L272
func OpenFile(name string, flag int, perm FileMode) (*File, error)
...
f, err := os.OpenFile("access.log", os.O_APPEND, 0644)

A: As documented (emphasis added):

OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.) and perm (before umask), if applicable. If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

So, the perm value is only used when the file is created--when opening an existing file, it is not applicable, so it is ignored.


text:
Q: How can i select the highest bid for every card? What we are trying to achieve is to retrieve the highest bid for every card from an auction. Users do not know who has bid how much thus allowing them to bid less or the same amount as other users. The issue we have right now is that we cannot find the right use of GROUP BY. For now we have the following queries:
-- This one does not order the records correctly
SELECT
    DISTINCT ON ("auctionCardId") "auctionCardId",
    auction_card_bid."userId",
    auction_card_bid.id AS bid_id,
    MAX(auction_card_bid.time),
    MAX(auction_card_bid."bid")
FROM
    auction_card_bid auction_card_bid
    INNER JOIN auction_card ac ON ac.id = auction_card_bid."auctionCardId"
GROUP BY
    auction_card_bid.id,
    auction_card_bid."auctionCardId";

-- Orders the records correctly but it essentially returns all the records
SELECT
    "auctionCardId",
    auction_card_bid."userId",
    auction_card_bid.id AS bid_id,
    MAX(auction_card_bid.time),
    MAX(auction_card_bid."bid")
FROM
    auction_card_bid auction_card_bid
    INNER JOIN auction_card ac on ac.id = auction_card_bid."auctionCardId"
GROUP BY
    auction_card_bid.id,
    auction_card_bid."auctionCardId"
ORDER BY
    auction_card_bid.bid DESC,
    auction_card_bid.time ASC;

We have the following database structure:
auction

id
start
end

1
2020-05-05
2020-05-06

auction_card

id
card_id
auction_id
min_bid

1
1
1
40

2
2
1
50

auction_card_bid

id
card_id
user_id
bid
time

1
1
1
10
2020-05-05 10:00

2
1
2
20
2020-05-05 10:05

3
1
3
20
2020-05-05 10:08

4
2
2
20
2020-05-05 10:10

5
2
3
40
2020-05-05 10:15

The ideal result would be something among the lines of:

user_id
auction_card_id
bid_id
bid
time

2
1
2
20
2020-05-05 10:05

3
2
5
40
2020-05-05 10:15

A: After a lot of trial and error, we finally found out how to achieve what we wanted.
SELECT DISTINCT ON ("auctionCardId") "auctionCardId" AS  auction_card_id,
                                     auction_card_bid.id bid_id,
                                     value,
                                     time,
                                     "userId",
                                     auction_card."auctionId"
FROM auction_card_bid auction_card_bid
         JOIN auction_card auction_card ON auction_card_bid."auctionCardId" = auction_card.id
WHERE auction_card."auctionId" = 2
ORDER BY "auctionCardId", value DESC, time ASC;


text:
Q: Android Studio - Gradle commands spanning multiple Java process When I run gradlew commands or when Android Studio starts, It spanning one java process in every second, Which ends up using 100% of system memory usage. It was fine in the last android studio version, any idea how to fix this?
About the system
Android Studio 4.1.2
java version "15.0.2" 2021-01-19
Java(TM) SE Runtime Environment (build 15.0.2+7-27)
Java HotSpot(TM) 64-Bit Server VM (build 15.0.2+7-27, mixed mode, sharing)
Gradle 6.5

CPU AMD Ryzen 7 2700
Memory 32GB

I tried updating gradle.properties

*

*org.gradle.jvmargs=-Xmx4g -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

*org.gradle.jvmargs = -Xms512m -Xmx512m -XX:+UseCompressedOops -XX:+HeapDumpOnOutOfMemoryError

A: The issue is Windows 10 Mobile hotspot, When the Mobile hotspot is turned on Windows refuses to connect 127.0.0.1, Which is necessary for the Gradle daemon.
The fix is just to turn off the Windows Mobile Hotspot


text:
Q: iPhone application crashes with Mprotect failed error (MonoTouch) I have a problem with my iPhone application developed with MonoTouch.
I am developing an application that contacts a WCF Service, and when the WCF Service answer back, I update an UITableView with the returned data, when this is done it sends a new WCF async call, and when it answer back it updates the table again and so on.
The problem is that  when it has done this in a variable amount of time, it crashes with an Mprotect failed error 12. This only happens when the application is running directly on the phone and not in the simulator.
I have tried to out comment where the update of the table happens, and making a Thread.Sleep(1000) before sending the next Async request to the WCF Service, but still the same error, but can run longer with out failing.
I contact the WCF Service through the "proxy" files, generated by SlSvcUtil.exe /noConfig http://mydomain/myservice.svc
My question is that can this error be avoid in a way or maybe with a workaround? Is it my fault, or is it a bug? It is actually because I shall use the application in my final school project, so it could be nice if I could fix it.
I post the console output, and a part from the crash report, but if you need more info please tell me, and I will post it. I am not a pro to use Mono or the MonoTouch environment it is my first time, so detailed responses would be nice.
Console output:
Mon Dec 27 20:37:17 tests-iPhone UIKitApplication:dk.test.iphone[0x1c3c][625] <Notice>: Mprotect failed at 0xa09a000 (length 1052672) with errno 12

Mon Dec 27 20:37:17 tests-iPhone UIKitApplication:dk.test.iphone[0x1c3c][625] <Notice>: Stacktrace:

Mon Dec 27 20:37:17 tests-iPhone UIKitApplication:dk.test.iphone[0x1c3c][625] <Notice>:   at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication.UIApplicationMain (int,string[],intptr,intptr) <0xffffffff>

Mon Dec 27 20:37:17 tests-iPhone UIKitApplication:dk.test.iphone[0x1c3c][625] <Notice>:   at MonoTouch.UIKit.UIApplication.Main (string[],string,string) <0x000e0>

Mon Dec 27 20:37:17 tests-iPhone UIKitApplication:dk.test.iphone[0x1c3c][625] <Notice>:   at MonoTouch.UIKit.UIApplication.Main (string[]) <0x00023>

Mon Dec 27 20:37:17 tests-iPhone UIKitApplication:dk.test.iphone[0x1c3c][625] <Notice>:   at iPhoneStdView.Application.Main (string[]) <0x0001b>

Mon Dec 27 20:37:17 tests-iPhone UIKitApplication:dk.test.iphone[0x1c3c][625] <Notice>:   at (wrapper runtime-invoke) object.runtime_invoke_dynamic (intptr,intptr,intptr,intptr) <0x000c3>

Mon Dec 27 20:37:17 tests-iPhone UIKitApplication:dk.test.iphone[0x1c3c][625] <Notice>: Native stacktrace:

Mon Dec 27 20:37:18 tests-iPhone ReportCrash[635] <Notice>: Formulating crash report for process iPhoneNoNavigation[625]

Mon Dec 27 20:37:18 tests-iPhone com.apple.launchd[1] (UIKitApplication:dk.test.iphone[0x1c3c][625]) <Warning>: (UIKitApplication:dk.test.iphone[0x1c3c]) Job appears to have crashed: Abort trap

Mon Dec 27 20:37:18 tests-iPhone SpringBoard[27] <Warning>: Application 'iPhoneStdView' exited abnormally with signal 6: Abort trap

Crash report:
Thread 0 Crashed:
0   dyld                            0x2fe08110 0x2fe00000 + 33040
1   libSystem.B.dylib               0x3020259e 0x301ff000 + 13726
2   libSystem.B.dylib               0x302531da 0x301ff000 + 344538
3   iPhoneNoNavigation              0x0051975c 0x1000 + 5343068
4   iPhoneNoNavigation              0x00538080 0x1000 + 5468288
5   libSystem.B.dylib               0x302765cc 0x301ff000 + 488908
6   libSystem.B.dylib               0x30201d64 0x301ff000 + 11620
7   CoreFoundation                  0x3081fc38 0x307f8000 + 162872
8   CoreFoundation                  0x3081f4c2 0x307f8000 + 160962
9   CoreFoundation                  0x3081f270 0x307f8000 + 160368
10  CoreFoundation                  0x3081f178 0x307f8000 + 160120
11  GraphicsServices                0x31e445ec 0x31e40000 + 17900
12  GraphicsServices                0x31e44698 0x31e40000 + 18072
13  UIKit                           0x31e5111c 0x31e4d000 + 16668
14  UIKit                           0x31e4f128 0x31e4d000 + 8488
15  iPhoneNoNavigation              0x0006e754 0x1000 + 448340

Thread 0 crashed with ARM Thread State:
    r0: 0x35f4d17c    r1: 0x302765a9      r2: 0x35989b04      r3: 0x0000000e
    r4: 0x2fe29e78    r5: 0x07d17490      r6: 0x302765d3      r7: 0x2fffe24c
    r8: 0x00000000    r9: 0x3598762c     r10: 0x0000000d     r11: 0x07d17470
    ip: 0x3598762c    sp: 0x2fffe240      lr: 0x3e08dc60      pc: 0x2fe08110
  cpsr: 0x20000030

A: Error 12 is ENOMEM, you've exhausted all the memory available on the iphone.


text:
Q: C# Entity Framework Database First: Create association so that an entity has a list of the same entity type I have the following scenario to solve, using entity framework and a database first approach:
A table Student having the fields:
ID (PK), Name, Surname

And a table StudentsFriends that basically tells me what students are related to another, having the fields:
StudentID, FriendID

For instance, the latter table content could be:
StudentID, FriendID,
1          2
1          3
2          3
2          1

What I'd like to achieve is creating an association with a navigation property on the Student entity which tells me the list of friends, using the vs built in model browser. The generated entity would look something like this:
public class Student
{
     public int ID;
     public string Name;
     public string Surname;
     public ICollection<Student> Friends;
}

In the example above Student 1 is Friends with Student 2, Student 3  and Student 2 is friends with Student 3, Student 1. Student 3 has no friends.
However I have no idea how to achieve that: I only managed to create association between entities, and if I create an association on the same entity I can't "reference" the table to join them.
Thansk in advance for the help.


text:
Q: Reason for a certain assumption while computing limits using the definition I was reading Calculus by Michael Spivak, when I came across this problem given in the textbook..
Compute the limit
$$\lim_{x\to 2}{\frac{x^3-8}{x-2}}$$
Now, this is a pretty standard limit and I know there are a couple of ways to solve it..by factoring or by using L Hospital's rule...but here..I want to solve the limit by factoring..
My question is, when we solve the limit by factoring..we make an assumption that $x$ is not equal to 2. Now, yea I know that $x$ is only approaching the value 2..and hence the assumption is justified...but then this is not what the definition says right?
To me, the definition of a limit allows us to ignore the value 2
,while verifying that a certain number is the limit of the function or not..by finding a $\delta$ given an $\epsilon$.
What I mean to say is..the word "approach" is quite subjective and to me it's not very convincing that the limit will be the same even if we ignore the value 2...so I am looking for a rigorous line of reasoning entirely based on the definition of a limit which would then allow us to completely ignore the value of the function at $x=2$ even while COMPUTING the limit...not just while VERIFYING whether a certain number is the limit or not
PS: My question is a little "dry", in the sense it asks for something which should be obvious..but I'm still confused..because the definition of the limit is something very fundamental..and any such assumption made while computing limits must follow from the definition..
EDIT: I have tried to explain my question in a better way here
Thanks for any answers!!

A: The definition of a limit does not include the words like "approaches" or "tends" in a semantic manner but rather as a part of notation. The definition just asserts the truth of a complicated logical statement.
Further the definition of limit can not be used directly to evaluate limit of a function but it can be used to check if a given number is limit of function or not (and even this part requires some experience). The power of definition of limit comes from the fact that it can be used to prove general theorems which can be used to evaluate limits very effectively.
Coming to your problem at hand you have option to use the definition directly but then you need to guess a value for the limit and then check whether it is indeed the limit or not. The desired limit is $12$ and you should try to check this via definition of limit.
Another option is to use limit laws as explained in this answer.

A: Limits are essentially used

*

*when a function is undefined at some point but not in its neighborhood, and we want to continue it,

*when we want to check continuity, by comparing the limit and the function value.
In the first case, we have no function value at the given point, so your question is pointless.
In the second case, we must not use the known function value, and your question is answered.

A: Notice the the original function is not defined at $2$ in the first place,  and the limit is only concerned with values infinitely close to $2$ (but never equal to $2$). The left and right limits will approach whatever the factored version of the function at $2$ would equal.

A: When you are using the formal definition, the assumption is for every \epsilon exists $\delta$ so that if $0<|(x-x_0)|<\delta$, then $|f(x)-f(x_0)|<\epsilon$. meaning you do not equal $x_0$ exactly but in a close proximity not containing the point itself. It is important mainly becuase of issues with "plugging in" the point $x_0$ itself as in examples that you have given (it is just invalid because the function is not even defined there).


text:
Q: How to identify form inputs in mutli forms page with AngularJS I have got a page with some forms with diffirent types of inputs.
My form are function of a list of events.

        Event {{ event.id }}

            <fieldset>

                    Title :
                    <input type="text" name="event.title" class="form-control" ng-model="event.title"  required >

                    Month
                    <input type="text" name="event.month" class="form-control" ng-model="event.mois" required>

                    Date
                    <input type="text" name="event.date" class="form-control" ng-model="event.date"  required >

                    hour
                    <input type="text" name="event.hour" class="form-control" ng-model="event.hour"  required>

                    Description
                    <textarea type="text" name="description" class="form-control" ng-model="event.description" required></textarea>

            </fieldset>

            <input type="button" class="btn btn-into btn-lg btn-right"  value="Edit"></input>

The problem is about how to disable or enable one form. I want to let the oportunity to the user to enable inputs in one form, change one value and finally update changes.
To sum up, I have got a list of forms and I want my "Edit" button to enable inpus from only one form. I have got one edit button per form.
I would like to do the same to hide/show some buttons about saving/deleting when the user chose to edit on form.
How can I identify each input or each button from different forms ?

A: Here is the answer :

        Evenement {{ event.id }}
            <button class="btn btn-default" ng-click="isEditModeEnabled = !isEditModeEnabled">Edit</button>
            <fieldset ng-disabled="!isEditModeEnabled">
                    Title :
                    <input type="text" name="event.title" class="form-control" ng-model="event.titre"  required >

                    Month
                    <input type="text" name="event.month" class="form-control" ng-model="event.month" required>

                    Date
                    <input type="text" name="event.date" class="form-control" ng-model="event.date"  required >

                    Heure
                    <input type="text" name="event.hour" class="form-control" ng-model="event.heure"  required>

                    Description
                    <textarea type="text" name="description" class="form-control" ng-model="event.description" required></textarea>

            </fieldset>

                    <input type="button" class="btn btn-into btn-lg btn-right"  value="Save" ng-click="updateThis(event.id,event.title,event.month,event.date,event.hour,event.description)"></input>
                    <input type="button" class="btn btn-into btn-lg btn-right"  value="Delete" ng-click="deleteThis(event.id)"></input>

I tought that we had to change the variable name  isEditModeEnabled to avoid overlaps between different forms.


text:
Q: Can i change Profile pic through iphone? I want to change my profile pic through the iphone.Does Facebook provide any API which can change the Profile pic?Is it possible?

A: No its not possible
http://developers.facebook.com/search?q=Photos.upload
references:
Can I set a users profile image using the Facebook API?


text:
Q: Class variables not yet supported I begin my project with a split view controller as initial view controller and start it automatically from storyboard.
Generally, an app with this UI have one and only one split view controller as root, so I create a static variable in the subclass and set it when initialisation was done.
So I want try this behaviour with swift.
I read the Swift programming language guide book on iBook about Type properties (with static and class keyword) and trying a piece of code to the job:
import UIKit

class SplitViewController: UISplitViewController {

    class func sharedInstance() -> SplitViewController {
        return SplitViewController.instance
    }

    class let instance: SplitViewController = nil

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        self.initialization()
    }

    init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder);
        self.initialization()
    }

    func initialization() {
        SplitViewController.instance = self;
    }
}

but I figured out when Xcode say the class keyword for type properties wasn't supported yet.

Did you have a solution to do this ?

A: Embedding a struct can work just fine as a workaround:
class SomeClass
{
  // class var classVariable: Int = 0
  // "Class variables not yet supported." Weird.

  // Workaround:
  private struct SubStruct { static var staticVariable: Int = 0 }

  class var workaroundClassVariable: Int
  {
    get { return SubStruct.staticVariable }
    set { SubStruct.staticVariable = newValue }
  }
}

The SomeClass.workaroundClassVariable computed type property can then be used as if it were a stored type property.

A: As of Swift 1.2 (available with Xcode 6.3b1 and onwards), static class properties and methods are supported.
class SomeClass
{
    static var someVariable: Int = 0
}

A: Using a dispatch_once singleton model in Swift
Seems to be the best answer so far, avoiding the use of a global variable.

A: A solution enough similar than var in file scope but more customisable and near singleton is to use a struct which support static var as property of class
struct PersonSharedData {
    static var backstore = ""
    var data: String {
    get { return PersonSharedData.backstore }
    set { PersonSharedData.backstore = newValue }
    }
}

class Person {
    var shared=PersonSharedData() //<< pseudo class var
    var family: String {
        get { return shared.data }
        set { shared.data=newValue }
    }
    var firstname = ""
    var lastname = ""
    var sexe: Sexe = .Unknown
}

A: Swift now has support for static variables in classes. This is not exactly the same as a class variable (because they aren't inherited by subclasses), but it gets you pretty close:
class X {
  static let y: Int = 4
  static var x: Int = 4
}

println(X.x)
println(X.y)

X.x = 5

println(X.x)

A: Ok, with the solution of Nikolai that do the work. I post my changes in this thread for information
var instance: SplitViewController? = nil

class SplitViewController: UISplitViewController {

    class func sharedInstance() -> SplitViewController? {
        return instance;
    }

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        self.initialization()
    }

    init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder);
        self.initialization()
    }

    func initialization() {
        instance = self
    }
}

and for example, in my appDelegate, I can access this static method like this
SplitViewController.sharedInstance()!.presentsWithGesture = false

A: It seems to be possible to declare variables with static storage duration in file scope (as in C):
var sharedInstance: SplitViewController? = nil

class SplitViewController: UISplitViewController {
    ....
    func initialization() {
        sharedInstance = self
    }
}

A: My preferred method is to just use a private file scope var outside of the class and then implement class/static getters and setters:
private var _classVar: Int = 0;

class SomeClass
{
    public class var classVar: Int
    {
        get { return _classVar }
        set { _classVar = newValue }
    }
}

A: The wording in the error heavily implies this will be a language feature in the future.
You may want to resort temporarily to declaring a property variable in the Application Delegate and retrieve it from there. Not ideal, definitely an anti-pattern, but would give you a central place to retrieve the UISplitViewController when needed.

A: You have to wrap the class variables inside an inner struct variable
class Store{
    var name:String
    var address:String
    var lat:Int
    var long:Int
    init(name:String, address:String, lat:Int, long:Int){
        self.name = name
        self.address = address
        self.lat = lat
        self.long=long
    }

    private struct FACTORY_INITIALIZED_FLAG { static var initialized: Bool = false
       static var  myStoreList:[Store]?
        static func getMyStoreList()->[Store]{
            if !initialized{
                println("INITIALIZING")
                myStoreList = [
                    Store(name: "Walmart", address: "abcd", lat: 10, long: 20),
                    Store(name: "JCPenny", address: "kjfnv", lat: 23, long: 34)
                ]
                initialized = true
            }
                return myStoreList!
    }
    }
}

var a = Store.FACTORY_INITIALIZED_FLAG.getMyStoreList()

var b = Store.FACTORY_INITIALIZED_FLAG.getMyStoreList()

// only prints INITIALIZING once

A: Try this:
class var instance: SplitViewController {
    return nil
}

A: It is called Type Property in Swift.

You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass's implementation. The example below shows the syntax for stored and computed type properties:

struct SomeStructure {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        return 1
    }
}
enum SomeEnumeration {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        return 6
    }
}
class SomeClass {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        return 27
    }
    class var overrideableComputedTypeProperty: Int {
        return 107
    }
}

Read more at link below,
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID254


text:
Q: Is there any non zero $C^{\infty}$ function having zero derivatives at $0$? Let us take a function $f : \mathbb{R} \rightarrow \mathbb{R}$. $f \in C^{\infty}$. $f^k (0) = 0$ $\forall$ $k \ge 0 \in \mathbb{Z}$. Is $f (x) = 0$ $\forall$ $x\in \mathbb{R}$?
My attempt:
The function $f$ has a Taylor series expansion around $0$ and so
$$f(x) = f(0) + \frac{f'(0)}{1!}x + \frac{f^2(0)}{2!}x + \dots$$
The coefficients are all zero and so the function $f \equiv 0$.
There should be some mistake that I do not know.
If such a non-zero function exists please give me an example.
Thank you for your help.

A: Here's a couple:
$$
f(x) =
\begin{cases}
e^{-\frac{1}{x}} & x > 0 \\
0 & x \leq 0
\end{cases}
$$
and
$$
f(x) =
\begin{cases}
e^{-\frac{1}{x^2}} & x \neq 0 \\
0 & x = 0
\end{cases}.
$$
The existence of such functions show that even if it is $C^\infty$, it is not necessarily analytic.

A: The problem is that the taylor series of $f$ may not converge. If $f$ is analytic, then certainly what you said is true. Otherwise, you can only say that for each $k>0$,
$$f(x)=f(0)+f^{\prime}(0)x+...\frac{1}{k!}f^{(k)}(0)x^{k}+R_{k}(x)$$
where $R_{k}(x)$ is a remainder term. This term is $O(x^{k+1})$ so that when you divide by that term by $x^{k+1}$ the limit is bounded. For the examples above, this is s true for each $k$, since exponentials to negative powers decay much quicker than polynomials.


text:
Q: In the optical bench experiment of two pins (the object and image pin) kept on either side of convex lens. Why the real image appears on the lens? Since real images can only be seen on screen why are we able to see it on the lens. Will it not be called virtual?

A: If you are looking through the lens, what you see is a virtual image.  Used as a simple magnifier, a convex lens lets you bring the object close to the lens giving it a large angular size, while putting the virtual image in focus out beyond your near point (and not "on the lens"). On an optical bench, a small light bulb and a screen work better than pins for locating a real object and image.


text:
Q: Mockery and Laravel constructor injection I am using laravel 5 with php unit to create a laravel package. I have a Repository..
namespace Myname\Myapp\Repositories;

use Myname\Myapp\Models\PersonModel;

class PersonRepository
{
    protected $personModel;

    public function __construct(PersonModel $personModel)
    {
        $this->personModel = $personModel;
    }

    public function testFunction($var)
    {
        return $this->personModel->find($var);
    }
}

..which implements a Model.
namespace Myname\Myapp\Models;

use Illuminate\Database\Eloquent\Model;

class PersonModel extends Model
{
    protected $table = 'person';
}

Laravels IoC automatically injects PersonModel into the constructor of PersonRepository.
I am writing a unit test where I want to mock the PersonModel model using mockery so I am not hitting the database during testing.
namespace Myname\Myapptests\unit;

use Mockery;

class PersonRepositoryTest extends \Myname\Myapptests\TestCase
{
     /**
     * @test
     */
     public function it_returns_the_test_find()
     {
         $mock = Mockery::mock('Myname\Myapp\Models\PersonModel')
            ->shouldReceive('find')
            ->with('var');

         $this->app->instance('Myname\Myapp\Models\PersonModel', $mock);
         $repo = $this->app->make('Myname\Myapp\Repositories\PersonRepository');
         $result = $repo->testFunction('var');

         $this->assert...
     }
}

When I run the test I get an error

1) Myname\Myapptests\unit\PersonRepositoryTest::it_returns_the_test_find
  ErrorException: Argument 1 passed to Myname\Myapp\Repositories\PersonRepository::__construct() must be an instance of Myname\Myapp\Models\PersonModel, instance of Mockery\CompositeExpectation given

From what I have read, mockery extends the class it is mocking so there should be no issue injecting the extended class in place of the type hinted parent (PersonModel)
Obviously I am missing something. Other examples explicitly inject the mocked object into the class they are then testing. Laravels IoC is (should be) doing this for me. Do I have to bind anything?
I have a feeling though that the mockery object isn't being created in the way I think (extending PersonModel) otherwise I assume I wouldn't see this error.

A: Problem is when you create your mock:
$mock = Mockery::mock('Myname\Myapp\Models\PersonModel')
    ->shouldReceive('find')
    ->with('var');

So this:
$mock = Mockery::mock('Myname\Myapp\Models\PersonModel')
var_dump($mock);
die();

Will output something like this: Mockery_0_Myname_Myapp_Models_PersonModel
But this:
$mock = Mockery::mock('Myname\Myapp\Models\PersonModel')
    ->shouldReceive('find')
    ->with('var');
var_dump($mock);
die();

Will output this: Mockery\CompositeExpectation
So try doing something like this:
$mock = Mockery::mock('Myname\Myapp\Models\PersonModel');
$mock->shouldReceive('find')->with('var');

$this->app->instance('Myname\Myapp\Models\PersonModel', $mock);
$repo = $this->app->make('Myname\Myapp\Repositories\PersonRepository');
$result = $repo->testFunction('var');

A: While Fabio gives a great answer, the issue here is really the test setup. Mockery's mock objects do comply to contracts and will pass instanceof tests and type hints in method arguments.
The problem with the original code is that the chain of methods being called end up returning an expectation rather than a mock. We should instead create a mock first, then add expectations to that mock.
To fix it, change this:
$mock = Mockery::mock('Myname\Myapp\Models\PersonModel')
    ->shouldReceive('find')
    ->with('var');

Into this:
$mock = Mockery::mock('Myname\Myapp\Models\PersonModel');
$mock->shouldReceive('find')->with('var');

The variable $mock will now implement PersonModel.
Bonus:
Instead of 'Myname\Myapp\Models\PersonModel', use PersonModel::class. This is a lot more IDE-friendly and will help you when refactoring code later on.


text:
Q: Errors in mapping using a stream I'm currently having troubles figuring out how to use Java 8 streams.
I'm trying to go from lista_dottori (Map<Integer, Doctor>) to a new map patientsPerSp where to every medical specialization (method getSpecialization) I map the number of patients wich have a doctor with this specialization (method getPatients in class Doctor returns a List of that doctor's patients). I can't understand how to use the counting method for this purpose, and I can't seem to find any examples nor explanations for this kind of problems on the internet.
That's what i've written, it does give me error in the counting section:
public Collection<String> countPatientsPerSpecialization(){
    patientsPerSp=
            lista_dottori.values().stream()
            .map(Doctor::getSpecialization)
            .collect(groupingBy(Doctor::getSpecialization, counting(Doctor::getPatients.size())))
            ;
}

A: Seems that you want to sum the sizes of patients lists. This can be done by summingInt() collector, not counting() (which just counts occurences; doctors in this case). Also mapping seems to be unnecessary here. So you cuold write:
patientsPerSp = lista_dottori.values().stream()
        .collect(groupingBy(Doctor::getSpecialization,
                 summingInt(doctor -> doctor.getPatients().size())));

Note that the results will be incorrect if several doctors have the same patient (this way it will be counted several times). If it's possible in your case, then it would be probably better to make a set of patients:
patientsPerSp = lista_dottori.values().stream()
        .collect(groupingBy(Doctor::getSpecialization,
                 mapping(Doctor::getPatients(), toSet())));

This way you will have a map which maps specialization to the set of patients, so the size of this set will be the count which you want. If you just need the count without set, you can add a final step via collectingAndThen():
patientsPerSp = lista_dottori.values().stream()
        .collect(groupingBy(Doctor::getSpecialization,
                 collectingAndThen(
                     mapping(Doctor::getPatients(), toSet()),
                     Set::size)));

A: I solved the problem avoiding using the streams. That's the solution I used:
public Collection<String> countPatientsPerSpecialization(){

    int numSpec = 0;
    Map<String, Integer> spec = new HashMap<>();

    for(Doctor d : lista_dottori.values()){
        if(!spec.containsKey(d.getSpecialization())){
            spec.put(d.getSpecialization(), d.getPatients().size());
            numSpec++;
        }
        else{ //cioè se la specializzazione c'è già
            spec.replace(d.getSpecialization(), +d.getPatients().size());
        }
    }
    patientsPerSp.add(spec.keySet() + ": " + spec.values());
    for(String s : patientsPerSp)
        System.out.println(s);
    return patientsPerSp;
}

I couldn't seem to be able to solve it using your solutions, although they were very well exposed, sorry.
Thank you anyway for taking the time to answer

A:     Map<String, Integer> patientsPerSpecialization =
            doctors.values()
            .stream()
            .collect(Collectors.groupingBy(Doctor::getSpecialization,
                   Collectors.summingInt(Doctor::nberOfAssignedPatients)));


text:
Q: Help debugging window.event.screenX I'm using firebug and the latest FF to debug this bit of javascript.  When line #30 is hit in the debugger the screen tries to refresh with message

"To display this page, firefox must
  send information that will repeat any
  action (such as a search or order
  confirmation) that was performed
  earlier.

Javascript with line #'s  Called via OnClick()
function EnterComment(divName, /*...couple other params*/) {
25
26 thatDiv = divName;
27 //...comment
28
29 // Mouse Position with offset
30 var x = window.event.screenX + 10;
31 var y = document.body.scrollTop + 20;

This doesn't work in IE either.  Is there any way to get an exception from Firebug?  Any other tips to fix this?

A: Firefox doesn't have a global "event" object at all. Instead, a reference to an essentially similar object is passed in to event handlers by the runtime system.
I can't tell what sort of code is that fragment you posted. As an example, if you're binding event handlers with the basic DOM 0 attributes, you can do this:
hi

and then:
function yourhandler(event) {
  event = event || window.event;
  var X = event.screenX;
  // ...
}

If, as you mention in a comment, you were to use jQuery to bind handlers, then it's even easier because it's the same in all browsers:
$(function() {
  $('#myAnchor').click(function(event) {
    var X = event.pageX;
  });
});