text:
Q: Angular 2; How to hide/disable the past events in fullcalendar I am using full calendar
this.calendarOptions = {
            height: '1000',
            fixedWeekCount: false,
            header:
            {
                left: 'prev,next,today',
                center: 'title',
                right: 'month,listYear',
            },
            defaultDate: new Date(),
            editable: true,
            timeFormat: 'hh:mm A',
            eventLimit: true,

            events: (start, end, title, callback) => {
                this.calenderservice.getExamCandidateById(this.value)
                    .subscribe(response => {
                        callback(response),
                            this.modalData = response.Items
                        this.myCalendar.fullCalendar('renderEvents', this.modalData)
                        console.log(this.modalData);
                        console.log(response);
                    });
            },

response
 Items:{
    ExamName:null
    ExamSiteId:334
    Id:85
    LastUpdateDateTime:"0001-01-01T00:00:00"
    PostalCode:"33172"
    PptSeats:null
    SeatCount:0
    SiteName:"UF"
    State:"FL"
    end:"2017-09-27T10:30:00"
    isCbt:"1"
    isPpt:null
    start:"2017-09-27T10:30:00"
    title:"7 available"
}

From above code i am getting all start and end dates from response,and displays the events in calendar
i want to hide the past events,how i can hide the events which contain past start and end dates from current date in fullcalendar.
please help me.

A: You should apply filter before passing the value to full calendar. Something like this:
 events: (start, end, title, callback) => {
            this.calenderservice.getExamCandidateById(this.value)
                .subscribe(response => {
                    callback(response),
                     var date = new Date(); //Today's date
                    this.modalData = response.Items.filter( item => item.StartDate > date || item.EndDate > date  ); //only select items whose start or end date are after today's date.
                    this.myCalendar.fullCalendar('renderEvents', this.modalData)
                    console.log(this.modalData);
                    console.log(response);
                });


text:
Q: Site-to-Site VPN from Windows Azure to Cyberoam CR25iNG I'm trying to configure Site-to-Site VPN between Windows Azure and on Premise network using Cyberoam CR25iNG UTM Firewall
The Local Network Subnet is
192.168.0.1/20 (192.168.0.0 - 192.168.15.255)

The Address Space of Azure is
192.168.16.0/20 (192.168.16.4 - 192.168.31.254)

The following subnets have been created on Windows Azure
FrontEndSubnet 192.168.18.0/24 (192.168.18.4 - 192.168.18.254)
BackEndSubnet  192.168.20.0/24 (192.168.20.4 - 192.168.20.254)
ADDNSSubnet    192.168.22.0/24 (192.168.22.4 - 192.168.22.254)
Gateway        192.168.16.0/24 (192.168.16.4 - 192.168.16.254)

I've followed the instructions on
http://www.windowsazure.com/en-us/manage/services/networking/cross-premises-connectivity/
I've got a valid Gateway address and managed to generate a Pre-Shared key.
On the Cyberoam gateway, I've setup an IPSEC VPN connection entering the gateway details and configuring the subnets as follows:
Local Network: 192.168.0.0/255.255.255.0

Remote Network: 192.168.16.0/255.255.240.0

Cant manage to connect from the Azure Side or the Local Network.
Azure only has scripts for Cisco, Juniper and Microsoft RRAS.
Anybody managed to use Cyberoam to connect with Azure VPN?

A: Cyberoam has given the solution for firmware 10.0 onwards. The detailed explanation is given on this URL
http://kb.cyberoam.com/default.asp?id=2936&Lang=1

redpajama_set_name: RedPajamaStackExchange


text:
Q: check NULL value of a std:string pointer In c++, as far as I know, I believe that a std::string cannot represent the absence of a value. Therefore, in case of a method returning a pointer to a std::string such as, std::string *myMethod(). Does it make sense to check if the return value from myMethod is NULL?
The use case related to my question is the following: the std::string *method() was automatically created by gsoap stub library from a WSDL file. I do not have access to the WSDL file, hence i cannot change the signature of the method. My c++ application is the client and the server is a java application. Both of these applications communicate via web services

A: Yes, it makes sense.
The return type is a pointer of type string..pointers contain addresses, and it is possible that it may be null.
In this case, returning a pointer and null check is the right way to go about it.
If you don't want to check for null, then the alternative would be return by reference, but the usage is complex and is best fit when used for operator chaining.Whether that fits the current use case is another question by itself.
Is the practice of returning a C++ reference variable, evil?

A: Yes, it makes sense. The relevant part is hidden in a comment: "method() was automatically created ... from a WSDL file". In text-based protocols such as WDSL that follow a "key-value" pattern, the absence of a key is syntactically different from a key="" empty key. A generic library cannot assume the two are semantically equivalent. Thus it will use return nullptr to signal the absence of a key.

A: If your function returns a std::string*, you can check if it returns NULL (or better, nullptr) because you don't check the string itself but a pointer to the string.


text:
Q: disaggregate summarised table in SQL Server 2008 I've received data from an external source, which is in a summarised format. I need a way to disaggregate this to fit into a system I am using.
To illustrate, suppose the data I received looks like this:
receivedTable:

Age     Gender     Count
40      M          3
41      M          2

I want this is a disaggregated format like this:
systemTable:

ID      Age        Gender
1       40         M
2       40         M
3       40         M
4       41         M
5       41         M

Thanks
Karl

A: Depending of the range of your count you could use  a lookup table that holds exactly x records for each integer x. Like this:
create table counter(num int)
insert into counter select 1

insert into counter select 2
insert into counter select 2

insert into counter select 3
insert into counter select 3
insert into counter select 3

insert into counter select 4
insert into counter select 4
insert into counter select 4
insert into counter select 4

then join with this table:
create table source(age int, gender char(1), num int)
insert into source select 40, 'm', 3
insert into source select 30, 'f', 2
insert into source select 20, 'm', 1

--insert into destination(age, gender)
    select age, gender
    from source
        inner join counter on counter.num = source.num

A: From the "Works on my machine (TM)" stable a recursive query, with all the usual caveats about maximum recursion depth.
with Expanded(exAge, exGender, exRowIndex) as
(
    select
        Age as exAge,
        Gender as exGender,
        1 as exRowIndex
    from
        tblTest1
    union all
        select
            exAge,
            exGender,
            exRowIndex+1
        from
            tblTest1 t1
            inner join
            Expanded e on (e.exAge = t1.Age and e.exGender = t1.Gender and e.exRowIndex < t1.Count)
)
select
    exAge,
    exGender,
    exRowIndex
from
    Expanded
order by
    exAge,
    exGender,
    exRowIndex
option (MAXRECURSION 0)  -- BE CAREFUL!!

You don't get the row identifier - but inserting the result of the query into a table with an identity column would deal with that.


text:
Q: install Nuance voices on a web hosting server I'm creating a text-to-speech application. it's an ASP.NET application that makes use of the System.Speech namespace to convert some text to .wav audio format.
the thing is that I want to be able to install multiple Nuance voices on the server to make use of them in my application.
is there any website hosting provider (like godaddy.com) that can allow a web application owner to install programs on their system ? is there another way to solve this ?

A: You can use a dedicated server from many ISP's including GoDaddy.com. This will basically be your own server, you can install anything you want. However, this will be pricey, you can look into a virtual dedicated server, which is cheaper and should allow you to install whatever applications you need.


text:
Q: How to sign in second user in incognito window to test actioncable I'm trying to sign in a 2nd user to see if ActionCable is working.  I have my app open in a regular Chrome window on localhost:3000 and I also have it open in an incognito window also localhost:3000
From https://github.com/rails/actioncable-examples:

*

*Open two browsers with separate cookie spaces (like a regular session and an incognito session).

*Login as different people in each browser.
3  Go to the same message.

*Add comments in either browser and see them appear real-time on the counterpart screen.

However, when I sign in the 2nd user in the incognito window, the 1st user gets logged out.
I'm using ng-token-auth and devise_token_auth for authentication.
Also, I have an ng-click that toggles the navbar to collapse
<button type="button" class="navbar-toggle" ng-click="isNavCollapsed = !isNavCollapsed">
  <i class="fa fa-bars" aria-hidden="true"></i>
</button>

When I click the hamburger button in either the regular window or the incognito window, the navbar collapses in both windows.
I thought an incognito window would give me a completely separate cookie jar and therefore separate $scopes but I guess not.
I hope someone can tell me what is going one.

A: When using Incognito mode, your Sesssion stays active on every tab/window as long as you do not close each and every one of them as stated on the Incognito start page:

Pages you view in incognito tabs won't stick around in your browser's history, cookie store, or search history after you've closed all of your incognito tabs. Any files you download or bookmarks you create will be kept.

Having stated this, your session is completely different from the one in a normal tab/window, so the action cable test should work.
This may fail if by any means your logic overrides the logged in user when a new user gets logged in.


text:
Q: If logic in for loop for asp.net MVC I have the following code and it is the nightmare that I feared when I saw the razor syntax in the project that got dumped in my lap. It doesn't understand what part is code and what part HTML.
@for (int i = 0; i < Model.Instructor.Classes.Count;i++ )
        {
            var c = Model.Instructor.Classes[i];
            var mod = (i%2);
            if (mod==1)
            {

                   }

                        @c.Subject @c.CatalogNumber -  @c.Section

                    if (mod==0)
                    {

            }

        }

I am just trying to do a simple multicolumn table because the list of items is too long on the page.It prints out my if logic as if it were text. If I put a @ in front of it, it gives me a syntax error. It seems there should be a control for this but all the controls I have seen are worried about alt-styles and not the number of columns to put the data.

A: For starters, remove the semi-colons.  Razor syntax doesn't use them.  More to the point, you shouldn't be writing things like var c = Model.Instructor.Classes[i]; in your view.  The view should just bind to the view model, which should be built/returned form the controller.
You can, within your controller, set ViewBag properties which map to these values that you want.  Be actual logic like this shouldn't be in the view.
Finally, if Razor is having trouble parsing which of your terms it needs to parse (which, as you allude to at the beginning of your question, is a potential pitfall), you can use the <text> tag to explicitly outline which parts should be text.


text:
Q: Tried everything but still get "native typeface cannot be made" In an app I am building, I'd like to use the standard Apple font: Myriad Pro. To do this, I've tried the normal way of using a custom font:
Typeface myriadPro = Typeface.createFromAsset(getAssets(), "fonts/myriad_pro.ttf");

And the workaround for an issue that Android sometimes has with fonts as discussed here:
public class Typefaces {
private static final String TAG = "Typefaces";

private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();

public static Typeface get(Context c, String assetPath) {
    synchronized (cache) {
        if (!cache.containsKey(assetPath)) {
            try {
                Typeface t = Typeface.createFromAsset(c.getAssets(),
                        assetPath);
                cache.put(assetPath, t);
            } catch (Exception e) {
                Log.e(TAG, "Could not get typeface '" + assetPath
                        + "' because " + e.getMessage());
                return null;
            }
        }
        return cache.get(assetPath);
    }
}
}

I've tried both methods with the OTF and the TTF versions of the font. None of the variations work. In all cases I get the native typeface cannot be made error (i.e. it can't find the typeface), even though the typeface is in the right place with the right name.
Any ideas what's still causing this error to occur?

A: I had the same problem.
Go to the AndroidManifest.xml.
minSdkVersion MUST be 10 or higher.


text:
Q: Why Unruh temperature is the temperature measured by observer with $\xi = 0$? My coordinate transformation is:
\begin{align}
t=\frac{1}{a} e^{a \xi} \sinh (a \eta), \quad x=\frac{1}{a} e^{a \xi} \cosh (a \eta).
\end{align}
The free scalar field is quantized under this coordinate by:
\begin{align}
\phi=\sum_{k}\left(\hat{b}_{k} g_{k}+\hat{b}_{k}^{\dagger} g_{k}^{*}\right).
\end{align}
By Bogoliubov transformation, the particle number distribution in Minkowski vacuum is:
\begin{align}
\left\langle 0_{\mathrm{M}}\left|\hat{b}_{k}^{ \dagger} \hat{b}_{k}^{}\right| 0_{\mathrm{M}}\right\rangle \propto \frac{1}{e^{2 \pi \omega / a}-1}.
\end{align}
This is a thermal spectrum of bosons with temperature $T=a/2\pi$. Then many textbooks claim that it is the temperature measured by observer $\xi=0$, but I dont quite understand. As far
as I see, $\hat{b}_{k}\hat{b}_{k}^{\dagger}$ is not a local operator, thus the temperature should be the average temperature of the whole Rindler wedge. Due to the red shift, Rindler observer with larger $\xi$ should measure a lower temperature:
\begin{align}
T(\xi) = e^{-a\xi} \cdot T(\xi=0).
\end{align}
I think the average temperature should be defined as:
\begin{align}
\bar{T} = \frac{\int{T(\xi)\sqrt{\gamma}}d\xi}{\int{\sqrt{\gamma}}d\xi},
\end{align}
but it does not give the right result. However, if I define in this way:
\begin{align}
\bar{T} = \frac{\int{T(\xi)\sqrt{\gamma}}d\xi}{\int{d\xi}},
\end{align}
it really gives $\bar{T} = T(\xi=0)$. But the denominator in this definition is coordinate-dependent. Do I miss something? Or my average temperature argument is wrong?
I know that Unruh effect can also be obtained by considering the interaction of an accelerating detector with the field. There is no ambiguity in this case. But I still wish to find a physical explanation under the framework of Bogoliubov transformation.

A: To define creation and annihilation operators in a curved spacetime, one needs to have a timelike Killing field to work as the generator of time-translations. This will then lead to an associated notion of energy and allow to obtain a positive and negative energy decomposition of modes of the field, allowing for the definition of the creation and annihilation operators. For a more detailed discussion of this construction see this answer I wrote a while back, which is based on the treatment given on R. Wald's Quantum Field Theory in Curved Spacetime and Black Hole Thermodynamics and on a seminal paper by Ashtekar & Magnon on QFT in Stationary Spacetimes.
In the Rindler wedge, one such vector field is given by
$$\beta^{\mu} = a\left(x \left(\frac{\partial}{\partial t}\right)^{\mu} + t \left(\frac{\partial}{\partial x}\right)^{\mu}\right),$$
which is the generator of boosts in the $x$ direction. In the Rindler wedge, this field is timelike, and hence it can be taken to be the generator of a different notion of time translations.
It remains to consider which observers experience this notion of time translation. To do so, we can simply impose $\beta^{\mu} \beta_{\mu} = - 1$, which corresponds to requiring that the Killing field corresponds to a four-velocity. This condition translates to
$$a^2 (-x^2 + t^2) = -1, \tag{1}$$
which specifies a particular orbit of the Killing field. Hence, for the observers following this particular orbit of the Killing field, the experienced notion of time is precisely that defined by the Killing field, and hence it makes sense to state that the particle content seem by them is the same described by the creation and annihilation operators defined with respect to this Killing field.
Replacing your expressions for $t$ and $x$ in terms of $\xi$ and $\eta$ on Eq. (1) leads to the condition that $\xi = 0$, while not imposing any new restrictions on $\eta$. It is not possible for an observer to be travelling parallel to the Killing field with $\xi \neq 0$: that would break the normalization of the four-velocity.


text:
Q: pisa html to pdf issue with greek stressed letters used with django I am using pisa to generate a pdf from html in a django application. My view code is the following
if request.method == 'POST':
    return write_to_pdf(request.POST['convert'], { }, 'file')

where convert is a TextArea from which i get the value to write on my pdf file
write_to_pdf
def fetch_resources(uri, rel):
    path = '%s/media/pdf/' % RHOMBUS_PATH
    return path

def write_to_pdf(template_data, context_dict, filename):
    print template_data
    template = Template(template_data)
    context = Context(context_dict)
    html = template.render(context)
    print html
    result = StringIO.StringIO()
    pdf = pisa.CreatePDF(html.encode('UTF-8'), result, link_callback=fetch_resources, encoding='UTF-8')
    print result.getvalue()

    if not pdf.err:
        response = http.HttpResponse(mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=%s.pdf' % filename
        response.write(result.getvalue())
        return response
    return http.HttpResponse('Problem creating PDF: %s' % cgi.escape(html))

The generated pdf though has a problem when the TextArea has greek stressed characters like
ά έ

etc. I tried changing the encodings but nothing. Any help would be appreciated.

A: I also had this issue with Greek characters (instead of stressed characters I received black boxes). As a first step you need to change your font to a proper one (like dejavu sans). To do this, add a style element to your html template like this:
<style type='text/css'>

    @font-face {
        font-family: "DejaVuSansMono";
        src: url("fonts/DejaVuSansMono.ttf");
    }

    @font-face {
        font-family: "DejaVuSansMono";
        src: url("fonts/DejaVuSansMono-Bold.ttf");
        font-weight: bold;
    }
    @font-face {
        font-family: "DejaVuSansMono";
        src: url("fonts/DejaVuSansMono-Oblique.ttf");
        font-style: italic, oblique;
    }
    @font-face {
        font-family: "DejaVuSansMono";
        src: url("fonts/DejaVuSansMono-BoldOblique.ttf");
        font-weight: bold;
        font-style: italic, oblique;
    }

    *, html {
        font-family: "DejaVuSansMono";
    }

    html {
        padding:10pt;
    }

</style>

Now, the dejavusans font can be downloaded from http://dejavu-fonts.org/wiki/Main_Page. Also, there are various issues with the location that you will put the font files - I have provided some insight on my answer to trouble in converting unicode template to pdf using xhtml2pdf. As a first step, I propose to put these fonts in C:/fonts (or /tmp/fonts if using unix) and use the absolute url for @font-face, for instance
@font-face {
    font-family: "DejaVuSansMono";
    src: url("c:/fonts/DejaVuSansMono.ttf");
}

After that, check my answer to see how you can use relative urls.
Finally, I have to mention that I've only tested the above with dejavu-sans (and it works fine) - however I'd really like to know if the above solution works fine with other fonts, like Calibry - if you test it please provide feedback.
If the above doesn't work, please take a look at the render_to_pdf function I use:
def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, path= settings.PROJECT_PATH)

    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('<pre>%s</pre>' % escape(html))


text:
Q: How to properly control snmptrapd within a bash script I am trying to monitor snmp notifications using snmptrapd.
It is ran using bash script and I add the '&' at the end of the snmptrapd line (1) to run it in the background. This way I start listening to the 162 port and the rest of the script can be executed without being blocked. The problem is I can not figure out how to properly terminate or stop the snmptrapd after I finished my test (since it runs on the background). The work flow is something like this:
1    sudo snmptrapd -f -C -c my.conf -L f my.log &
2    # do test 1
3    sudo service snmptrapd stop;
4    # analyze the .log file
5    sudo service snmptrapd start;
6    # do test 2
7    sudo service snmptrapd stop;
8    # analyze the .log file
9    ...

but line (3) does not seem to stop the trapd - I can see that the notifications are kept being received. Not sure if line (5) starts "unstopped" smnptrapd, but the line (7) seem to stop the service - I can see that the notifications are not being received anymore (using wireshark). In addition to that, the two files referenced in line (1) are with the "locked" icon.
I would like to be able to stop snmptrapd and make changes and/or create new files and then restart the snmptrapd again to run the next test.

*

*Why do I get this inconsistent behavior when the first "stop" command does not seem to have any effect, and the second one does.

*Is there a better way to control this process?

*How to make the files "unlocked", so I could delete them or edit?


text:
Q: Cesar's Cypher method repeating the last letter of each word I'm making Cesar's Cypher that shifts the letters 13 places. It works, but the last letter of each word is repeated. I know there is probably a more efficient way to write this, but here is my code.

function rot13(str) {
  var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
  var word = "";
  var z = 30;
  for (i = 0; i < str.length; i++) {
    if (str.substring(i, i + 1) === " ") {
      word = word + str.substring(i, i + 1);
    }

    for (x = 0; x < letters.length; x++) {
      if (str.substring(i, i + 1) === letters[x]) {
        z = x; //18
      }
    }

    var n = z + 13; //31
    if (n >= 26) {
      word = word + letters[13 - (26 - z)];
    } else if (n < 26)
      word = word + letters[13 + z];
  }

  return word;
}

rot13("LBH QVQ VG!");

For example LBH QVQ VG! prints out YOU UDID DITT instead of YOU DID IT!. Also, I'm new to javascript so if any syntax looks off please correct me.

A: Your first problem is that you should continue; the for loop if you detect a space (otherwise your last used character gets appended a second time):
if (str.substring(i, i + 1) === " ") {
  word += " ";
  continue;
}

Your second problem is that you don't care if the current character isn't found in your letters array, in that case your code simply uses the last z.
Just as a sidenote: In your position I would take a look at JS' built-in functions, for example split, indexOf, charCodeAt, fromCharCode, which can simplify your life quite a bit.

A: The problem is that when you find a space and copy it to the result, you don't skip over the rest of the code that processes the character. Since the loop that sets z never finds a match, it uses the value of z from the previous iteration of the loop, so it duplicates the last character of the previous word.
The same thing happens if there's a punctuation character. In this case, the code that tests for space doesn't copy it to the result, then you go into the loop that looks for the character in letters, it doesn't find it, so it again uses the previous value of z.
A simple solution for both is to check whether the current character is in letters, rather than checking specifically for space.
BTW, you can use str[i] or str.charAt(i) to get the current character in the string, rather than str.substring(i, i+1). And to find an element of an array, use letters.indexOf(char) instead of an explicit loop.

function rot13(str) {
  var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
  var word = "";
  var z = 30;
  for (i = 0; i < str.length; i++) {
    var char = str[i];
    z = letters.indexOf(char);
    if (z == -1) {
      word += char;
      continue;
    }

    var n = z + 13; //31
    if (n >= 26) {
      word = word + letters[13 - (26 - z)];
    } else if (n < 26)
      word = word + letters[13 + z];
  }

  return word;
}

console.log(rot13("LBH QVQ VG!"));

And instead of your if statement at the end, you can use the modulus operator:
word += letters[n % letters.length];


text:
Q: After finishing the countdown I want to show number of counts in a Text View ,eg: after finishing 1st round Text view should show x1, for 2nd round x2 [enter image description here][1]
emphasized text
[1]: https://i.stack.imgur.com/tNgwZ.png

A: Create a global var and increment that with every timer reset
Example
int timerCounts = 0;

@Override
onCreate....

private void starttimer(){
  ......
  .....
  onFinish(){
    timerCounts++;
    your_text_view_to_show_counts.setText(timerCounts+'X');
  }

}


text:
Q: Downloading CSV Online and Converting to Pandas DF I have a CSV file that I'm downloading online. I'm trying to get it into a Pandas DataFrame. The source is the Federal Reserve Bank and using inflation data (CPI). I'm missing something to make this work.
Here's the URL to download:
s_url = https://fred.stlouisfed.org/graph/fredgraph.csv?cosd=1990-01-01&coed=2040-01-01&id=CPIAUCSL

I'm taking that URL and reading it with this:
response = urlopen(s_url).read()

That gives me something that looks like this:
b'DATE,CPIAUCSL\n1990-01-01,127.5\n1990-02-01,128.0\n1990-03-01,128.6\n1990-04-01,128.9\n1990-05-01,129.1\n1990-06-01,129.9\n1990-07-01,130.5\n1990-08-01,131.6\n1990-09-01,132.5\n1990-10-01,133.4\n1990-11-01,133.7\n1990-12-01,134.2\n1991-01-01,134.7\n1991-02-01,134.8\n1991-03-01,134.8\n1991-04-01,135.1\n1991-05-01,135.6\n1991-06-01,136.0\n'

I tried to then take that response and read it into Pandas:
df = pd.read_csv(response)

That doesn't work. What steps am I missing in this process?

A: It seem that using url directly as df argument works. Did you try it?
import pandas as pd
s_url = 'https://fred.stlouisfed.org/graph/fredgraph.csv?cosd=1990-01-01&coed=2040-01-01&id=CPIAUCSL'
df = pd.read_csv(s_url)

A: You can use stringIO to read data from string.
data = b'DATE,CPIAUCSL\n1990-01-01,127.5\n1990-02-01,128.0\n1990-03-01,128.6\n1990-04-01,128.9\n1990-05-01,129.1\n1990-06-01,129.9\n1990-07-01,130.5\n1990-08-01,131.6\n1990-09-01,132.5\n1990-10-01,133.4\n1990-11-01,133.7\n1990-12-01,134.2\n1991-01-01,134.7\n1991-02-01,134.8\n1991-03-01,134.8\n1991-04-01,135.1\n1991-05-01,135.6\n1991-06-01,136.0\n'
from io import StringIO
import pandas as pd
data = data.decode('utf-8') #decode binary string to utf-8
df = pd.read_csv(StringIO(data)) #read the data
df

Output:
DATE    CPIAUCSL
0   1990-01-01  127.5
1   1990-02-01  128.0
2   1990-03-01  128.6
3   1990-04-01  128.9
4   1990-05-01  129.1
5   1990-06-01  129.9


text:
Q: AXIsProcessTrustedWithOptions returns NO even though the app is on the whitelist We have a Mac App Store app that needs access to the Accessibility API. Since 10.9 Mavericks, there is a system whitelist for the apps that want to use the Accessibility API (System Preferences → Security & Privacy → Accessibility).
While testing an update for our app, we have noticed that right after the upgrade from the old version, system tells us that we don't have a right to use the Accessibility API (AXIsProcessTrustedWithOptions returns NO), even though our app is on the whitelist, with the checkbox checked. Once we uncheck and recheck the permission, everything works fine.
Obviously, this is not a acceptable upgrade scenario for us, especially since the accessibility whitelist is buried so deep in System Preferences and can't be accessed from code.
Is this a system bug? Is there a known workaround? We would accept having to recheck the Accessibility permissions after a big update – it just sucks navigating your users to the System Preferences only to see the checkbox already checked, without the feature working.
Updates:

During the first post-upgrade launch, the system complains in the console:
16/03/15 06:47:10,343 tccd[190]: Unable to verify code signing identity of com.company.app:  code failed to satisfy specified code requirement(s)
16/03/15 06:47:10,350 universalAccessAuthWarn[401]: AccessibilityAPI: pid 471, is not allowed to access the accessibility API. Path: /path/to/app

Weird thing is, once the permission checkbox on the accessibility whitelist is unchecked and rechecked, there are no errors in the console during the subsequent launches, even though the binary is the same.

I've peeked under the hood into the SQLite database implementing the access whitelist (/Library/Application Support/com.apple.TCC/TCC.db). The access table holds a csreq column that looks like some application fingerprint/hash blob:
$ sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db 'select client, quote(csreq) from access'
com.apple.dt.Xcode|X'…'
com.apple.AccessibilityInspector|X'…'
com.ourcompany.app|X'…'

(The quoted hashes were replaced with "…".)
Now, if I install the older version of our app and run it, a hash is computed by the system and stored in the csreq column. If I perform a clean install of the new app version, I get a different hash.
When I install the old version and then delete it, the column still contains the hash for the old version. Could this be the source of the problem? Because when I set the column to NULL before updating the app, everything works fine. A new hash gets computed, the Accessibility API check returns YES as it should.

Same issue in a different app on GitHub.

A: There's a thing called designated requirement (see the Code Signing Guide). Roughly speaking, it's a set of criteria that system uses to determine if two app bundles represent the same app, security-wise. The designated requirement can be displayed using the codesign -dvv --req - YourApp.app command. In our case, the designated requirement check failed, since the older app version was signed using a different certificate than the development build.
In other words, when trying to replace a Mac App Store build with a development build, a security check will fail because of certificate mismatch and you will have to re-check some app permissions. As far as I know, this won't happen when you have distributed and installed the same build through Mac App Store.


text:
Q: Convert long/lat to pixel x/y on a given picture I have a city map of Moscow. We modified a Google Maps image with some artistic elements, but the relation between GPS coordinates and pixels remains the same.
Problem: How do I convert GPS coordinates from various data points we have into pixel coordinates in the image?
Ideally I can do this in Javascript, but PHP would be OK.

I know that on small scales (for example on city scales) it to make simply enough (it is necessary to learn what geographic coordinates has one of picture corners, then to learn "price" of one pixel in geographic coordinates on a picture on axes OX and OY separately).
But on the big scales (country scale) "price" of one pixel will be not a constant, and will vary strongly enough and the method described above cannot be applied.
How to solve a problem on country scales?

Update:
I do not use API Google Maps, I have only: geographic coordinates of the object (they are from google maps), I still have at my site a simple picture *. gif, in which I must draw a point corresponding geographic coordinates.

A: So you want to take latitude/longitude coordinates and find out the pixel coordinates on your image of that location?
The main GMap2 class provides transformation to/from a pixel on the displayed map and a lat/long coordinate:
Gmap2.fromLatLngToContainerPixel(latlng)

For example:
var gmap2 = new GMap2(document.getElementById("map_canvas"));
var geocoder = new GClientGeocoder();

geocoder.getLatLng( "1600 Pennsylvania Avenue NW Washington, D.C. 20500",
    function( latlng ) {
        var pixel_coords = gmap2.fromLatLngToContainerPixel(latlng);

        window.alert( "The White House is at pixel coordinates (" +
            pixel_coodrs.x + ", " + pixel_coords.y + ") on the " +
            "map image shown on this page." );
    }
);

So assuming that your map image is a screen grab of the Google Map display, then this will give you the correct pixel coordinate on that image of a lat/long coordinate.
Things are trickier if you're grabbing tile images and stitching them together yourself since the area of the complete tile set will lie outside the area of the displayed map.
In this case, you'll need to use the left and top values of the top-left image tile as an offset from the coordinates that fromLatLngToContainerPixel(latlng:GLatLng) gives you, subtracting the left coordinate from the x coordinate and top from the y coordinate. So if the top-left image is positioned at (-50, -122) (left, top), and fromLatLngToContainerPixel() tells you a lat/long is at pixel coordinate (150, 320), then on the image stitched together from tiles, the true position of the coordinate is at (150 - (-50), 320 - (-122)) which is (200, 442).
It's also possible that a similar GMap2 coordinate translation function:
GMap2.fromLatLngToDivPixel(latlng:GLatLng)

will give you the correct lat/long to pixel translation for the stitched-tiles case - I've not tested this, nor is it 100% clear from the API docs.
See here for more:
http://code.google.com/apis/maps/documentation/reference.html#GMap2.Methods.Coordinate-Transformations

A: The key to all of this is understanding map projections.  As others have pointed out, the cause of the distortion is the fact that the spherical (or more accurately ellipsoidal) earth is projected onto a plane.
In order to achieve your goal, you first must know two things about your data:

*

*The projection your maps are in.  If they are purely derived from Google Maps, then chances are they are using a spherical Mercator projection.

*The geographic coordinate system your latitude/longitude coordinates are using.  This can vary, because there are different ways of locating lat/longs on the globe.  The most common GCS, used in most web-mapping applications and for GPS's, is WGS84.

I'm assuming your data is in these coordinate systems.
The spherical Mercator projection defines a coordinate pair in meters, for the surface of the earth.  This means, for every lat/long coordinate there is a matching meter/meter coordinate.  This enables you to do the conversion using the following procedure:

*

*Find the WGS84 lat/long of the corners of the image.

*Convert the WGS lat/longs to the spherical Mercator projection.  There conversion tools out there, my favorite is to use the cs2cs tool that is part of the PROJ4 project.

*You can safely do a simple linear transform to convert between points on the image, and points on the earth in the spherical Mercator projection, and back again.

In order to go from a WGS84 point to a pixel on the image, the procedure is now:

*

*Project lat/lon to spherical Mercator.  This can be done using the proj4js library.

*Transform spherical Mercator coordinate into image pixel coordinate using the linear relationship discovered above.

You can use the proj4js library like this:
// include the library
<script src="lib/proj4js-combined.js"></script>  //adjust the path for your server
                                                 //or else use the compressed version
// creating source and destination Proj4js objects
// once initialized, these may be re-used as often as needed
var source = new Proj4js.Proj('EPSG:4326');    //source coordinates will be in Longitude/Latitude, WGS84
var dest = new Proj4js.Proj('EPSG:3785');     //destination coordinates in meters, global spherical mercators projection, see http://spatialreference.org/ref/epsg/3785/

// transforming point coordinates
var p = new Proj4js.Point(-76.0,45.0);   //any object will do as long as it has 'x' and 'y' properties
Proj4js.transform(source, dest, p);      //do the transformation.  x and y are modified in place

//p.x and p.y are now EPSG:3785 in meters

A: You may have a look at code that used on gheat, it's ported from js to python.

A: The translation you are addressing has to do with Map Projection, which is how the spherical surface of our world is translated into a 2 dimensional rendering.  There are multiple ways (projections) to render the world on a 2-D surface.
If your maps are using just a specific projection (Mercator being popular), you should be able to find the equations, some sample code, and/or some library (e.g. one Mercator solution - Convert Lat/Longs to X/Y Co-ordinates.  If that doesn't do it, I'm sure you can find other samples -  https://stackoverflow.com/search?q=mercator.  If your images aren't map(s) using a Mercator projection, you'll need to determine what projection it does use to find the right translation equations.
If you are trying to support multiple map projections (you want to support many different maps that use different projections), then you definitely want to use a library like PROJ.4, but again I'm not sure what you'll find for Javascript or PHP.

A: If each pixel is assumed to be of the same area then the following article about converting distances to longitude/latitude co-ordinates may be of some help to you:
http://www.johndcook.com/blog/2009/04/27/converting-miles-to-degrees-longitude-or-latitude/

A: You need formulas to convert latitude and longitude to rectangular coordinates. There are a great number to choose from and each will distort the map in a different way. Wolfram MathWorld has a good collection:
http://mathworld.wolfram.com/MapProjection.html
Follow the "See Also" links.

A: One of the important things to take into account is the "zoom" level of your projection (for Google Maps in particular).
As Google explains it:

At zoom level 1, the map consists of 4 256x256 pixels tiles, resulting
  in a pixel space from 512x512. At zoom level 19, each x and y pixel on
  the map can be referenced using a value between 0 and 256 * 2^19

( See https://developers.google.com/maps/documentation/javascript/maptypes?hl=en#MapCoordinates)
To factor in the "zoom" value, I recommend the simple and effective deltaLonPerDeltaX and deltaLatPerDeltaY functions below. While x-pixels and longitudes are strictly proportional, this is not the case for y-pixels and latitudes, for which the formula requires the initial latitude.
// Adapted from : http://blog.cppse.nl/x-y-to-lat-lon-for-google-maps

window.geo = {

    glOffset: Math.pow(2,28), //268435456,
    glRadius:  Math.pow(2,28) / Math.PI,
    a: Math.pow(2,28),
    b: 85445659.4471,
    c: 0.017453292519943,
    d: 0.0000006705522537,
    e: Math.E, //2.7182818284590452353602875,
    p: Math.PI / 180,

    lonToX: function(lon) {
        return Math.round(this.glOffset + this.glRadius * lon * this.p);
    },

    XtoLon: function(x) {
        return -180 + this.d * x;
    },

    latToY: function(lat) {
        return Math.round(this.glOffset - this.glRadius *
                          Math.log((1 + Math.sin(lat * this.p)) /
                          (1 - Math.sin(lat * this.p))) / 2);
    },

    YtoLat: function(y) {
        return Math.asin(Math.pow(this.e,(2*this.a/this.b - 2*y/this.b)) /
                                 (Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1) -
                                 1/(Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1)
                        ) / this.c;
    },

    deltaLonPerDeltaX: function(deltaX, zoom) {
        // 2^(7+zoom) pixels <---> 180 degrees
        return deltaX * 180 / Math.pow(2, 7+zoom);
    },

    deltaLatPerDeltaY: function(deltaY, zoom, startLat) {
        // more complex because of the curvature, we calculte it by difference
        var startY = this.latToY(startLat),
            endY = startY + deltaY * Math.pow(2, 28-7-zoom),
            endLat = this.YtoLat(endY);

        return ( endLat - startLat ); // = deltaLat
    }
}

A: my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823

A: You will have to implement the Google Maps API projection in your language. I have the C# source code for this:
public class GoogleMapsAPIProjection
{
    private readonly double PixelTileSize = 256d;
    private readonly double DegreesToRadiansRatio = 180d / Math.PI;
    private readonly double RadiansToDegreesRatio = Math.PI / 180d;
    private readonly PointF PixelGlobeCenter;
    private readonly double XPixelsToDegreesRatio;
    private readonly double YPixelsToRadiansRatio;

    public GoogleMapsAPIProjection(double zoomLevel)
    {
        var pixelGlobeSize = this.PixelTileSize * Math.Pow(2d, zoomLevel);
        this.XPixelsToDegreesRatio = pixelGlobeSize / 360d;
        this.YPixelsToRadiansRatio = pixelGlobeSize / (2d * Math.PI);
        var halfPixelGlobeSize = Convert.ToSingle(pixelGlobeSize / 2d);
        this.PixelGlobeCenter = new PointF(
            halfPixelGlobeSize, halfPixelGlobeSize);
    }

    public PointF FromCoordinatesToPixel(PointF coordinates)
    {
        var x = Math.Round(this.PixelGlobeCenter.X
            + (coordinates.X * this.XPixelsToDegreesRatio));
        var f = Math.Min(
            Math.Max(
                 Math.Sin(coordinates.Y * RadiansToDegreesRatio),
                -0.9999d),
            0.9999d);
        var y = Math.Round(this.PixelGlobeCenter.Y + .5d *
            Math.Log((1d + f) / (1d - f)) * -this.YPixelsToRadiansRatio);
        return new PointF(Convert.ToSingle(x), Convert.ToSingle(y));
    }

    public PointF FromPixelToCoordinates(PointF pixel)
    {
        var longitude = (pixel.X - this.PixelGlobeCenter.X) /
            this.XPixelsToDegreesRatio;
        var latitude = (2 * Math.Atan(Math.Exp(
            (pixel.Y - this.PixelGlobeCenter.Y) / -this.YPixelsToRadiansRatio))
            - Math.PI / 2) * DegreesToRadiansRatio;
        return new PointF(
            Convert.ToSingle(latitude),
            Convert.ToSingle(longitude));
    }
}

Source:
http://code.google.com/p/geographical-dot-net/source/browse/trunk/GeographicalDotNet/GeographicalDotNet/Projection/GoogleMapsAPIProjection.cs

A: Struggled with this - Have both openstreet map and google street map and wanted to project an external graphic image
var map = new OpenLayers.Map({
            div:"map-id",
            allOverlays: true
    });
    var osm = new OpenLayers.Layer.OSM("OpenStreeMao");
    var gmap = new OpenLayers.Layer.Google("Google Streets", {visibility: false});

    map.addLayers([osm,gmap]);

    var vectorLayer = new OpenLayers.Layer.Vector("IconLayer");

    var lonlatObject = new OpenLayers.LonLat(24.938622,60.170421).transform(
            new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()
    );
    console.log(lonlatObject);

    var point = new OpenLayers.Geometry.Point(lonlatObject.lon, lonlatObject.lat);
    console.log(point);

    var point2 = new OpenLayers.Geometry.Point(lonlatObject.x, lonlatObject.y);
    console.log(point2);

    var feature = new OpenLayers.Feature.Vector(point, null, {
        externalGraphic:  "http://cdn1.iconfinder.com/data/icons/SUPERVISTA/networking/png/72/antenna.png",
        graphicWidth: 72,
        graphicHeight: 72,
        fillOpacity: 1
    });

    vectorLayer.addFeatures(feature);

    map.addLayer(vectorLayer);

    map.setCenter(
            new OpenLayers.LonLat(24.938622,60.170421).transform(
            new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()
            ),
            12);

     map.addControl(new OpenLayers.Control.LayerSwitcher());

http://jsfiddle.net/alexcpn/N9dLN/8/


text:
Q: parameterized sql script using wrapper I have created below sql script where i am trying to parameterized it using zone and market ans saved this script as wrapper.sql
define zone1= &1.
define market1= &2.
set lines etc
SET ECHO OFF
SET FEEDBACK OFF
SET HEAD OFF
SET LIN 256
SET WRAP OFF
SET PAGES 0
spool H:\extract_&zone1&market1..csv
select 'zone'         ||','||
       'market'         ||','||
       'id'
result from dual
union all
select zone    ||','||
       market    ||','||
       id
from solution_report
where rownum <5 and zone = &zone1 and market = &market1;
/
spool off

Now as i have 23 zones with respect to the market i have created 23 wrapper script and saved it in file wrapper_script.sql. I want to generate 23 excel files for each zone with respect to their market.
@C:\Users\raw\Desktop\wrapper.sql As Asia
.
.
.
@C:\Users\raw\Desktop\wrapper.sql AF Africa

But when i am trying to run this wrapper_script.sql then its generating the 23 csv files but there is no  data in the file. I am using oracle sql developer client to run this scripts as i dont have access to sql plus.
I am not sure whether i am using spool on the wrong place or i am calling it wrong as i am passing string values in wrapper?
Also is there any other way around so that instead of creating 23 wrapper files it can optimize the work.
Below is my select query result and i believe i have to format the string for zone and market column.
zone,market,boutique_id
EUR,Belgium,1233
EUR,Portugal,1345
EUR,Portugal,1567

A: You need to use &1. and &2. in the script to reference the 1st and second command line parameters.  You can immediately assign them to named variables like this:
define zone1 = &1.
define market1 = &2.

The . at the end is optional but I prefer to always use it to avoid ambiguity in some cases.


text:
Q: Issue with uniqueness of the persist names in syslog-ng I am new to syslog-ng and was trying to fix the issue of an error which arises due to uniqueness of the persist names in syslog-ng,
I see the below error in my syslog

err Error checking the uniqueness of the persist names, please override it with persist-name option. Shutting down.; persist_name='afsocket_dd.(dgram,10.120.21.10:514)', location='/etc/syslog-ng/syslog-ng.conf:81:26'

The current syslog-ng.conf is as below, I did a search in google and found we need to add persist-name() in order to make it unique,
but with my understanding each if the destination is already unique, with the below syslog-ng.conf, I get the error when the IP address are same, destination d_tempask_1  and destination d_temst_1 have the same IP address. But if I provide a different IP address I don't see the error.
Could anybody provide some insight as to how to handle same IP address.

source s_syslogng {
file ("/proc/kmsg" program_override("kernel: "));
unix-stream ("/run/systemd/journal/syslog" max-connections(200)); };
source s_internal {
internal();   };
filter f_test1 { message("__test1"); };
destination d_test1_1 { udp ( "192.168.202.119"
port(514)  template("<$PRI>$DATE local0 infoblox Outbound[]: debug
$MSGONLY\n") template_escape(no) ); };
log { source(s_syslogng); filter(f_test1); destination(d_test1_1); };
filter f_tempask { message("__tempask"); };
destination d_tempask_1 { udp ( "10.120.21.10"
port(514)  template("<$PRI>$DATE local0 infoblox Outbound[]: debug
$MSGONLY\n") template_escape(no) ); };
log { source(s_syslogng); filter(f_tempask); destination(d_tempask_1);
};
filter f_temst { message("__temst"); };
destination d_temst_1 { udp ( "10.120.21.10"
port(514)  template("<$PRI>$DATE local0 infoblox Outbound[]: debug
$MSGONLY\n") template_escape(no) ); };
log { source(s_syslogng); filter(f_temst); destination(d_temst_1); };
filter f_dir { message("__dir"); };
destination d_dir_1 { udp ( "10.35.183.11"
port(514)  template("<$PRI>$DATE local0 infoblox Outbound[]: debug
$MSGONLY\n") template_escape(no) ); };
log { source(s_syslogng); filter(f_dir); destination(d_dir_1); };

tried with persist-name(), but even that still throws the error even if IP address is different or same
syslog-ng.conf with persist-name()

source s_syslogng {
file ("/proc/kmsg" program_override("kernel: "));
unix-stream ("/run/systemd/journal/syslog" max-connections(200)); };
source s_internal {
internal();   };
filter f_test1 {
message("__test1"); };
destination d_test1_1 { persist-name(test1_1) udp ( "192.168.202.119"
port(514)  template("<$PRI>$DATE local0 infoblox Outbound[]: debug
$MSGONLY\n") template_escape(no) ); };
log { source(s_syslogng); filter(f_test1); destination(d_test1_1); };
filter f_tempask { message("__tempask"); };
destination d_tempask_1 { persist-name(tempask_1) udp ( "10.120.21.11"
port(514)  template("<$PRI>$DATE local0 infoblox Outbound[]: debug
$MSGONLY\n") template_escape(no) ); };
log { source(s_syslogng); filter(f_tempask); destination(d_tempask_1);
};
filter f_temst { message("__temst"); };
destination d_temst_1 { persist-name(temst_1) udp ( "10.120.21.10"
port(514)  template("<$PRI>$DATE local0 infoblox Outbound[]: debug
$MSGONLY\n") template_escape(no) ); };
log { source(s_syslogng); filter(f_temst); destination(d_temst_1); };
filter f_dir { message("__dir"); };
destination d_dir_1 { persist-name(dir_1) udp ( "10.35.183.11"
port(514)  template("<$PRI>$DATE local0 infoblox Outbound[]: debug
$MSGONLY\n") template_escape(no) ); };
log { source(s_syslogng); filter(f_dir); destination(d_dir_1); };

Any input will be very help full.

A: The persist-name() option should go inside the destination's declaration:
udp("10.120.21.10" port(514) persist-name("temst_1"));


text:
Q: HTML BASE doesn't work properly in FF 13 and Chromium 18 on Ubuntu 12.04 I got some simple and valid HTML:
<!DOCTYPE html>

  <base href="http://localhost/cow/" />
  <title></title>

    bar

but the link only points to http://localhost/foo.html instead of the full URI (with subdir). In addition something like <base href='http://127.0.0.1/something/' /> doesn't work but it is done as described here: http://www.w3schools.com/html5/tag_base.asp
That shouldn't be, or?
How to fix that?
Thanks in advance!

A: You should remove the '/' before foo.html
bar

And of course all the slashes before all the relative paths in this web page


text:
Q: need to download a PDF using python selenium i am trying to automate PDF downloading using Selenium Webdriver in python
but the problem is the download button was hidden inside a embed tag in HTML
<embed width="100%" height="100%" name="plugin" id="plugin" src="www.abc.com/123.pdf" type="application/pdf" internalinstanceid="4" title="">

and the page would be like this page view before download button view
if i move the mouse over the top of the PDF
after i move the mouse button over the top of the PDF
i need to click on the download button but the element was not visible at first when i try to inspect its element by clicking f12 but when i inpect the element by right clickin on it, it will load the new separate HTML document  so i have no idea how to manipulate into that HTML any idea would be very helpful.

A: Why are you using Selenium for this?
It is easy and efficient with Requests.
import requests
url='https://www.cs.uky.edu/~keen/115/Haltermanpythonbook.pdf'
page = requests.get(url) # get url

name = url.split('/')[-1] # to get filename
f = open(name,'wb')  # make a file object

f.write(page.content) # write data
f.close()

This gives you flexibility to download anywhere you want and is a lot faster than selenium.


text:
Q: How to fix this "your system administrator has configured chrome to open an alternate browser to access" I'm trying open an application in google chrome, when I launch the website chrome it redirects to IE and showing message "your system administrator has configured chrome to open an alternate browser to access" in chrome. How to overcome this issue

A: Behavior

*

*You open a corporate site. For example,
http://legacy_SharePoint_2010.com

*You will see a message: "Your
system administrator has configured chrome to open an alternate
browser to access"

*Your IE 11 will be opened and your chrome tab will be closed:

Why this is happening

*

*The behavior is controlled by the Chrome Policies (chrome://policy/)

*

*When Policy is setup, chrome://browser-switch protocol is used to redirect to IE

*The list of sites that will be forced to use IE 11 is listed in the  registry, under Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\BrowserSwitcherUrlList

*

*You might need local admin permissions to modify or remove these registry keys
:

A: When your company forces such policy by default than sooner or later you have to update the policy in regedit again. Quite elegant solution could be to switch off/on the policy when needed. I do so with Python and winreg module (but could be similar in other languages):
import winreg
from itertools import count

def switch_reg_browser_switcher():
    reg_handler = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    with winreg.OpenKey(reg_handler, r"SOFTWARE\Policies\Google\Chrome", 0, winreg.KEY_ALL_ACCESS) as regkey:
        for i in count():
            try:
                val_name, curr_value, _ = winreg.EnumValue(regkey,i)
                if val_name == 'BrowserSwitcherEnabled':
                    print(val_name, curr_value)
                    winreg.SetValueEx(regkey, val_name, 0, winreg.REG_DWORD, curr_value^1)
                    break
            except OSError:
                print('All keys iterated but "BrowserSwitcherEnabled" not found')
                break

print('Updating Windows registry to reset company policy...')
switch_reg_browser_switcher()

Or a simple solution in Batch file:
@echo off
set regkey="HKLM\SOFTWARE\Policies\Google\Chrome"
REG QUERY %regkey% /v BrowserSwitcherEnabled
if %errorlevel% equ 0 ( REG ADD %regkey% /v BrowserSwitcherEnabled /t REG_DWORD /d 0 /f
) else (echo no such value)

My motivation to do this was webscraping with Selenium (Chrome driver is much faster than IE) and no power to force my company to change policy.


text:
Q: Update list item through Sharepoint REST API I want to update certain fields for a ListItem in Sharepoint. How can I achieve this via the REST API?
Is there any documentation for this?
 EDIT 1
Consider the following JSON that I receive on requesting a ListItem(GET)
{
"d": {
    "__metadata": {
        "id": "8b3d2196-ad3e-4766-a23e-7e6a89153965",
        "uri": "https://abc-my.sharepoint.com/personal/nn_abc_co/_api/Web/Lists(guid'd02a8c5b-cd69-4aa8-b7fb-9d539733f285')/Items(383)",
        "etag": "\"2\"",
        "type": "SP.Data.DocumentsItem"
    },
    "FirstUniqueAncestorSecurableObject": {
        "__deferred": {
            "uri": ".../FirstUniqueAncestorSecurableObject"
        }
    },
    "RoleAssignments": {
        "__deferred": {
            "uri": ".../RoleAssignments"
        }
    },
    "AttachmentFiles": {
        "__deferred": {
            "uri": ".../AttachmentFiles"
        }
    },
    "ContentType": {
        "__deferred": {
            "uri": ".../ContentType"
        }
    },
    "FieldValuesAsHtml": {
        "__deferred": {
            "uri": ".../FieldValuesAsHtml"
        }
    },
    "FieldValuesAsText": {
        "__metadata": {
            "id": ".../FieldValuesAsText",
            "uri": ".../_api/Web/Lists(guid'd02a8c5b-cd69-4aa8-b7fb-9d539733f285')/Items(383)/FieldValuesAsText",
            "type": "SP.FieldStringValues"
        },
        "ContentTypeId": "0x0120000E7EB3018A9074468823208C432BDCA5",
        "Title": "",
        "IsMyDocuments": "",
        "SharedWithInternal": "",
        "SharedWithUsers": "",
        "ID": "383",
        "Created": "7/29/2014 11:28 PM",
        "Author": "3",
        "Modified": "7/29/2014 11:28 PM",
        "Editor": "3",
        "OData__x005f_CopySource": "",
        "CheckoutUser": "",
        "OData__x005f_UIVersionString": "1.0",
        "GUID": "da1e223b-1335-49e8-a544-b2cbebd4064f",
        "OData__x005f_ModerationStatus": "Approved",
        "OData__x005f_Level": "1",
        "UniqueId": "3dba6291-92c7-458f-9a28-e0a91696d9ca",
        "FSObjType": "1",
        ...
        },
    "FileSystemObjectType": 1,
    "Id": 383,
    "ContentTypeId": "0x0120000E7EB3018A9074468823208C432BDCA5",
    "Title": null,
    "IsMyDocuments": null,
    "SharedWithInternalId": null,
    "SharedWithUsersId": {
        "__metadata": {
            "type": "Collection(Edm.Int32)"
        },
        "results": [5]
       },
...   }
}

From the JSON above(which I have altered ofcourse, but is a real response), I need to change the value for "SharedWithUsers" under "FieldValuesAsText" object.
Is this possible? I have been trying it, and even the call returns success response code, but it doesn't change anything.
On the other hand if I change fields in the first level, by that I mean fields like "Title", it changes successfully.
However(beyond my understanding) values like "SharedWithUsersId" in the first level don't change either. Even though I get the same success response code for it as well.
The Post data I am creating is as follows,
For Title (works like a charm! Every blog that I have read, refers this example!)
{
  "__metadata": {
    "type": "SP.Data.DocumentsItem"
},
    "Title":"Blabla"
}

For SharedWithUsers field under FieldValuesForEdit OR FieldValuesAsText
{
"__metadata": {
    "type": "SP.Data.DocumentsItem"
},
"FieldValuesForEdit": {
    "__metadata": {
        "type": "SP.FieldStringValues"
    },
    "SharedWithUsers": ""
}
}

I have verified that SharedWithUsers's value is "" when it doesn't contain any data (the sample JSON i have posted confirms it) But POST call with such data doesn't update it.
For SharedWithUsersId
{
"__metadata": {
    "type": "SP.Data.DocumentsItem"
},
"SharedWithUsersId": {
        "__metadata": {
            "type": "Collection(Edm.Int32)"
        },
        "results": []
    }
}

Note here that in this case >>> "SharedWithUsersId":null doesn't work either, even though my own sinful eyes have seen such a response for some items! (All Hail Microsoft!!!)
For all of the above POST data JSON objects, I get a 204 response code (which I believe is the right code for a MERGE call)
I hope I have explained my question well enough. Any or all help is appreciated!

A: Read this MSDN post: http://msdn.microsoft.com/en-us/library/office/dn292552%28v=office.15%29.aspx#ListItems
url ==> should be pointing to the listitem you want to update.
method ==> POST, because you want to update a listitem
body ==> JSON formatted, contains the fields you want to update. Omit the ones you don't want to change.
Below and example:
url: http://site url/_api/web/lists/GetByTitle('Test')/items(item id)
method: POST
body: { '__metadata': { 'type': 'SP.Data.TestListItem' }, 'Title': 'TestUpdated'}
headers:
   Authorization: "Bearer " + accessToken
   X-RequestDigest: form digest value
   "IF-MATCH": etag or "*"
   "X-HTTP-Method":"MERGE",
   accept: "application/json;odata=verbose"
   content-type: "application/json;odata=verbose"
   content-length:length of post body

Getting the accessToken could be hard, depending from what kind of application (SharePoint App, Console App, inside SharePoint) you do this call.

A: If you wish to do this using the HttpClient you can reference this article.  I show how to get the Digest and Upload files and update the list item after the fact.  Works for Windows Store, Console and Forms apps.
Example for updating a file from the HttpClient using REST:

     client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
     client.BaseAddress = new System.Uri(url);
     client.DefaultRequestHeaders.Clear();
     client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
     client.DefaultRequestHeaders.Add("X-HTTP-Method", "MERGE");
     client.DefaultRequestHeaders.Add("IF-MATCH", "*");
     HttpContent strContent = new StringContent(String.Concat("{ '__metadata': { 'type': 'SP.List' }, 'Title': '", filename, "' }"));
     strContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
     strContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));
     HttpResponseMessage updateResponse = await client.PostAsync(String.Concat("_api/web/lists/GetByTitle('Project Photos')/Items(", id, ")"), strContent);
     updateResponse.EnsureSuccessStatusCode();
     if (updateResponse.IsSuccessStatusCode)
     {}

https://arcandotnet.wordpress.com/2015/04/01/sharepoint-2013-rest-services-using-c-and-the-httpclient-for-windows-store-apps/
Arcan.NET


text:
Q: Doctrine Native SQL many-to-many query I have a many-to-many relationship between Students and Programs with tables student, program, and student_program in my database.
I'm trying to join the two entities and perform some custom queries that require subqueries. This means that the Doctrine QueryBuilder cannot work because it does not support subqueries.
Instead, I'm trying the NativeSQL function and am making decent progress. However, when I try to SELECT something from the Program entity, I get the error Notice: Undefined index: Bundle\Entity\Program in vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php line 180.
    $mapping = new \Doctrine\ORM\Query\ResultSetMappingBuilder($em);
    $mapping->addRootEntityFromClassMetadata('Student', 's');
    $mapping->addJoinedEntityFromClassMetadata('Program', 'p', 's', 'programs', array('id' => 'program_id'));
    // Query based on form
    $sql = 'SELECT s.id, s.last_name, p.name <---- problem when this is added
            FROM student s
            JOIN program p
            ';

    $query = $em->createNativeQuery($sql, $mapping);

    $students = $query->getResult();

A: Not a direct answer but doctrine 2 does indeed support sub queries.  Just create a query then feed the dql into a where class.  This example is somewhat verbose but it works just fine:
public function queryGames($search)
{
    // Pull params
    $ages    = $this->getValues($search,'ages');
    $genders = $this->getValues($search,'genders');
    $regions = $this->getValues($search,'regions');

    $sortBy  = $this->getValues($search,'sortBy',1);
    $date1   = $this->getValues($search,'date1');
    $date2   = $this->getValues($search,'date2');
    $time1   = $this->getValues($search,'time1');
    $time2   = $this->getValues($search,'time2');

    $projectId = $this->getValues($search,'projectId');

    // Build query
    $em = $this->getEntityManager();
    $qbGameId = $em->createQueryBuilder(); // ### SUB QUERY ###

    $qbGameId->addSelect('distinct gameGameId.id');

    $qbGameId->from('ZaysoCoreBundle:Event','gameGameId');

    $qbGameId->leftJoin('gameGameId.teams',   'gameTeamGameId');
    $qbGameId->leftJoin('gameTeamGameId.team','teamGameId');

    if ($projectId) $qbGameId->andWhere($qbGameId->expr()->in('gameGameId.projectId',$projectId));

    if ($date1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.date',$date1));
    if ($date2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.date',$date2));

    if ($time1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.time',$time1));
    if ($time2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.time',$time2));

    if ($ages)    $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.age',   $ages));
    if ($genders) $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.gender',$genders));

    if ($regions)
    {
        // $regions[] = NULL;
        // $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.org',   $regions));

        $qbGameId->andWhere($qbGameId->expr()->orX(
            $qbGameId->expr()->in('teamGameId.org',$regions),
            $qbGameId->expr()->isNull('teamGameId.org')
        ));

    }
    //$gameIds = $qbGameId->getQuery()->getArrayResult();
    //Debug::dump($gameIds);die();
    //return $gameIds;

    // Games
    $qbGames = $em->createQueryBuilder();

    $qbGames->addSelect('game');
    $qbGames->addSelect('gameTeam');
    $qbGames->addSelect('team');
    $qbGames->addSelect('field');

    $qbGames->addSelect('gamePerson');
    $qbGames->addSelect('person');

    $qbGames->from('ZaysoCoreBundle:Event','game');

    $qbGames->leftJoin('game.teams',   'gameTeam');
    $qbGames->leftJoin('game.persons', 'gamePerson');
    $qbGames->leftJoin('game.field',   'field');

    $qbGames->leftJoin('gameTeam.team',     'team');
    $qbGames->leftJoin('gamePerson.person', 'person');

    $qbGames->andWhere($qbGames->expr()->in('game.id',$qbGameId->getDQL())); // ### THE TRICK ###

    switch($sortBy)
    {
        case 1:
            $qbGames->addOrderBy('game.date');
            $qbGames->addOrderBy('game.time');
            $qbGames->addOrderBy('field.key1');
            break;
        case 2:
            $qbGames->addOrderBy('game.date');
            $qbGames->addOrderBy('field.key1');
            $qbGames->addOrderBy('game.time');
            break;
        case 3:
            $qbGames->addOrderBy('game.date');
            $qbGames->addOrderBy('team.age');
            $qbGames->addOrderBy('game.time');
            $qbGames->addOrderBy('field.key1');
            break;
    }

    // Always get an array even if no records found
    $query = $qbGames->getQuery();
    $items = $query->getResult();

    return $items;
}


text:
Q: How to call own function from click method I know it sounds stupid, but i have no idea how to call my function from "onclick" function?
I made own class and what i wanna do is to call my function inside a class.
I have tried various stuff inside that onclick function:

*

*function(){this.getWidth()}

*this.getWidth()

*Test.getWidth()

function Datagrid(_parent, _data)
{
    this.table = [];
    this.parent = $("#"+_parent)[0] ? $("#"+_parent) : ($("."+_parent)[0] ? $("."+_parent) : ($(+_parent)[0] ? $(_parent) : null));
    this.data = _data;
this.Datagrid = function(parent,data)
{
    this.setParent(parent);
    if(data != null)
        this.setData(data);
    return this;
}

this.setParent = function(parent)
{
    return this.parent = $("#"+parent)[0] ? $("#"+parent) : ($("."+parent)[0] ? $("."+parent) : ($(+parent)[0] ? $(parent) : null));
}

this.getParent = function()
{return this.parent;}

this.setData = function(data)
{this.data = data;}

this.buildTable = function()
{
    var dtTbl = [];
    dtTbl.push('
');

    var style;

    //Header//////////////////////
    dtTbl.push('
');
    for (var cell in this.data.row[0].cell) {
        dtTbl.push('' + this.data.row[0].cell[cell].id + '	');
    }
    dtTbl.push('
');
    //Content//////////////////////
    for(var r in this.data.row)
    {
        if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'"  onmouseout="this.className=\'r1\'"'; }
        else { style = 'class="r2" onmouseover="this.className=\'hover\'"  onmouseout="this.className=\'r2\'"'; }

        dtTbl.push('
');
        for(var c in this.data.row[r].cell)
        {
            dtTbl.push('' + this.data.row[r].cell[c].value + '	');
        }
        dtTbl.push('
');
    }
    //Footer//////////////////////
    dtTbl.push('
');
    for (var cell in this.data.row[0].cell) {
        dtTbl.push(' 	');
    }
    dtTbl.push('

');

    this.parent.html(dtTbl.join(''));
}

this.buildTableDiv = function()
{
    var tableString = [];
    //Header//////////////////////
    tableString.push('

');
    for (var cell in this.data.row[0].cell) {
        tableString.push('' + this.data.row[0].cell[cell].id + '	');
    }
    tableString.push('

');
    //Content//////////////////////
    tableString.push('

');
    var TD1 = new Object();
    var TD2 = new Object();

    for(var r in this.data.row)
    {
        if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'"  onmouseout="this.className=\'r1\'"'; }
        else { style = 'class="r2" onmouseover="this.className=\'hover\'"  onmouseout="this.className=\'r2\'"'; }

        for(var c in this.data.row[r].cell)
        {
            if(c == 0)
            {   if(TD1.value != this.data.row[r].cell[c].value){
                    TD1.value = this.data.row[r].cell[c].value;
                    TD1.show = true;
                }
                else
                    TD1.show = false;
            }
            if(c == 1)
            {   if(TD2.value != this.data.row[r].cell[c].value){
                    TD2.value = this.data.row[r].cell[c].value;
                    TD2.show = true;
                }
                else
                    TD2.show = false;
            }
            if(TD1.show && c == 0){//First line
                tableString.push('
');
                tableString.push('<input type="button" class="arrow_down" /> ' + this.data.row[r].cell[c].value + '	');
                for(var c = 0; c < this.data.row[r].cell.length - 1; c++)
                {
                    tableString.push('&nbsp	');
                }
                tableString.push('
');
            }
            else if(TD2.show && c == 1)//Second line
            {
                tableString.push('
');
                tableString.push(' 	' + this.data.row[r].cell[c].value + '	');
                for(var c = 0; c < this.data.row[r].cell.length - 2; c++)
                {
                    tableString.push('&nbsp	');
                }
                tableString.push('

 	 	');
            }
            else if(!TD2.show && c == 1)//third line (distincts second cells name)
            {
                tableString.push('
');
                tableString.push(' 	 	');
            }
            else if(c > 1)//Rest filling (not ordered stuff)
            {
                tableString.push('' + this.data.row[r].cell[c].value.replace(""," ") + '	');
            }
        }
        tableString.push('
');
        // $(".arrow_down").children(":nth-child(1)").click(function(){alert("test");});
    }
    tableString.push('

');
    //Footer//////////////////////
    tableString.push('

');
    for (var cell in this.data.row[0].cell) {
        tableString.push(' 	');
    }
    tableString.push('

');

    this.parent.html(tableString.join(''));

    // Setting width to all cells
    for (var i in this.data.row[0].cell)
    {
        cell = parseInt(i)+1;
        var h = this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
        var c = this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
        var f = this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
        var width = h > c ? h : (c > f ? c : f);

        this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
        this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
        this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
    }
    // this.activateScroller(0);
}

this.getScrollerWidth = function()
{
    var div = $('

');
     // Append our div, do our calculation and then remove it
    $('body').append(div);
    var w1 = $('div', div).innerWidth();
    div.css('overflow-y', 'scroll');
    var w2 = $('div', div).innerWidth();
    $(div).remove();
    return (w1 - w2);
}

this.activateScroller = function(value)
{
    var d = [];
    d.push('

');

    this.parent.children(":first").children(".content").scrollTop(value);
}

expandParent = function()
{
    alert(this.parent);
}

};
i am kinda makig datagrid based on javascript. i am not allowed to use jQuery UI.
My datagrid is made from tables. now i try to add a button inside a td element like            User Name
The problem is that i cant access my function inside my class without making instance. is it even possible to do that without making an instance?

A: Once your html is generated using your generateHTML function, the handler for onclick on div looses context of what "this" is. To be more specific, this in onclick handler for div refers to that div node in DOM.
To access getWidth method you have to make it available to global context or (better solution) do something like this:
// new version of your generateHTML function
this.generateHTML() {
   var str = [];
   str.push('
<input type="button" value="button"/>
');
   var that = this;
   $("#testDiv").append(str.join('')).find('button:first').click(function() {that.getWidth()});
}

EDIT:
To further explain how code above works, here's simplified example with comments.
Test = function() {
    this.generate = function() {
        var newnode = $('<button>click me</button>');
        $("body").append(newnode);
        // "cache" this in a variable - that variable will be usable in event handler
        var that = this;
        // write event handler function here - it will have access to your methods by using "that" variable
        newnode.click(function(e) {
            // here this refers to button not Test class
            // so we have to "reach" to outer context to gain access to all methods from Test
            that.doSomething('learn');
        })
    }
    this.doSomething = function(x) {
        alert('do it: '+x);
    }
}

// initialize part
// make instance of Test "class"
t = new Test();
// generate the button (clicking on a button will essentialy fire Test.doSomething function in a context of "t"
t.generate();


text:
Q: Android version 9 DatePickerDialog dateset issue My Android native application was working fine on older versions before 9. But, now on 9 on selecting date with SimpleDateFormat("MMM dd, yyyy");  date is selected as Jan. 07 , 2020  I don't understand from where a . is added after Jan which results in following error from service
java.text.ParseException: Unparseable date: "Jan. 07, 2020"

My android code
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, monthOfYear);
            cal.set(Calendar.DATE, dayOfMonth);
            mEditTextDate.setText(getDateFormat(context).format(
                    cal.getTime()));
        }
    };

public DateFormat getDateFormat(Context context) {
        if (dateF == null)
            dateF = new SimpleDateFormat("MMM dd, yyyy");
        return dateF;
    }

I am testing on Samsung Galaxy Tablet S6. I also tried changing Settings-->GeneralManagement --> Date and Time to Automatic date and time. But same code is working on all other tablets with MMM dd, yyyy format

A: You should use Locale.ENGLISH to get your desired date. Try below:
dateF = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH);


text:
Q: How do i join two tables in a database using MySQL with specific names I have a movies database using mysql in xampp.
It has 3 tables
movies(movieid(PK), title, rating, genre, release_date),
actors(actorid(PK), firstname,lastname,gender, date_of_birth), and actorsmovies(actorid(PK),movieid(pk).
I have to Display all fields from the movies where Michael J. Fox is the actor. How do i join the two tables that will show me only movies michael j fox was in? the actorsmovies has constraints on it.
example: Ive tried a million combinations but this is an example
select firstname,lastname,title from actors where firstname,lastname = 'Michael J','Fox' join actorsmovies on actors.actorid = actorsmovies.actorid join movies on actorsmovies.movieid = movies.movieid;

A: You have
select firstname,lastname,title
from actors
  where firstname,lastname = 'Michael J','Fox'
join actorsmovies
  on actors.actorid = actorsmovies.actorid
join movies on actorsmovies.movieid = movies.movieid;

and you need
select firstname,lastname,title
from actors
join actorsmovies
  on actors.actorid = actorsmovies.actorid
join movies on actorsmovies.movieid = movies.movieid
where firstname = 'Michael J' and lastname 'Fox';

Simply put, the where clause has to be after the joins and before an order by group by and having.  I also recommend being more explicit on your where clause and spelling out the and just for readability.
Now if your joins where outer joins you may need to mvoe the limit to the critiera
say in this example you want all movies and you want to "hilight" the ones with michael J fox...  the right join here returnss all the movies titles and firstname,lastname will not be blank when it's michael J. Fox. otherwise it will be blank!
select firstname,lastname,title
from actors
join actorsmovies
  on actors.actorid = actorsmovies.actorid
and actors.firstname = 'Michael J' and actors.lastname 'Fox';
right join movies on actorsmovies.movieid = movies.movieid;


text:
Q: Hacking Vertical Scroll into Horizontal Scroll I know this goes against every usability rule in the book, but does anyone have any ideas for forcing a vertical scroll to scroll horizontally?
So if:
The user was viewing the page, and scrolled downwards, the page would scroll horizontally?
Thanks!

A: With all respect, this sounds like a very strange thing to do and my preliminary tests show that it can be done, but the result is practically useless. Try this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>Scrolling test</title>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur tincidunt dictum rhoncus. Phasellus nulla nulla, facilisis eu aliquam aliquet, mattis pulvinar purus.

Since the scrolling is on the actual browser window itself it seems like it's not possible to capture the scrolling event and prevent it from propagating. I tried this using jQuery (event.stopPropagation) and it didn't work. So insted I resorted to adding top padding to the body to create the illusion that no vertical scrolling has occured. I can't see this being used in a live environment though since the result is horrible. :-)
Nevertheless, it was a fun thing to explore!
Regards,
Thomas Kahn

A: If anyone still wants to know. I wanted to do the same, and this worked for me, using multiple divs, position fixed and some JavaScript code.
HTML:

CSS:
#first {
    overflow:hidden;
    height:9000px;
}
#second {
    width:9000px;
    position:fixed;
}

JS:
window.onscroll=function() {
    var scroll = window.scrollY;
    $('#second').css('left', '-' + scroll + 'px');
}

Created a little fiddle:
http://jsfiddle.net/zfBhK/


text:
Q: How auth.getCurrentUser() works in firebase? I am not understanding how Auth.getCurrentUser() work? Specifically i want to know

*

*Where this current user is stored? Auth.getCurrentUser() gets user from local device or from firebase?

*If Current User is stored on firebase then how come this is resolved for my application? Because there might be hundreds of user in firebase logged into a particular application?

*If i make a call to some rest api on server and if i need to authenticate first before making rest call , should i call Auth.getCurrentUser or i should store all information in shared preference and use that everytime?

A:
Where this current user is stored? Auth.getCurrentUser() gets user from local device or from firebase?

After you sign the user in, the FirebaseUser is stored in Firebase and cached locally. To force refresh use FirebaseUser.reload(). You shouldn't need to do this manually, read further.

If Current User is stored on firebase then how come this is resolved for my application? Because there might be hundreds of user in firebase logged into a particular application?

You may be signed in automatically in Firebase UI using Smart Lock. This can be adjusted:
startActivityForResult(
    AuthUI.getInstance()
        .createSignInIntentBuilder()
        .setIsSmartLockEnabled(false /* credentials */, true /* hints */)
        .build(),
    RC_SIGN_IN);

If i make a call to some rest api on server and if i need to authenticate first before making rest call , should i call Auth.getCurrentUser or i should store all information in shared preference and use that everytime?

It's already cached locally, use getCurrentUser. If the operation fails because the token is expired, use FirebaseUser.getIdToken(forceRefresh = true) to get a fresh token or fail

[...] if the current user's account has been disabled, deleted, or its credentials are no longer valid

If that happens, you should treat the user as signed out and re-authenticate them.


text:
Q: Proving $\lvert\frac{z}{\lvert z\rvert}-1\lvert\leq\rvert Arg(z)\rvert$ I need some help with the following problem:

Let $0\neq z\in\mathbb{C}$, prove $\lvert\frac{z}{\lvert z\rvert}-1\lvert\leq\rvert Arg(z)\rvert$

where we take the argument to be in $\left(-\frac{\pi}{2},\frac{\pi}{2}\right]$.
What I did:
I say that it is clear that it sufficient to prove that if $z'$ is
on the unit circle then $|z'-1|\leq|Arg(\alpha z)|$ where $0\neq\alpha\in\mathbb{R}$.
Since if $0\neq\alpha\in\mathbb{R}$ then $Arg(\alpha z)=Arg(z)$
we need to prove that $|z'-1|\leq|Arg(z)|$.
Now, let $a,b\in\mathbb{R}$s.t $z'=a+bi$ then $\sqrt{a^{2}+b^{2}}=1$
and we need to prove that $\sqrt{(a-1)^{2}+b^{2}}\leq|Arg(z')|$.
This is where I am stuck, can someone please provide a hint ? am I
even on the right track ?

A: $z = r e^{i\theta}$. Then you want to prove that
$$\left \vert e^{i \theta} - 1\right \vert \leq \theta$$
$$e^{i \theta} - 1 = \cos(\theta) + i \sin(\theta) - 1 = -2\sin^2(\theta/2) + 2i \sin(\theta/2) \cos(\theta/2) = 2i \sin(\theta/2) e^{i \theta/2}$$

Hence, $$\vert e^{i \theta} - 1 \vert  = 2 \left \vert \sin(\theta/2) \right \vert \leq 2 \times \left \vert \theta/2 \right \vert= \left \vert \theta \right \vert$$


text:
Q: Change the opacity on a fraction of each stacked geom_bar Using the following data frame I aim to stack all x values by group using geom_bar or geom_col and fill them by subgroup.
 dat <- data.frame(group = c(rep("H", 4), rep("T",4)), subgroup = rep(c("A", "B", "C", "D"), 2),
               x = c(100, 10, 80, 50, 40, 50, 80, 70),
               y = c(20, 5, 50, 20, 20, 10, 40, 50))

But I also want to fill each stacked x value with their corresponding y value. However when I use the following code I get the following bar plot.
 dat %>%
   ggplot(aes(x = group, y = x, fill = subgroup)) +
   geom_col(alpha = .5) +
   geom_col(aes(x = group, y = y, fill = subgroup), alpha = 1)

Can anyone help me to fill a fraction of each subgroup with the y values please? All I have been able to get is an overlapped stack of y values, but not mapped to each color.
I have tried grouping the values and adding a key. however I am stuck with the previous plot

A: You will need to use geom_rect for this.
If I may put in my 2 cents worth: The result is a fairly clattered visual. I think there might be other options out there to show your fractions. I think my favoured way would to use facets. This is not only making the fraction idea much clearer, and way more intuitive, but is also way simpler to code. See below
library(tidyverse)
dat <- data.frame(group = c(rep("H", 4), rep("T",4)), subgroup = rep(c("A", "B", "C", "D"), 2),
                  x = c(100, 10, 80, 50, 40, 50, 80, 70),
                  y = c(20, 5, 50, 20, 20, 10, 40, 50))
## width for rects
w <- .45
dat %>%
  ## because it is stacking in reverse alphbetic order
  arrange(group, desc(subgroup)) %>%
  group_by(group) %>%
  mutate(frac_ymin = lag(cumsum(x), default = 0),
         frac_ymax = frac_ymin + y,
         ## group needs to be numeric for geom_rect
         group = as.integer(factor(group, levels = c("H", "T")))) %>%
  ggplot(aes(x = group, y = x, fill = subgroup)) +
  geom_col(alpha = .5) +
## now use geom_rect instead
  geom_rect(aes(xmin = group - w, xmax = group + w,
               ymin = frac_ymin, ymax = frac_ymax,
               fill = subgroup), alpha = 1)

Suggestion to use facets instead
library(tidyverse)
dat <- data.frame(group = c(rep("H", 4), rep("T",4)), subgroup = rep(c("A", "B", "C", "D"), 2),
                  x = c(100, 10, 80, 50, 40, 50, 80, 70),
                  y = c(20, 5, 50, 20, 20, 10, 40, 50))

## you can use your old code, just add a facet!
dat %>%
  ggplot(aes(x = group, y = x, fill = subgroup)) +
  geom_col(alpha = .5) +
  geom_col(aes(x = group, y = y, fill = subgroup), alpha = 1) +
  facet_wrap(~subgroup)


text:
Q: Accessing the same view controller in a Storyboard by a subclass Hullo,
I would like to create a new target for a project without overcrowding the main view controller with #ifdef's. So I am thinking of splitting its functions with a weaker superclass and have the new target use the top one. How do I configure the new target to attach the top view controller to the view controller in the storyboard instead of the bottom one as in the old target?

A: You would have to invoke and set the view controller manually like so:
    UIStoryboard *storyboard = [UIApplication sharedApplication].keyWindow.rootViewController.storyboard;
    UIViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"yourViewControllerIdentifier"];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:myViewController animated:YES completion:nil];


text:
Q: What is the best way to fully clear a DOM element for use in a pool? I am considering using object pooling of DOM nodes. When a DOM node is done being used, it would be put into a pool. I have something like this currently.
function removeNativeElement(virtualElement, store) {
  let stack = [virtualElement]
  let els = []
  while (stack.length) {
    const node = stack.shift()
    const el = node.nativeElement
    // remove from parent
    el.parentNode.removeChild(el)
    // remove event listeners
    node.handlers.forEach(({ type, handler }) => {
      el.removeEventListener(type, handler)
    })
    el.children.forEach(child => {
      stack.push(child)
    })
    els.push(el)
  }
  els.forEach(el => {
    // clear out any remaining text
    el.innerHTML = ''
    addNativeElementToPool(el)
  })
}

function addNativeElementToPool(el, store) {
  const pool = store.pool[el.tagName] = store.pool[el.tagName] || []
  if (pool.length > store.maxPoolSize) {
    return
  }
  pool.push(el)
}

But what about resetting the attributes and style properties, in an efficient way, how do you do that? The goal is to make putting object into a pool not be overburdeningly expensive.


text:
Q: AngularJS use variable in ng-* statements I use AngularJS 1.5, and I want to use ng-repeat to build a form.
Now, I have in my code :

      Label 1 required
     <input type="text" class="form-control" ng-model="model.field1" ng-required="currentStep == 2" ng-blur="function1()">
     Field required !

      Label 2 not required
     <input type="text" class="form-control" ng-model="model.field2">

 ....

I want to use an array to buid my form like that :
$scope.myForm= [{
    'type': 'text',
    'name': 'field1',
    'required': true,
    'label': 'My field 1',
    'ng': [{'ng-blur': 'function1'}]
}, {
    'type': 'text',
    'name': 'field2',
    'required': false,
    'label': 'My field 2',
}];

So I tried something like that :

    {{ field.label }}
    <input type="text" class="form-control" name="{{ field.name }}" ng-model="adherent.{{ field.name }}" ng-required="currentStep == 2">
    Field required !

But of course I got a syntax error... Do I have to create a directive ? or to use ng-init ?

A: You could use a different object-syntax for your ng-model. This should do the job:
ng-model="adherent[field.name]"

A: Do not use ngInit!!! It has two very specific uses and really shouldn't be used for anything else: have a look.
You actually have some syntax errors:
Missing second opening curly brace:
class="form-group {field.name}}"

Also, I'm pretty sure this is not going to work:
ng-class="{'has-error': Form.{{ field.name }}.$dirty ...

ngClass is not setup to do interpolation in the way you are trying to use it. You are basically writing this:
ng-class="{'has-error': Form."exampleFieldName".$dirty

And that is never going to work.
You are better off writing a directive or a component and using ng-repeat with that. Using this approach makes way more sense and is much easier to implement. Ultimately you want something like this:
$scope.myForm= [{
  'type': 'text',
  'name': 'field1',
  'required': true,
  'label': 'My field 1',
  'ng': [{'ng-blur': 'function1'}],
  model: {}
}, {
  'type': 'text',
  'name': 'field2',
  'required': false,
  'label': 'My field 2',
  model: {}
}];

<my-form-field field="field" ng-model="field.model" ng-repeat="field in myForm"></my-form-field>

See how easy that is to write and read? About actually writing the directive/component... that could prove to be quite a challenge. I'm sure if you do some Google-ing you will find someone that has written a blog on this exact subject.


text:
Q: Only add to List if there is a match I have a file that I am importing to a RTB:
// Some Title
// Some Author
// Created on
// Created by
//

Format:
 "Text Length" : 500 lines
 "Page Length" : 20 pages

Component: 123456
 "Name" : Little Red Riding Hood
 "Body Length" : 13515 lines
 ........etc // can have any number of lines under 'Component: 123456'

Component: abcd
 "Name" : Some other Text
 "Body Length" : 12 lines
 ........etc // can have any number of lines under 'Component: abcd'

... etc, etc  // This can occur thousands of times as this file has an unset length.

Now what is happening is the values are being stored from Component: 123456 until it reaches the next Component (which happens to be abcd) into the List<string> position 0.  The next one will be in position 1.. and so on until the entire file is read.
Using the code below, I am able to do the above problem:
string[] splitDataBaseLines = dataBase2FileRTB.Text.Split('\n');
StringBuilder builder = null;
var components = new List<string>();
foreach (var line in splitDataBaseLines)
{
    if (line.StartsWith("Component : "))
    {
        if (builder != null)
        {
            components.Add(builder.ToString());
            builder = new StringBuilder();
        }
        builder = new StringBuilder();
    }
    if (builder != null)
    {
        builder.Append(line);
        builder.Append("\r\n");
    }
}
if (builder != null)
    components.Add(builder.ToString());

However, now that this is working properly I need to manipulate this code to only add it to the components List if there is a match from a different list.
In order to find out if the line matches so I can add it to the components list I need to split the beginning line above. I am doing this by adding this code:
string partNumberMatch;

if (line.StartsWith("Component : "))
{
    partNumberMatch = line.Split(':');
    if (builder != null)
    {
    //....
}

Now that I have the Component number/string I need to compare that to another list... I was thinking about doing something like:
foreach (var item in theOtherList)
{
    if (item.PartNumber.ToUpper().Equals(partNumberMatch[1]))
}

But I do not think this is the best way or if this way actually works properly..
So my question is, can someone help me compare these two strings to see if they match and only add the Component values to the component List if the item was matched.
Special thanks to Jon Skeet

A: This is what I came up with to get it to work:
StreamWriter sw2 = new StreamWriter(saveFile2.FileName);
Boolean partMatch = false;
Boolean isAMatch = false;
List<string> newLines = new List<string>();
string[] splitDataBaseLines = dataBase2FileRTB.Text.Split('\n');

foreach (var item in theOtherList)
{
    foreach (var line in splitDataBaseLines)
    {
        if (line.StartsWith("Component : "))
        {
            partNumberMatch = line.Split(':');
            partNumberMatch[1] = partNumberMatch[1].Remove(0,2);
            partNumberMatch[1] = partNumberMatch[1].TrimEnd('"');

            if (partNumberMatch[1].Equals(item.PartNumber))
            {
                isAMatch = true;
                sw2.WriteLine();
            }

            partMatch = true;
        }

        if (line.Equals(""))
        {
            partMatch = false;
            isAMatch = false;
        }

        if (partMatch == true && isAMatch == true)
            sw2.WriteLine(line);
    }
}
sw2.Close();


text:
Q: parameter value lost (seam framework) After clicking on an image, the user is redirected to a new page like:
/viewPalermoUser.seam?accountId=100245

with the code:
<s:link title="#{messages['palermo.userlist.view']}" view="/portal/custom/palermo/administration/viewPalermoUser.xhtml"
                            propagation="none">
                        <f:param name="accountId" value="#{account.id}"/>
                        <img src="/static/portal/customer/palermo/find.png" style="border:none"/>
                    </s:link>

There is a backing bean where i take the account id and print the account information for that user (when the page is first rendered all it's ok).
BUT have a rich tab panel and a search button. Whenever i press one of this, the accountId value is NULL, although in the url it is the OK, so it has a real value.
I do not understand why the accountId's value is lost if a postback occurs?
I take the accountId like:
@RequestParameter
private Long accountId;

Can anyone give me a clue?
UPDATE: Finally it works. Use page param like Petar suggested. Had problems until i realized that:
A seam page param is not available in @Create method of the backing bean. Workaround: create a page action to use this param. (must be usefull for others)
Thanks.

A: As far as I know, @RequestParameter works only on an initial request. To solve the problem, you can use a Seam page parameter. Put in your page.xml descriptor the following tag:
<param name="accountId" value="#{backingBean.accountId}"/> You don't need the @RequestParameter annotation.

A: After clicking on an image, the user is redirected to a new page - I suppose it is called /viewPalermoUser.xhtml
First of all, a simple request parameter does not survive a postback.
To solve your problem, you can create a page parameter
<page view-id="/viewPalermoUser.xhtml">
    <param name="courseId" value="#{courseHome.courseId}"/>
</page>

So when Seam notices
<param name="courseId" value="#{courseHome.courseId}"/>

It creates a page parameter and because of value attribute (not required), it is assigned to courseHome.courseId property. Page parameter survives JSF postback.
If you want accountId survive a postback in s:link (or s:button), you have to create a page parameter in the view-id that matchs s:link view="/portal/custom/palermo/administration/viewPalermoUser.xhtml" attribute
So we need
<page view-id="/portal/custom/palermo/administration/viewPalermoUser.xhtml">
    <param name="courseId"/>
</page>

When using page parameter, you do not have to worry about f:param. s:link takes care of it. So your accoutId page parameter is automatically appended to the link.
<s:link title="#{messages['palermo.userlist.view']}" view="/portal/custom/palermo/administration/viewPalermoUser.xhtml"/>

regards,


text:
Q: Проектирование API и наследование интерфейсов Скорее всего, это достаточно глупый вопрос, но произошел глобальный "затык".
Итак: необходимо реализовать API и имплементацию подсистемы для большого проекта. Задача подсистемы - реализация синхронизации нескольких наборов данных разными способами (через веб/flash и, возможно, в будущем чего то еще).
При проектировании был выделен общий набор методов. Соответственно, пишем базовый интерфейс:
public interface IBase
{
   void A1();
   void A2();
   void A3();
}

Далее для каждого способа синхронизации были спроектированы свои интерфейсы:
public interface IDerived1 : IBase
{
   void B();
}

public interface IDerived2 : IBase
{
   void B();
   void C();
}

Для работы с API реализована фабрика:
public static class Factory
{
   public static IBase CreateDerived1() { ... }
   public static IBase CreateDerived2() { ... }
}

Соответственно, необходимо разделить имплементацию базового и дочерних интерфейсов так, что работая с объектом IBase, созданным с помощью фабрики, обращаться к методам, реализованным по-разному в зависимости от имплементации дочерних интерфейсов.
Как правильно это реализовать?

A: Я может чего-то недопонимаю,
class Derived1: IDerived1{ ... }
class Derived2: IDerived2{ ... }

public static class Factory
{
   public static IBase CreateDerived1()
   {
       return new Derived1();
   }
   public static IBase CreateDerived2()
   {
       return new Derived2();
   }
}

Получили два класса с разной реализацией и разные фабричные методы для создания объектов
IBase parent = Factory.CreateDerived1();
// вызовется реализация из Derived1
parent.A1();
parent = Factory.CreateDerived2();
// вызовется реализация из Derived2
parent.A1();

Использовали это дело.
Я всё правильно понял?

A: Если Вы хотите после создания объекта обращаться к методам B() и C(), которых в IBase нет, то что Вам мешает сделать так:
public static class Factory
{
    public static IDerived1 CreateDerived1() { ... }
    public static IDerived2 CreateDerived2() { ... }
}

?
У Вас ведь даже и методы названы соответственно.