Q:

What is the plain R equivalent of an aggregation sqldf query?

What is the plain R equivalent command of the following sqldf query"
test <- sqldf("SELECT *, SUM(value) FROM dataFrame GROUP BY run")

I try something like:
test <-aggregate(dataFrame$value, by=list(dataFrame$run), FUN=sum, na.rm=TRUE)

but somehow the SUM happens on each column of dataFrame

A:

As we discussed in the comments, the sqldf commands get the sum of the 'value' column grouped by 'run' along with the last observation other columns (if any) for each 'run'.
library(sqldf)
sqldf("SELECT *, SUM(value) FROM dataFrame GROUP BY run")
#  run        value    value2 SUM(value)
#1   a -0.848370044 0.2387489 -0.1627249
#2   b  0.002311942 0.3688175 -0.6826107
#3   c -1.316908124        NA -0.3993579

To get similar output with aggregate, you may try two aggregates.  First, to get the sum of the 'value' and second for the last observation per group.  If there are NA values, specify na.rm=TRUE argument of sum as well as the na.action=NULL from the aggregate.  The default option in aggregate is na.action=na.omit, which can remove a complete row from calculation if there is any 'NA' values.
d1 <- aggregate(value~run, dataFrame, FUN=sum, na.rm=TRUE, na.action=NULL)
d2 <- aggregate(.~run, dataFrame, tail,1, na.action=NULL)

and merge by 'run'
merge(d1, d2, by='run')
#  run    value.x      value.y    value2
#1   a -0.1627249 -0.848370044 0.2387489
#2   b -0.6826107  0.002311942 0.3688175
#3   c -0.3993579 -1.316908124        NA

Or using data.table
library(data.table)
setDT(dataFrame)[,c(.SD[.N], SUMVALUE=sum(value, na.rm=TRUE)) , run]
#   run        value    value2   SUMVALUE
#1:   a -0.848370044 0.2387489 -0.1627249
#2:   b  0.002311942 0.3688175 -0.6826107
#3:   c -1.316908124        NA -0.3993579

Or with dplyr (thanks for @Frank)
library(dplyr)
dataFrame %>%
    group_by(run) %>%
    mutate(SUMVALUE=sum(value,na.rm=TRUE)) %>%
    slice(n())
#  run        value    value2   SUMVALUE
#1   a -0.848370044 0.2387489 -0.1627249
#2   b  0.002311942 0.3688175 -0.6826107
#3   c -1.316908124        NA -0.3993579

data
  set.seed(24)
  dataFrame <- data.frame(run=rep(letters[1:3], 4),
           value=c(NA,rnorm(11)), value2=c(runif(11), NA))


Q:

Excel formula to take string value from cell and sort its characters in alphabetical order

Can you please help me to make Excel formula that takes string value from cell and sorts its characters in alphabetical order?
Ex.
original cell value: 'BACR'
sorted characters cell: 'ABCR'

A:

This UDF will sort numbers and Text character by character:
Function sortletter(rng As Range)
    If rng.Count > 1 Then Exit Function
    Dim srtArr() As String
    Dim i&, j&, k&
    ReDim srtArr(1 To Len(rng))
    srtArr(1) = Mid(rng, 1, 1)
    For i = 2 To UBound(srtArr)
        For j = 1 To UBound(srtArr)
            If srtArr(j) = "" Then
                srtArr(j) = Mid(rng, i, 1)
                Exit For
            ElseIf IIf(Asc(Mid(rng, i, 1)) > 96, Asc(Mid(rng, i, 1)) - 32, Asc(Mid(rng, i, 1))) <= IIf(Asc(srtArr(j)) > 96, Asc(srtArr(j)) - 32, Asc(srtArr(j))) Then
                For k = UBound(srtArr) To j + 1 Step -1
                    srtArr(k) = srtArr(k - 1)
                Next k
                srtArr(j) = Mid(rng, i, 1)
                Exit For
            End If
        Next j
    Next i
    sortletter = Join(srtArr, "")
End Function

Put this is a module attached to the workbook, NOT in the worksheet or ThisWorkbook code.
Then it can be called like any other formula
=sortletter(A1)


Q:

Extracting Data from Expression>

Im having a little trouble about extracting some data from Expression<Func<,>>, and having more trouble explaining what i want.
So i have a rest API and im building a method that could work as WFC.
meaning that i will not be needing to call the rest api by url but.
Building an interface or some kind of wrapper and from that interface we could extract the rest api controller Name, method and parameters.
Ok let me show you how i have imagine it to work.

This is my controller interface

[Route(url: "api/")]
public interface IYoutubeController
{
    /// <summary>
    /// Get a collection of the searched youtube videos
    /// </summary>
    /// <param name="searchString"></param>
    /// <param name="pageSize"></param>
    /// <param name="relatedTo"></param>
    /// <param name="videoSearchType"></param>
    /// <returns></returns>
    [Route]
    YoutubeVideoCollection Search(string searchString, int pageSize = 50, string relatedTo = null, VideoSearchType videoSearchType = VideoSearchType.Videos);

    /// <summary>
    /// Get the playlist video contents
    /// </summary>
    /// <param name="playListId"></param>
    /// <returns></returns>
    [Route]
    List<YoutubeItem> Playlist(string playlistId);

    /// <summary>
    /// decrypted youtube video
    /// </summary>
    /// <param name="videoId"></param>
    /// <returns></returns>
    [Route(httpMethod: HttpMethod.POST)]
    Task<YoutubeVideoInfo> GetVideoAsync(string videoId);
}

This the controller Repository

public static class ControllerRepository
{
    public static async Task<P> Execute<P>(Expression<Func<IYoutubeController, P>> func)
    {
        return await HttpHelper.ExecuteAsync(func);
    }
}

Now i could simple call my method like this
 YoutubeVideoCollection test = await ControllerRepository.Execute(x => x.Search("Eminem"));

You can se that there is no method seach exist, its only a method in interface.
And here is a httphelper, in it exist PostAsync and GetAsync and also ExecuteAsync
 private static string baseUrl = "http://xxx"
 public static async Task<P> ExecuteAsync<T, P>(Expression<Func<IYoutubeController, P>> func)
    {
        var url= typeof(T).GetCustomAttribute<Route>()?.Url ?? ""; // eg api/
        var controller = typeof(T).Name; // eg IYoutubeContrller, will be renamed to youtube later on
        var method = // get the method from func P which is Search
        var parameters = // the parameter data from func which is Eminem
        var fullUrl= $"{baseUrl}/{url}/{controller}"
        // and here we do PostAsync<P>(fullUrl, parameters ) Or GetAsync<P>(fullUrl, parameters )
    }

In HttpHelper ExecuteAsync i want to retrive from my Func<T, P> the Method name which is Search and the parameter which is searchString and also the value of the parameter which is Eminem
Could you help me retrive these information from func parameter?
This is still an idee, so it may not really work, just let me know if its possible.

A:

For your very special case:
Execute(x => x.Search("Eminem"));

You could do this
public static async Task<P> ExecuteAsync<T, P>(Expression<Func<IYoutubeController, P>> func)
{
    MethodCallExpression callExpression = expression.Body as MethodCallExpression;
    string methodName = callExpression.Method.Name;
    object argument = ((ConstantExpression)callExpression.Arguments).Value;
    // do something
}

But of course this will crash if the expression passed to Execute is more complicated or uses calls with no arguments or non-constant expression arguments etc.
But in that case, you wouldn't know which information to extract at all.


Q:

I'd like to have play bar visible all the time but is only visible when hover

Hi I'd like to have play bar visible all the time but is only visible when hover, can somebody guide me where to modify the script thank you. I'm at the moment in college but they dont teach anything useful, so I have to do it on my own sorry english is not my language
    $("#equalizer audio")();

equalizer.hover(function(){
    $("#equalizer audio").fadeIn(400);
},function(){
    $("#equalizer audio").(400);
});

var i = 0;

$(".equalizer_bar").each(function(index) {

  for( var j=0;j<n_components_per_bar;j++)
  {

       $(this).append("

");

  }

  $(".equalizer_bar_component",this).reverseOrder();

  i++;
});

A:

Replace this:
$("#equalizer audio")();

equalizer.hover(function(){
    $("#equalizer audio").fadeIn(400);
},function(){
    $("#equalizer audio").(400);
});

with:
$("#equalizer audio").show();


Q:

How to ask for a bank account "upgrade"?

I have an existing account with an Austrian bank that provides for a certain level of annual turnover and with a certain kind of payment card. The bank also offers a "higher level" type of account that has higher limits and comes with a better, more universally accepted debit card.
I'm trying to write an email to the bank that contains the simple sentence "I would like to upgrade my account." But I am struggling to find an appropriate German verb for this kind of upgrade. Google Translate suggests "aktualisieren" which seems to imply "update" rather than "upgrade", e.g. bringing software up to the most recent version as opposed to consciously choosing a "better" version of something.
If I give Google the specific phrase "I would like to upgrade my bank account" then it suggests "aufwerten", but dictionary translations seem to suggest that this implies more of an "appreciation in value" rather than the sense I'm looking for.
Any suggestions for what would sound right to a native speaker? It's not the kind of thing one can tell the nuances of just by looking in a dictionary.

A:

I checked some german banks which offer an upgrade for their accounts. Clicking these links, you get a webpage with a more legal phrasing, where the bank itself uses the word "wechseln", so you could write in your e-mail something like this:

Ich möchte von meinem Basic-Konto zu Ihrem Premium-Kontomodell wechseln.

A:

Here is a simple solution, close to your English expression, but anyway valid even in more refined written communication:

Ich möchte gerne mein Konto zu einem xyz-Konto hochstufen.

Note however that it is advisabel to not dismiss the "zu einem xyz-Konto" part, as Ich möchte gerne mein Konto hochstufen would sound a little bit odd. (xyz is here used for the name of the new type of account.)
You may also say:

Ich möchte für mein Konto um eine Höherstufung (auf ein xyz-Konto) bitten.

In oral communciation, the most natural, non-formal way would probably be to not mention the direction of the shift (up) at all, and rather ask for the change as such:

Ich habe das Konto mit der Numer xxxxxxx bei Ihnen. Das ist derzeit ein abc-Konto. Könnten Sie das zu einem xyz-Konto machen?

A:

I can't say for sure how language conventions are in Austria but when writing to a German bank I would use the German loanword from English upgraden:

Ich möchte mein Basic-Konto zu einem Premium-Konto upgraden.


Q:

SAT, How Do I Find The Penetration Vector?

I've just successfully implemented Separating Axis Theorem (SAT) in my game but I was wondering how do I find the penetration vector? I heard it can be useful for collision response. e.g. The harder they collide the harder the response.
I want the penetration vector so I apply it to the position of an object when it is current penetrating an other so I can move it back outside of the other object's bounds.
Here is my code so far.
Any help would be much appreciated,
Thanks in advance.

A:

The classic way to do this is the GJK algorithm.  It's a fairly complicated algorithm with a lot of moving parts, so might be tricky to implement.  However, there are many implementations out there on the Web that you might be able to adapt.
A simpler way to get an approximate penetration vector might be to leverage the SAT itself; when you iterate over all the possible separating axes and check for overlap on each, keep track of which axis has the shortest overlap and use that as the penetration vector.


Q:

Update Navigation Properties with Entity Framework (MVC3 Razor)

I'm having trouble figuring out how to get my navigation property to update with the Entity Framework. I used a database first approach and set up all appropriate FK relationships. Here's what the two tables I'm working with look like:
Rate Profile

RateProfileID
ProfileName

Rate

RateID
RateProfileID (FK)
Several Other Properties I Want to Update

One RateProfile can/will have many Rates. I built my edit page for RateProfile to display editors for the RateProfile Entity and all of it's associated Rate entities and stuck all of that in a form with a submit button. I can display everything just fine, but my changes will only persist for the model class (RateProfile) and not for its navigation property (Rates).
Below are my views/HttpPost Edit/ Models
In my HttpPost Edit method, you can see my feeble attempt to loop through and Update each record in the navigation property Rates of the model.
@model  PDR.Models.RateProfile

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>RateProfile</legend>

    @Html.HiddenFor(model => model.RateProfileID)
    @Html.HiddenFor(model => model.LoginID)

        @Html.LabelFor(model => model.ProfileName)

        @Html.EditorFor(model => model.ProfileName)
        @Html.ValidationMessageFor(model => model.ProfileName)

        @Html.LabelFor(model => model.isDefault)

        @Html.EditorFor(model => model.isDefault)
        @Html.ValidationMessageFor(model => model.isDefault)

        <fieldset>
        <legend>Dime</legend>

                    Min

                    Max

                    Price

        @foreach (var rate in Model.Rates)
        {

                    @Html.EditorFor(modelItem => rate.minCount)

                    @Html.ValidationMessageFor(model => rate.minCount)

                    @Html.EditorFor(modelItem => rate.maxCount)
                    @Html.ValidationMessageFor(model => rate.maxCount)

                    @Html.EditorFor(modelItem => rate.Amount)
                    @Html.ValidationMessageFor(model => rate.Amount)

        }

    </fieldset>

        <input type="submit" value="Save" />

</fieldset>
}

[HttpPost]
    public ActionResult Edit(RateProfile rateprofile)
    {

        if (ModelState.IsValid)

        {
            db.Entry(rateprofile).State = EntityState.Modified;

            foreach (Rate rate in rateprofile.Rates)
            {
                db.Entry(rate).State = EntityState.Modified;
            }
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(rateprofile);
    }

public partial class Rate
{
    public int RateID { get; set; }
    public int RateProfileID { get; set; }
    public string Size { get; set; }
    public decimal Amount { get; set; }
    public int minCount { get; set; }
    public int maxCount { get; set; }
    public int PanelID { get; set; }

    public virtual Panel Panel { get; set; }
    public virtual RateProfile RateProfile { get; set; }
}

public partial class RateProfile
{
    public RateProfile()
    {
        this.Rates = new HashSet<Rate>();
    }

    public int RateProfileID { get; set; }
    public string ProfileName { get; set; }
    public int LoginID { get; set; }
    public bool isDefault { get; set; }

    public virtual Login Login { get; set; }
    public virtual ICollection<Rate> Rates { get; set; }
}

A:

You change the foreach into for statement and try whether the model binding is working fine or not.
@for (var int i = 0; i < Model.Rates; i++)
{

            @Html.EditorFor(modelItem => Model.Rates[i].minCount)
            @Html.ValidationMessageFor(model => Model.Rates[i].minCount)

            @Html.EditorFor(modelItem => Model.Rates[i].maxCount)
            @Html.ValidationMessageFor(model => Model.Rates[i].maxCount)

            @Html.EditorFor(modelItem => Model.Rates[i].Amount)
            @Html.ValidationMessageFor(model => Model.Rates[i].Amount)

}


Q:

What is the Q-construction, metaphysically?

An exact (small) category $P$ is an environment in which we make sense of the "put-together"-edness of objects via (short) exact sequences. It seems like the K-theory of an exact category encodes the high order relations of how objects fit together, but I can't see how the $Q$-construction is the natural medium for this.
$\bullet$ $0 \to B \to A \to C \to 0$ means that $A$ is put together in some way from $B$ and $C$. Letting $E$ denote the category of short exact sequences in $P$ (with obvious morphisms), we see that this holds in the large as well: If $p$ (resp. $q$) is the projection functor $E \to P$ that sends a s.e.s. to the first (resp. last) object in the sequence, then $(K_i(p), K_i(q)): K_i(E) \to K_i(P) \oplus K_i(P)$ is an isomorphism.
$\bullet$ Moreover, results like devissage, localisation, and resolution are also easily seen  to be reassurances that we are distilling a very sensible notion of put-together-edness.

Can anyone offer a (non-circular) reason as to why the Q-construction is right?

I don't see the sense or utility considering a category in which a morphism from $X$ to $Y$ is an isomorphism of $X$ with an (admissable) subquotient of $Y$.

A:

1)  One wants the $Q$-construction to have the property that $\pi_1(QP)=K_0(P)$.
2)  To get this, one wants, for any covering space of $BQP$, that $K_0(P)$ acts naturally on the fiber over $0$.
3)  To get this, one wants to associate to any monomorphism $i$ in $P$ a morphism $i_!$ in $QP$ and to any epimorphism $j$ in $P$ a morphism $j^!$ in $QP$ in a way that satisfies certain simple properties; the statement of the properties, and the proof that they suffice to get this result, is in Quillen's Algebraic K-Theory I (Theorem I).
4)  Quillen's $Q$-construction is the Universal construction yielding such $i_!$ and $j^!$.  (The proof is in QUillen's paper, immediately preceding Theorem 1.)
5)  Therefore, there's a sense in which Quillen's $Q$-construction is the natural first guess for what should work.  (Of course the "naturality" of this guess appears only in hindsight; a lot of other people failed to find this construction.)
PS.  After you work through the constructions, you see that this is another way to see the same thing:  For any object $A$ in your category $P$, you want to associate the $K_0$-class $[A]$ to some loop in $BQP$.  The simplest thing to hope for is two canonically defined maps from $0$ to $A$ in $QP$, which together give you your loop.  Quillen's construction provides those two maps (recognizing $0$ as a quotient of both $0\subset A$ and $A\subset A$) in the simplest possible way.

A:

There's an interesting motivation in the paper by G. Segal:
K-homology theory and algebraic K-theory. K-theory and operator algebras (Proc. Conf., Univ. Georgia, Athens, Ga., 1975), pp. 113–127. Lecture Notes in Math., Vol. 575, Springer, Berlin, 1977
It is well-known that the space of Fredholm operators gives a model for
topological K-theory $\Bbb Z \times BU$.
According to Segal, if $C$ is an exact category, a morphism of the Q-construction $QC$ is akin to a Fredholm operator.
So algebraic K-theory via the Q-construction mimics topological K-theory defined via Fredholm operators.


Q:

How to properly use structs inside a class?

Using:  VS2008, Win32, C/C++
I'm trying to encapsulate my entire dialog window into a class for reusability. Sort of like a custom control.  In doing this, I am moving my seperate functions into a class.  The following struct design though is giving me problems, with Visual Studio outputting: error C2334 '{'.
It's a simple message map layout.  But I can't seem to escape this C2334 error.   :(
Here is my class code snippet.
class CScrollingListDlg
{
private:

LRESULT DoCommandMain (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam);
LRESULT DoPaintMain   (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam);
LRESULT DoAnimationTimer (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam);
LRESULT DoHandleTouch (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam);
LRESULT DoDestroyMain (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam);

//
// message maps
//
// Generic defines and data types.
struct decodeUINT {
    UINT Code;
    LRESULT (*Fxn)(HWND, UINT, WPARAM, LPARAM);
};

struct decodeCMD {
    UINT Code;
    LRESULT (*Fxn)(HWND, WORD, HWND, WORD);
};

// WM_Message dispatch table for MainWndProc.

//
// ***  error C2334 '{'  ***
//
const struct decodeUINT MainMessages[] = {
    WM_PAINT,   DoPaintMain,
    WM_DESTROY, DoDestroyMain,
    WM_QUIT,    DoDestroyMain,
    WM_COMMAND, DoCommandMain,
};

};

What am I missing here?
Thanks.

A:

You can't initialize an array member inside a class declaration. You should only declare MainMessages, then initialize it in the constructors of the class.
I also recommend using std::vector instead of array. This way, decodeUINT declaration becomes:
std::vector<decodeUINT> MainMessages;

and in constructor, use std::vector::push_back method to insert content.
If you need access to the memory managed by the vector, use &MainMessages[0].

A:

You cannot specify initialisers for non-static members that way -- you would normally need to declare the array and then populate it inside the constructor...  Except that, in fact there is no way to initialise const member arrays in C++ (see this thread).
If you are prepared to share MainMessages amongst all instances of CScrollingListDlg (which I suspect was your intention all along), you should make it static, in which case you can declare:
static const decodeUINT MainMessages[];  // "struct" keyword unnecessary

inside the class definition of CScrollingListDlg, and then define it outside the class:
const CScrollingListDlg::decodeUINT CScrollingListDlg::MainMessages[] = {
    WM_PAINT,   DoPaintMain,
    WM_DESTROY, DoDestroyMain,
    WM_QUIT,    DoDestroyMain,
    WM_COMMAND, DoCommandMain,    // The comma *is* allowed -- thanks Josh!
};

In order for this to actually compile, you'll need to make DoPaintMain(), DoDestroyMain(), etc. static as well -- as it stands, they are all per-object methods that implicitly take a this pointer, so they can't actually be contained in a function pointer of type LRESULT (*Fxn)(HWND, UINT, WPARAM, LPARAM).  (You could leave them as non-static methods and change the pointer type in decodeUINT to a pointer-to-member-function type, but that's probably not what you want.)
[EDIT: Thanks to Josh for some helpful comments!]


Q:

Visual Studio 2015 Toolbox for Windows Form Application

I'm new in C++, I'm trying to create Windows Form Application, but toolbox doesn't works, so what I'm doing wrong.

"CLR Empty Project".
Windows Form (under UI).
Inside the CPP file:

#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;

    [STAThread]
    void main(array<String^>^ args)
    {
        Application::EnableVisualStyles();
        Application::SetCompatibleTextRenderingDefault(false);
        MYPROG::MyForm form;
        Application::Run(%form);
    }

In the Solution Explorer properties entry Point to "main"
SubSystem to "Windows (/SUBSYSTEM/WINDOWS)"
Build MYPROG
Open MyForm.h
Open toolbox, right click and press "Show All", to drug button on MyForm

But the tools does not works, looks like this
Can you help me figure out with this problem

A:

Probably your project is RUNNING. So STOP the project then your toolbar items will become "enabled".
If my guess was wrong. Then Right-Click on a toolbox item and Reset Toolbox. Then they will get "enabled".
Note that you may lose any custom controls you added.


Q:

Can someone explain the types of acceleration data (RAW, BODY, GROUND)? And how they differ from each other?

I am working with a research group and we are using acceleration to determine variables necessary for our work. But I am confused at the advatages and disadvanteages of each type of acceleration data. Under Enumeration Documentation I found three different types of acceleration data: RAW, GROUND, and BODY. I understand the different frames of reference for GROUND and BODY, but I am puzzled as to what RAW means. Can anyone give me an explanation of differences between these, and explain to me what acceleration raw is?
Thank you.

A:

The updated (08/15/2018) Telemetry API Reference includes information about frames of reference for each topic and also warns if there are non-standard frames involved. You can submit any issues you have with the docs on the documentation Github repo.


Q:

rails render partial after ajax get request

I use Jvectormap into my Rails 3 app.
When I click on it, I want to hide the map and visualize a partial with information about the selected country.
I handle the map click and I send a GET req to the server.
users.js.coffee.erb
$ ->
  $("#world-map").vectorMap
    onRegionClick: (event, code) ->
      $('#world-map').hide(1000)
      $.get('/users/statistics', {code: code});
      $('#statistics').show(1000)

users_controller.rb
def statistics
 @country = Country.find_by_two_letter_code((params[:code]).downcase)
 render :nothing => true

end
this is the response

Started GET "/users/statistics?code=ET" for 127.0.0.1 at 2013-06-02 17:54:49 +0200
Processing by UsersController#statistics as /
Parameters: {"code"=>"ET"}
Country Load (0.2ms)  SELECT "countries".* FROM "countries" WHERE
"countries"."two_letter_code" = 'et' LIMIT 1
Rendered text template (0.0ms)
Completed 200 OK in 2ms (Views: 0.6ms | ActiveRecord: 0.2ms)

and the view
show.html.erb

        <%= render partial:'statistics', :locals => {:country => @country}  %>

_statistics.html.erb
<%= link_to ''.html_safe%>
<%=country%>
<%=@country%>

Now, everything works, but the partial doesn't visualize the country value.
I don't undestand if I have to re-render the partial after the ajax get request, and how.
I've tried to change the controller in another way, but the behavior is the same.
def statistics
 @country = Country.find_by_two_letter_code((params[:code]).downcase)
 render 'users/_statistics'
end

A:

i think that since you don't need a page refresh and just need to display the details the country, you can use ajax.
show.html

in the controller
def statistics
  @country = Country.find_by_two_letter_code((params[:code]).downcase)
  respond_to do |format|
    format.js
  end
end

in statistics.js.haml #i am comfortable with haml.
$('#place_partial_here').replaceWith("#{escape_javascript(render partial: 'country_data', locals: {country: @country})}");

in the _country.html.haml
#place_partial_here #id is denoted in haml using hash
  = country.name #display country name
  = country.code #display code

the partial must have the view code 'inside' the id 'place_partial_here' so that it can be used in further ajax calls


Q:

How to make Simple Read-Only Output Log Console for WPF?

I have a WPF Application and I'd like to add a button that will open a Console window and display Console.WriteLine messages. It doesn't have to be a CMD Console, just a display box like an emulated one.
My idea was to create a Window, Console.xaml with a ScrollViewer/TextBox and redirect the WriteLine using something like this but I can't get it to work:
XAML
<ScrollViewer Name="Scroller" Margin="0" Background="#FF000128">
    <TextBlock Name="OutputBlock" Foreground="White" FontFamily="Consolas"/>
</ScrollViewer>

C#
System.Diagnostics.Debug.WriteLine("hello", console.OutputBlock.Text);

Constructor
public Console(MainWindow mainwindow)
{
    InitializeComponent();
    this.mainwindow = mainwindow;
}

An Example I made in Photoshop with made up log text

I tried this solution, but I'm not sure how to use it. I get an OnStartup "no suitable method found to override" error:
https://stackoverflow.com/a/10416069/6806643
I also tried this solution. I copy exact but it is filled with errors:
https://stackoverflow.com/a/14957478/6806643
This code gives no errors but I don't know how it's supposed to be used:
https://stackoverflow.com/a/3058921/6806643

A:

A very crude way I've come up using ScrollView TextBlock and Inlines.Add() instead of Console.WriteLine(), but it's doing what I need.
Create Window - LogConsole
XAML
<Grid>
    <ScrollViewer Name="Scroller" Margin="0" Background="#FF000128">
        <TextBlock Name="OutputBlock"  Foreground="White" FontFamily="Consolas" Padding="10"/>
    </ScrollViewer>
</Grid>

Enable Pass Data to LogConsole
private MainWindow mainwindow;

public LogConsole() {}

public LogConsole(MainWindow mainwindow)
{
    InitializeComponent();

    this.mainwindow = mainwindow;
}

// Hide Window instead of Exiting
protected override void OnClosing(CancelEventArgs e)
{
    this.Hide();
    e.Cancel = true;
    base.OnClosing(e);
}

MainWindow
Method - Start Log Console Hidden
public MainWindow()
{
    InitializeComponent();

    // Start the Log Console
    StartLogConsole();
}

// Method
public void StartLogConsole()
{
    MainWindow mainwindow = this;
    console = new LogConsole(mainwindow);
    // window position
    console.Left = this.Left + 0;
    console.Top = this.Top + 0;
    console.Hide();
}

LogConsole console = new LogConsole();

Open Log Console Button
private void buttonLogConsole_Click(object sender, RoutedEventArgs e)
{
    // window position
    console.Left = this.Left + 0;
    console.Top = this.Top + 0;
    console.Show();
}

Write Log Message to ScrollView TextBlock
// Log Console Message
console.OutputBlock.Inlines.Add("Starting Application...\n");

It logs at all time while running in the background and open/close without losing text.


Q:

Parsing big numbers in JSON to strings

I'm trying to tackle the issue with JSON.parse() rounding big numbers. I know why this is happening but am looking for away around it.
I was thinking a regex which could parse the JSON text and turn all the big ints into strings.
I'm using JavaScript in a Windows 8 app and its got to be dealt with client side.
Got me stumped so far.
The main issue is I have to do this after I receive the response from an XMLHTTPRequest and cant change the original format of the JSON
e.g
{ "data" : {
    "username":"Brad", "userID":941022167561310208, "location":"London"
    }
}

A:

Disclaimer:
This is an old answer, and the question is even older. You shouldn't ever be parsing JSON with regular expressions - it's too brittle of a solution, and is liable to break at random. The right way to do this is to parse the entire JSON string, then use code to convert string values to numbers, e.g. parseInt(jsonData.data.userID).
An even better way to do it is to fix it on your back-end so your client doesn't have to do this.

Here's the regex to wrap all integers with quotes. If you wanted to do this only for long strings, change + to {9,} (or any int).
var json = ('{"data":{"username":"Brad","userID":941022167561310208,"location":"London","test":"3908349804","test2":"This already exists in 034093049034 quotes"},"list":[3409823408,3409823408,"A list 234908234"]}');
json = json.replace(/([\[:])?(\d+)([,\}\]])/g, "$1\"$2\"$3");
json = JSON.parse(json);

See example: http://jsfiddle.net/remus/6YMYT/
Edit Updated to accommodate lists as well.
Here's the regex in action: http://regex101.com/r/qJ3mD2

A:

I know this is a very old question, but this is the solution you can use if you are using npm. Javascript can handle bigInt of value 9007199254740991 docs. You can use this npm package to parse JSON's containing large numbers.
Install your package
npm i json-bigint

Then use it like this.
var JSONbig = require('json-bigint');
let result = JSONbig.parse(<your-json>);

A:

If you need to use it as a string then just save it as a string, with "":
{ "data" : {
    "username":"Brad", "userID":"941022167561310208", "location":"London"
    }
}

You also have a misstake username => "username".
You can also parse it to integer with parseInt() later
For updated question: Then you need to surround your number with "" with regexp:
s='{"data":{"username":"Brad","userID":9410221675613105435234324235235235235235523208,"location":"London"}}';
s = s.replace(new RegExp('"userID":([0-9]+),',"g"),'"userID":"$1",')

example: http://jsfiddle.net/E4txx/


Q:

Specify the type of the output of a Calculator filter

It seems as though the result of a Calculator filter is always a double array. Is there a way to change this type? For example, if I create a Sphere Source, then use a Calculator filter with the following:
1*iHat + 2*jHat + 0*kHat

I get an array that could theoretically be used to color the points (i.e. it is interpretable as RGB 3-vectors), but it is of type 'double' so Paraview cannot use it for coloring (without color mapping).

A:

As of ParaView 5.1.2, and perhaps earlier versions, you can actually interpret 3-tuple arrays of doubles as colors the way you describe. Color values are specified in the range [0, 1] for double and float arrays instead of [0, 255] for unsigned char arrays.
To show these Calculator-defined colors without color mapping, color by the Calculator output array, then uncheck the option Map Scalars in the Properties panel.


Q:

ionic problem No 'Access-Control-Allow-Origin'

I'm working on an ionic apps.
My problem is: when I try to get data from server I got this:

XMLHttpRequest cannot load https://mywebsite.com/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

I already try to add this to .htaccess:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>

And this to my api page (PHP): header('Access-Control-Allow-Origin: *');
but still not working
$http.get(url).success(function(response) {...}

A:

Put it on top of your PHP file like:
<?php
header("Access-Control-Allow-Origin: *");
// then your stuff goes here

?>

Note: as with all uses of the PHP header function, this must be before any output has been sent from the server.

A:

This cors problem has a simple work around in ionic.
Go to your ionic.config.json (previously ionic.project) and add a proxy for example:
{
  "name": "proxy-example",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://cors.api.com/api"
    }
  ]
}

After that use "/api/" instead of "https://mywebsite.com/api" when you call your api.
For more info:
http://blog.ionic.io/handling-cors-issues-in-ionic/


Q:

Filesystem errors when restoring many files

I had an external hard drive that I mounted internally.  It came formatted with NTFS, and I wanted to move to ext4.  So I copied everything I wanted to keep onto other drives, created a brand new partition table (GPT) with a single ext4 partition, and now I'm trying to copy everything back.  I'm using rsync -a --info=progress2 for most of the copy operations.
My problem is that after 100 GB or so, I tend to get weird errors:

rsync: write failed on "somepath": Read-only file system (30)
rsync error: error in file IO (code 11) at receiver.c(389) [receiver=3.1.0]

If I try to list the directory that rsync was working on when it failed, I see weird results:

drwx------  3 pdaddy pdaddy 4096 Aug 28 2011 subdirectory1
drwx------  3 pdaddy pdaddy 4096 Mar 12 2014 subdirectory2
d?????????  ? ?      ?         ?           ? subdirectory3
d?????????  ? ?      ?         ?           ? subdirectory4

Trying to list the directories with question marks in their listings, and even some of them without, gives me:

ls: reading directory subdirectory3: Input/output error
total 0

Even fdisk has errors:

~ % fdisk /dev/sde
fdisk: unable to read /dev/sde: Input/output error

If I try to unmount the drive, the umount command hangs.  I ran htop and saw that umount was using 100% of one CPU core.  I assumed it was committing journals or some such, so I let it go all night once, but it was in the same state in the morning.  Issuing sudo reboot or sudo init 6 while umount is hung results in yet another hung terminal.  I have to hold the power button.  Just now I tried rebooting without explicitly unmounting, and it hung with a black screen (the monitor went to sleep), and no response via ssh or the keyboard.
After a hard power cycle, I unmounted the disk and did sudo fsck.ext4 -f /dev/sde1, and there were no errors.  I checked the files, and they seemed to all be there and a sample of them were correct.
I assumed the errors had something to do with the journal being too large (maybe it's limited to a maximum size?), so I remounted with -o data=writeback.  I figured it's a good idea anyway to mount this way temporarily while restoring terabytes worth of files.
This helped to marginally speed the copy, but did not help with the errors.  Twice more, I've gotten into the same state.  A hard power cycle is the only thing I can do, and afterward, a disk check shows no errors, the files seem okay, and I can copy another 100 GB or so.
What's going on?  I think the disk itself is healthy.  I had no problems with it before reformatting.  Should I do a sector scan on the disk?  It's 5 TB, so I'm hesitant to do that.

I've restored some more files, watching the kernel logs, as suggested by Stephen Kitt.  Before rsync failed, I started seeing some funky errors:

[ 8807.572286] ata4.00: exception Emask 0x0 SAct 0x7fffffff SErr 0x0 action 0x6 frozen
[ 8807.572290] ata4.00: failed command: WRITE FPDMA QUEUED
[ 8807.572293] ata4.00: cmd 61/40:00:c0:57:b6/05:00:b7:00:00/40 tag 0 ncq 688128 out
[ 8807.572293]          res 40/00:00:00:4f:c2/00:00:00:00:00/40 Emask 0x4 (timeout)
[ 8807.572295] ata4.00: status: { DRDY }

The last three messages repeat many times, then I get:

[ 8807.572412] ata4: hard resetting link
[ 8808.060464] ata4: SATA link up 3.0 Gbps (SStatus 123 SControl 300)
[ 8808.062462] ata4.00: configured for UDMA/133
[ 8808.076459] ata4.00: device reported invalid CHS sector 0

The last message repeats 20 times or so, and then I get:

[ 8808.076526] ata4: EH complete

47 seconds later, the sequence repeats itself.  And again 81 seconds after that, and 120 seconds after that, except this time, it starts with:

[ 9160.779935] ata4.00: NCQ disabled due to excessive errors

The next time, it's different.  It starts the same, but then I see:

[ 9235.819291] ata4: hard resetting link
[ 9241.181501] ata4: link is slow to respond, please be patient (ready=0)
[ 9245.839449] ata4: COMRESET failed (errno=-16)

This repeats a couple of times, and then:

[ 9290.922301] ata4: limiting SATA link speed to 1.5 Gbps
[ 9290.922303] ata4: hard resetting link
[ 9295.948393] ata4: COMRESET failed (errno=-16)
[ 9295.948400] ata4: reset failed, giving up
[ 9295.948401] ata4.00: disabled

There are some new errors:

[ 9295.948522] sd 3:0:0:0: [sdf] FAILED Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK
[ 9295.948524] sd 3:0:0:0: [sdf] CDB:
[ 9295.948525] Write(16): 8a 00 00 00 00 00 b9 0c fd 00 00 00 40 00 00 00
[ 9295.948538] blk_update_request: I/O error, dev sdf, sector 3104636160
[ 9295.948542] EXT4-fs warning (device sdf1): ext4_end_bio:317: I/O error -5 writing to inode 49807774 (offset 155189248 size 4194304 starting block 388079688)
[ 9295.948543] Buffer I/O error on device sdf1, logical block 388079264

(Note that I've shuffled some drives since I started this post, and this drive is now sdf instead of sde.)
This last error repeats several times with different logical blocks, and then I get this an equal number of times:

[ 9295.948585] EXT4-fs warning (device sdf1): ext4_end_bio:317: I/O error -5 writing to inode 49807774 (offset 155189248 size 4194304 starting block 388079856)

There's more of the same, and all the while the copy is still going on without complaining.  Finally I get:

[ 9295.950321] Aborting journal on device sdf1-8.
[ 9295.950345] Buffer I/O error on dev sdf1, logical block 610304000, lost sync page write
[ 9295.950361] EXT4-fs (sdf1): Delayed block allocation failed for inode 49807775 at logical offset 0 with max blocks 1024 with error 30
[ 9295.950362] Buffer I/O error on dev sdf1, logical block 0, lost sync page write
[ 9295.950365] EXT4-fs (sdf1): This should not happen!! Data will be lost
[ 9295.950365]
[ 9295.950366] EXT4-fs error (device sdf1) in ext4_writepages:2421: Journal has aborted
[ 9295.950368] EXT4-fs error (device sdf1): ext4_journal_check_start:56: Detected aborted journal
[ 9295.950370] JBD2: Error -5 detected when updating journal superblock for sdf1-8.
[ 9295.950371] EXT4-fs (sdf1): Remounting filesystem read-only
[ 9295.950372] EXT4-fs (sdf1): previous I/O error to superblock detected
[ 9295.950379] Buffer I/O error on dev sdf1, logical block 0, lost sync page write
[ 9295.950394] Buffer I/O error on dev sdf1, logical block 0, lost sync page write
[ 9326.009002] scsi_io_completion: 10 callbacks suppressed
[ 9326.009007] sd 3:0:0:0: [sdf] FAILED Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK
[ 9326.009009] sd 3:0:0:0: [sdf] CDB:
[ 9326.009011] Write(16): 8a 00 00 00 00 00 00 00 0f b8 00 00 00 08 00 00
[ 9326.009018] blk_update_request: 10 callbacks suppressed
[ 9326.009020] blk_update_request: I/O error, dev sdf, sector 4024
[ 9326.009023] Buffer I/O error on dev sdf1, logical block 247, lost async page write

(Note that this time I did not unmount and remount with data=writeback, so it was doing its default journaling.)
After this, the rsync failed, presumably because the file system was remounted read-only.
I'm sorry for the log dump.  I've tried to pare it down to the essentials, but I'm afraid I'm not familiar enough with what's going on here to pare it down any further.

A:

This looks like a hardware issue, rather than a kernel bug. You can try the following:

re-seat the SATA cable
use another SATA cable
run SMART diagnostics (the self-tests, see smartmontools)
run a destructive badblocks scan

If you have a spare drive or computer you could also try switching (use another drive in the same computer, use the troublesome drive in another computer) to check whether the motherboard's at fault. Since the drive seems to have issues under load a simple dd if=/dev/zero of=... with appropriate size parameters might be enough to reproduce the errors.
I'm not sure if your drive's warranty would apply since it was originally an external drive...


Q:

Transcription of a predicate applied to a definite description

I am unsure about the transcription of a predicate $\psi$ applied to a definite description $℩x(\phi x)$, in some places it is transcribed as,

$\exists !x(\psi (x) \land \phi (x))$

, whereas in others it is transcribed as

$\exists x(\phi (x) \land \forall y(\phi(y) \rightarrow y=x) \land \psi(x))$.

Definition 2 seems like the correct transcription as it says 'There is exactly one object with the property $\phi$ and that object also has the property $\psi$' however definition 1 says 'There is exactly one object that is both $\psi$ and $\phi$.'
Could you please tell me which transcription is correct?
Also, the book I am reading says a definite description is a term. Since a term is a name or a variable, a definite description could be a name or a variable, but wouldn't it just be a name?

A:

$\exists !x~(\phi(x)\wedge\psi(x))$ is equivalent to $\exists x~((\phi(x)\wedge\psi(x)\wedge(\forall y~(\phi(y)\wedge\psi(y)\to y=x))$.   This says "there is only one entity which satisfies $\psi$ and $\phi$".   This assertion does not deny the existence of entities that satisfy $\phi$ yet not $\psi$.
$\exists x~(\phi(x)\wedge\forall y~(\phi(y)\to y=x)\wedge\psi(x))$ says "the only entity which satisfies $\phi$ also satisfies $\psi$".   This assertion indicates that any entity which satisfies $\phi$ must also satisfy $\psi$, because that would definitely be the only entity which satisfies $\phi$.
So your two statements are not equivalent, and the second does look to say what you require.


Q:

Is it possible such a race condition waiting for a thread to complete a task?

My unexperience with concurrency is quite clear, and I'm looking here for some help.
I was writing a multithreaded application in Java while I was assailed by a doubt. Please look at this sample code (mixing pseudocode and Java):
Thead 1 body (portion):
/* It creates and starts thread Thread 2 */
if (!thread2.taskCompleted)
   thread2.wait();
/* continue execution... */

Thead 2 body:
class Thread2 extends Thread {

    volatile boolean taskCompleted = false;

    public void run() {
        /* It executes a complex task... */
        taskCompleted = true;
        notifyAll(); // notify waiting threads
    }

}

My concern is simple as that: what happens if the statements are executed in that order:

Thread 1 starts Thread 2
Thread 2 does some stuff, but doesn't complete the task
Thread 1 reads taskCompleted as false
Thread 2 completes the task, raises the taskCompleted flag, and notifies (nobody)
Thread 1 starts waiting. And never ends.

Please let me know if you have any ideas and/or it is a well-known scenario (exact duplicate?)

A:

The usage of the taskCompleted flag and wait()/nofiyAll() must be protected by a lock to avoid the scenario you describe.
/* It creates and starts thread Thread 2 */
synchronized (thread2) {
  if (!thread2.taskCompleted)
    thread2.wait();
}
/* continue execution... */

and
class Thread2 extends Thread {

  boolean taskCompleted = false;

  public void run() {
    /* It executes a complex task... */
    synchronized (this) {
      taskCompleted = true;
      notifyAll(); // notify waiting threads
    }
  }
}


Q:

Is this question correctly worded?

I'm taking some online quizzes in a specific subject and I've faced the following question
Which statement is false?
1- XXX.
2- XXX.
3- XXX
4- No statement is false.
5- All statements are false.
The sentences 1,2, and 3 are true. I've chosen 5 and I got incorrect answer and the teacher said the correct answer is 4. It seems to me the way the question is formulated doesn't test my knowledge in the subject which pisses me off. I would like to know if the question from linguistic point of view is correct or valid so that I can file a claim.

A:

Purely as a point of logic, options 4 and 5 are contradictory and immediately cancel each other out, so neither can be the answer. For example, choosing 4 - No statement is false can't be the answer, because 5- All statements are false is false :)
I can only presume that the question is poorly worded, and should have been presented as

XXX
YYY
ZZZ
1, 2 and 3 are all true.
1, 2 and 3 are all false.


Q:

Issues Overloading ToString on Nested PSObject Property

I've created a custom PSObject with a variety of properties and I'm trying to overload ToString for a few of them. I've had success with the one of the TimeSpan properties, but not with one that is a WMI object.
# Get WMI info
$wmiOS = Get-WmiObject -Class Win32_OperatingSystem
$wmiSystem = Get-WmiObject -Class Win32_ComputerSystem
$wmiDrives = Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType='3'"
$ipv4Address = (Test-Connection -ComputerName $env:COMPUTERNAME -Count 1).IPV4Address.IPAddressToString
$uptime = (Get-Date) - ($wmiOS.ConvertToDateTime($wmiOS.LastBootUpTime))
# Setup object
$result = New-Object -TypeName psobject -Property @{
    Hostname = $($wmiSystem.Name)
    Domain = $($wmiSystem.Domain)
    Username = $($wmiSystem.Username)
    OperatingSystem = $($wmiOS.Caption)
    OSArchitecture = $($wmiOS.OSArchitecture)
    PSVersion = "$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor)"
    IPv4Address = $ipv4Address
    Uptime = $uptime
    DriveInfo = $wmiDrives
}

# Overload DriveInfo ToString
$result.DriveInfo = $result.DriveInfo | Add-Member -MemberType ScriptMethod -Name ToString -Value {
    "$($this.DeviceID) $($this.FreeSpace) GB;"
} -Force -PassThru

# Overload Uptime ToString
$result.Uptime = $result.Uptime | Add-Member -MemberType ScriptMethod -Name ToString -Value {
    "$($this.Days) days, $($this.Hours) hours, $($this.Minutes) minutes, $($this.Seconds) seconds"
} -Force -PassThru

# Overload result ToString
$result = $result | Add-Member -MemberType ScriptMethod -Name ToString -Value {
    $temp = @"
Hostname: $($this.Hostname)
Domain: $($this.Domain)
Console User: $($this.Username)
Operating System: $($this.OperatingSystem)
OS Architecture: $($this.OSArchitecture)
PS Version: $($this.PSVersion)
IPv4 Address: $($this.IPv4Address)
Uptime: $($this.Uptime.ToString())
Free Space: $($this.DriveInfo)
"@
        $temp
    } -Force -PassThru

Everything seems to work fine but the DriveInfo overload.  I just get "System.Object[]" as a return from it. What's strange to me is when I just do $result.ToString(), I get the following (see "Free Space"):
Domain: domain.local
Console User: domain\username
Operating System: Microsoft Windows 10 Pro
OS Architecture: 64-bit
PS Version: 5.1
IPv4 Address: 1.1.1.1
Uptime: 2 days, 1 hours, 31 minutes, 49 seconds
Free Space: C: 58721181696; E: 631496687616;

$result.Uptime.ToString():
2 days, 1 hours, 19 minutes, 34 seconds

$result.DriveInfo.ToString():
System.Object[]

I'm probably missing something obvious, but I'm lost at this point.  Thanks for any help you can provide in advance!

A:

Can you just try to replace :
$result.DriveInfo = $result.DriveInfo | Add-Member -MemberType ScriptMethod -Name ToString -Value {"$($this.DeviceID) $($this.FreeSpace) GB;"} -Force -PassThru

By
$result.DriveInfo | Add-Member -MemberType ScriptMethod -Name ToString -Value {"$($this.DeviceID) $($this.FreeSpace) GB;"} -Force -PassThru

In my understanding the Add-Member apply to each drive, you do not need to affect the result, because you change each objects in the list. After that you can test using :
$n = 0
$result.DriveInfo[$n].ToString()


Q:

kendo-ui angular2 detailrow width, html and autoexpand

I have been playing now for some time with the kendo-ui angular components
and I have created this plunker:
http://plnkr.co/edit/zrr3nlxQl7uxbdtH4oEA?p=preview
For setting the width of the detail row I have implemented css:
.detailRow{
  display: inline-block;
  word-wrap: break-word;
  word-break: break-all;
  max-width: 100px;
  white-space: normal;
}

And the html:
    <template kendoDetailTemplate let-dataItem>

{{dataItem.Category?.Description}}

    </template>

Is this the way to control the detailrow width?
Is it possible to render html in the detailrow (show bold and italic)?
Is it possible to auto-expand every single row on loading?

A:

Yes, using width on the detail row content is fine for controlling its width.
If the Category.Description field contains HTML, you may need to bind it using the innerHTML binding, as shown in this thread. Be sure to sanitize the HTML, or XSS attacks may follow.
There is no provided way for controlling all detail rows at this time. This has been logged and can be tracked in the feature request in the kendo-angular2 repo.


Q:

An exponential Diophantine equation.

I'm solving an exponential Diophantine equation, and I've taken (mod 3) to have that $z$ is odd, but it's still hard for me .
" Find all the positive integers $x, y, z$ such that $7^x+1=3^y+5^z$ ".

A:

Finally, I've found a solution only using modulo.
We want to find all the positive integers $x,y,z$ such that
$ 7^x+1=3^y+5^z $ (1)
Consider the equation $(1)$ in $\pmod 3$, we have $$ 5^z \equiv 2\pmod 3$$ So $z$ is odd. If $y\ge 2$, then we can take $\pmod 9$ to have that $$ 7^x+1\equiv 5^z \pmod 9$$ Note that $ord_9(5)=6$ and $ord_9(7)=3$, we have:
If $x\equiv 1 \pmod 3 \Rightarrow z\equiv 3 \pmod 6$
$x\equiv 2 \pmod 3 \Rightarrow z\equiv 1 \pmod 6$
$x\equiv 0 \pmod 3 \Rightarrow z\equiv 5 \pmod 6$
Now take $(1)$ in $\pmod 7$, we have $$3^y+5^z\equiv 1 \pmod 7$$
So if $z\equiv 1 \pmod 6 \Rightarrow y\equiv 1 \pmod 6$
$z\equiv 3 \pmod 6\Rightarrow y\equiv 2 \pmod 6$
$z\equiv 5 \pmod 6 \Rightarrow y\equiv 5 \pmod 6$
Then take $\pmod {13}$ we have $$7^x+1\equiv 3^y+5^z\pmod {13}$$ Now consider all cases of $x$ in modulo 12, we found only one case is compatible: $x\equiv 2 \pmod 12$, $ y\equiv 1 \pmod 6$, and $z\equiv 7 \pmod 12$.
Now we can write $x=12k+2$, then $7^x+1=49^{6k+1}+1\equiv 0 \pmod 5\Rightarrow 3^y+5^z\equiv 0 \pmod 5$, contradiction.
So we conclude that $y=1$ and $7^x-5^z=2$. If $z\ge 2$ then take modulo 25 to have $7^x\equiv 2 \pmod {25}$, contradiction. So $z=1$ and $x=1$.
Hence $(x,y,z)=(1,1,1)$ is the only solution for $(1)$.


Q:

php preg_replace \n

I need to double escape \n into \\n. The string is echoed and passed to client side javascript code which retrieves the data by doing an eval. I have tried doing preg_replace('/\\/', 'blah', $string), which returns an empty string. However, when I used preg_replace('/\n/', 'blah', $string), it worked. Any ideas? Thanks.

A:

What about str_replace("\n", "\\n", $string)?


Q:

Java - Getting rid of NullPointerException

Think about two cases case1 and case2 plus two methods method1 and method2. Say method1 solves case1 and method2 solves case2. Now, I have a program that might end up with case1 or case2. In my codes, I call method1 no matter what case happens. But, if case2 occurs, method1 gives a nullpointerexception.
What I want is the following: my codes should call method1 first, if an exception occurs, then method2 is called. How am I gonna do that? Since I have no info about try and catch, I really need some help!

A:

You could do this:
    try {
        method1();
    }
    catch ( Exception e ) {
        method2();
    }

That said, it's typically better to rely on exceptions only for exceptional conditions. For normal flow of control, you can use an if:
    if ( isCase2() ) {
        method2();
    }
    else {
        method1();
    }


Q:

Jasmine checking if variable is defined in method

I'm new to jasmine. My Company is using jasmine 1.3.1
I am trying to test if a variable is defined in a method.  I keep coming back with a failure.
objectParentName.accessoriesSlider = {
modifyJSON: function(obj) {
        var contentLoadJSON = [];

        for (var property in obj) {
            objectParentName.accessoriesSlider.contentJSONTotal++
            contentLoadJSON.push(obj[property]);
        }

        contentLoadJSON = objectParentName.accessoriesSlider.sortJSON(contentLoadJSON, 'dateAdded', false);

        return contentLoadJSON;
    }
}

Here is jasmine for that method.
describe('Test "modifyJSON" function', function () {

    beforeEach(function() {
        spyOn(objectParentName.accessoriesSlider, 'modifyJSON');

        var contentLoadJSON = []; //forcibly add variable to see if that fixes issue
        objectParentName.accessoriesSlider.modifyJSON();
    });

    it('is defined as "modifyJSON"', function () {
        /**
         * objectParentName.accessoriesSlider.modifyJSON should be defined.
         */

        expect(objectParentName.accessoriesSlider.modifyJSON).toBeDefined();
    });

    it('and "modifyJSON" is a function', function () {
        /**
         * This should be a 'function'.
         */

        expect(objectParentName.accessoriesSlider.modifyJSON).toBeFunction();
    });

    describe('Test "contentLoadJSON" variable', function () {
        it('is defined', function () {
            expect(contentLoadJSON).toBeDefined();
        });

    });

});

I am getting this error
ReferenceError: contentLoadJSON is not defined
at .<anonymous> (http://localhost:8234/spec/jasmine_accessories_slider.js:300:24)
at jasmine.Block.execute (http://localhost:8234/?spec=accessories_slider.js:1164:19)
at jasmine.Queue.next_ (http://localhost:8234/?spec=accessories_slider.js:2196:33)
at jasmine.Queue.start (http://localhost:8234/?spec=accessories_slider.js:2149:10)
at jasmine.Spec.execute (http://localhost:8234/?spec=accessories_slider.js:2476:16)
at jasmine.Queue.next_ (http://localhost:8234/?spec=accessories_slider.js:2196:33)
at jasmine.Queue.start (http://localhost:8234/?spec=accessories_slider.js:2149:10)
at jasmine.Suite.execute (http://localhost:8234/?spec=accessories_slider.js:2621:16)
at jasmine.Queue.next_ (http://localhost:8234/?spec=accessories_slider.js:2196:33)
at jasmine.Queue.start (http://localhost:8234/?spec=accessories_slider.js:2149:10)

So, I have no idea why I am getting an error here.

A:

The first problem is that the variable contentLoadJSON is not defined in the scope of the function you are calling it from.
When you define a variable using var, it becomes a local variable, and is only accessible inside the scope of that function. In this case, the function it exists in is:
beforeEach(function() {
    spyOn(objectParentName.accessoriesSlider, 'modifyJSON');

    var contentLoadJSON = [];

    objectParentName.accessoriesSlider.modifyJSON();
});

The function you are getting the error in is a different function() { ... } that isn't nested in beforeEach. It is therefore can't see the local variable you defined.
One way to rectify this is by defining the variable in the scope of your test suite, instead of in the scope of the beforeEach function:
describe('Test "modifyJSON" function', function () {
    var contentLoadJSON; // Define it here

    beforeEach(function() {
        contentLoadJSON = []; // Assign it here
        // ... more code here ...
    }

    // ... more code here ...

    describe('Test "contentLoadJSON" variable', function () {
        it('is defined', function () {
            // Test contentLoadJSON here...

The second problem is that just because variables have the same name doesn't mean they are actually the same variable. They have to also be in the same scope for that to be true. var contentLoadJSON inside modifyJSON is actually a totally different variable than the var contentLoadJSON you are defining in beforeEach in your test suite.
When you call the function under test, you are not assigning its result to the variable you are trying to test. In fact, you are actually throwing away the result immediately after you call the function.
To fix this, change:
var contentLoadJSON = [];
objectParentName.accessoriesSlider.modifyJSON();
// Note that contentLoadJSON still equals [] at this point.
// The return of the function call is getting thrown away,
// because you don't assign it to a variable

To:
var contentLoadJSON = objectParentName.accessoriesSlider.modifyJSON();

The third problem is that expect(someVariable).toBeDefined(); might not do what you are expecting it to do. It doesn't check that the variable is "in scope". It checks that the value someVariable is not equal to the value undefined. Unless your function might sometimes return undefined, then this particular test isn't very important and will probably never fail.
It may be better to check that the result is "truthy" (expect(contentLoadJSON).toBeTruthy()). It might even make sense to just check that it is equal to the value you'd expect for the given data/input.


Q:

fail to get gps/network location even when i set the location permission

I trying to get the location using network/gps.
I define add the permission on the manifest ( ACCESS_FINE_LOCATION ) but i getting that the permission is -1 ( PERMISSION_DENIED )
I calling a instance of the class 'GetLocation' on the main activity.
And call the 'getCurrentLocation(this)' from this main activity.
The code:
  public class MainActivity extends AppCompatActivity {

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

    TraceActionLocation t = new TraceActionLocation();

    Location l = t.getCurrentLocation(this);

}

  public class GetLocation
  {
    public Location getCurrentLocation(Context context)
    {
        Location location = null;

    LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

    Boolean isGpsEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    Boolean isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if(!isGpsEnable && !isNetworkEnable)
    {
        // TODO !!! => no gps and no network !!!
    }
    else if(context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_DENIED)
    {
        // 1. get the location from network provider
        if(isNetworkEnable)
        {
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }

        // 2. get the more equate location from the gps
        if(isGpsEnable)
        {
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
    }

    return location;
}
}

A:

Adding the permission for location in manifest for Marshmallow is not enough. You will have to request the permission at runtime. And for that first you will have to add ACCESS_COARSE_LOCATION permission. As I have tried to request ACCESS_FINE_LOCATION at runtime before and that never works.
Request for ACCESS_COARSE_LOCATION in your activity. Find a rough example below:
public class MainActivity extends AppCompatActivity {

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

    if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("result", "permissioin granted");

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

}


Q:

Understanding VBJSON class set up in Excel 2010

I have downloaded and set the JSON parser for VB6 from this website:
VB-JSON
I cannot understand how this module works. I successfuly set it in Excel 2010 and I think I also understand the JSON format but I don't know how this class extracts the items. I tried to parsed the following text in the JSON format
{"realms":[{"type":"pvp","population":"low","queue":false,"wintergrasp":{"area":1,"controlling-faction":1,"status":0,"next":1356724174636},"tol-barad":{"area":21,"controlling-faction":1,"status":0,"next":1356723246779},"status":true,"name":"Kor'gall","slug":"korgall","battlegroup":"Cruelty / Crueldad","locale":"en_GB","timezone":"Europe/Paris"},{"type":"pve","population":"medium","queue":false,"wintergrasp":{"area":1,"controlling-faction":0,"status":0,"next":1356724425638},"tol-barad":{"area":21,"controlling-faction":0,"status":0,"next":1356723369780},"status":true,"name":"Alonsus","slug":"alonsus","battlegroup":"Cruelty / Crueldad","locale":"en_GB","timezone":"Europe/Paris"}]}

A browser will return this content when the following address is used:
Alonsus, Kor'gall
I wrote a code similar to this
Dim objJSON As Object
...
strData = objJSON.Item("Realms")(1).Item("Type")

but it causes errors: "Object variable or With block variable not set". I expected to get "pve" value. I am confused because it starts with an object name "realms" followed by an Array. The array is supposed to be returned as a collection. I would be grateful for any help with that.
Thanks

A:

set objJSON = JSON.Parse(jsonFromUrl)
strData = objJSON.Item("realms").Item(1).Item("type")

Keys inside json is case-sensitive.


Q:

Xcode 5.0.2 Crashes on Running Simple Code

I have made simple code that builds in XCode. When I place the play/run button in the upper left corner I receive the error below this paragraph. I have tried the following things: Downloading and running XCode 5.0 instead. Disabling source control in Preferences. Re-installing iTunes. None have worked.
Process:         Xcode [2603]
Path:            /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:      com.apple.dt.Xcode
Version:         5.0.2 (3335.32)
Build Info:      IDEApplication-3335032000000000~4
App Item ID:     497799835
App External ID: 106632651
Code Type:       X86-64 (Native)
Parent Process:  launchd [288]
Responsible:     Xcode [2603]
User ID:         501

Date/Time:       2013-12-24 21:18:17.467 -1000
OS Version:      Mac OS X 10.9 (13A603)
Report Version:  11
Anonymous UUID:  EA8A0ADD-1FEE-BE0F-43E2-EDD5C4C34AE3

Sleep/Wake UUID: 6C4103F6-A3F4-48D0-9935-E0F2C50A2CFE

Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000

Application Specific Information:
Sending performRunAction: to <IDERunPauseContinueToolbarButton: 0x7fd501cea240> from <IDERunPauseContinueToolbarButton: 0x7fd501cea240>
ProductBuildVersion: 5A3005
UNCAUGHT EXCEPTION (NSInternalInconsistencyException): Error getting value for key 'workerClass' of extension 'Xcode.DebuggerFoundation.Debugger.LLDB' in plug-in 'com.apple.dt.dbg.DebuggerLLDB'
UserInfo: {
    NSUnderlyingError = "Error Domain=DVTPlugInErrorDomain Code=2 \"Loading a plug-in failed.\" UserInfo=0x7fd508dbf330 {DVTPlugInIdentifierErrorKey=com.apple.dt.dbg.DebuggerLLDB, DVTPlugInExecutablePathErrorKey=/Applications/Xcode.app/Contents/PlugIns/DebuggerLLDB.ideplugin/Contents/MacOS/DebuggerLLDB, NSLocalizedRecoverySuggestion=The plug-in or one of its prerequisite plug-ins may be missing or damaged and may need to be reinstalled., NSLocalizedDescription=Loading a plug-in failed., NSFilePath=/Applications/Xcode.app/Contents/PlugIns/DebuggerLLDB.ideplugin, NSLocalizedFailureReason=The plug-in \U201ccom.apple.dt.dbg.DebuggerLLDB\U201d at path \U201c/Applications/Xcode.app/Contents/PlugIns/DebuggerLLDB.ideplugin\U201d could not be loaded.  The plug-in or one of its prerequisite plug-ins may be missing or damaged., NSUnderlyingError=0x7fd508eb8ef0 \"The bundle \U201cDebuggerLLDB\U201d couldn\U2019t be loaded because it is damaged or missing necessary resources.\"}";
}
Hints:
  0: Sending performRunAction: to <IDERunPauseContinueToolbarButton: 0x7fd501cea240> from <IDERunPauseContinueToolbarButton: 0x7fd501cea240>
  1: Sending performAction: to <DVTDelayedMenuButtonCell: 0x7fd501cbaa40> from <IDERunPauseContinueToolbarButton: 0x7fd501cea240>
Backtrace:
  0  0x00007fff85e1d404 __exceptionPreprocess (in CoreFoundation)
  1  0x000000010f827d73 DVTFailureHintExceptionPreprocessor (in DVTFoundation)
  2  0x00007fff86fbce75 objc_exception_throw (in libobjc.A.dylib)
  3  0x000000010f7b5cd2 -[DVTExtension valueForKey:] (in DVTFoundation)
  4  0x0000000114262109 -[DBGLLDBDebugLocalService operationWorkerWithLaunchSession:error:] (in DebuggerLLDBService)
  5  0x000000011749fe17 -[IDERuniPhoneSimulatorService operationWorkerWithLaunchSession:error:] (in IDEiOSSupportCore)
  6  0x000000011027ad49 -[IDERunDestination runWorkerForLaunchSession:error:] (in IDEFoundation)
  7  0x000000011027aa74 -[IDERunDestination runOperationForLaunchSession:error:] (in IDEFoundation)
  8  0x00000001102e2fee -[IDELaunchSchemeAction runOperationForExecutionEnvironment:withBuildOperation:buildParameters:buildableProductDirectories:schemeActionRecord:outError:actionCallbackBlock:] (in IDEFoundation)
  9  0x00000001102d6f5b -[IDEScheme _executionOperationForExecutionEnvironment:build:onlyBuild:buildPurpose:buildCommand:schemeCommand:title:overridingProperties:destination:buildLog:filePath:overridingBuildConfiguration:restorePersistedBuildResults:invocationRecord:overridingTestingSpecifiers:error:actionCallbackBlock:] (in IDEFoundation)
 10  0x00000001102d434d -[IDEScheme runWithExecutionContext:buildIfNeeded:onlyBuild:destination:overridingProperties:commandName:invocationRecord:error:] (in IDEFoundation)
 11  0x0000000110a585d4 -[IDEWorkspaceTabController _actuallyPerformSchemeTask:onScheme:runDestination:command:commandName:buildCommand:filePath:overridingTestingSpecifiers:invocationRecord:completionBlock:] (in IDEKit)
 12  0x0000000110a5bcd7 __175-[IDEWorkspaceTabController _performSchemeTask:onScheme:runDestination:command:commandName:buildCommand:filePath:overridingTestingSpecifiers:invocationRecord:completionBlock:]_block_invoke (in IDEKit)
 13  0x0000000110a5bafc -[IDEWorkspaceTabController _performSchemeTask:onScheme:runDestination:command:commandName:buildCommand:filePath:overridingTestingSpecifiers:invocationRecord:completionBlock:] (in IDEKit)
 14  0x0000000110a5c797 __185-[IDEWorkspaceTabController _performDebuggableSchemeTask:onScheme:runDestination:command:commandName:buildCommand:filePath:overridingTestingSpecifiers:invocationRecord:completionBlock:]_block_invoke (in IDEKit)
 15  0x0000000110a5cd02 -[IDEWorkspaceTabController _forceSwitchToLLDBIfNecessary:preAlertHandler:completionHandler:] (in IDEKit)
 16  0x0000000111ea6264 -[DVTDeveloperModeAlertHelper _askToEnableDeveloperModeIfNecessary] (in DVTDeveloperModeHelper)
 17  0x0000000110a5c657 -[IDEWorkspaceTabController _performDebuggableSchemeTask:onScheme:runDestination:command:commandName:buildCommand:filePath:overridingTestingSpecifiers:invocationRecord:completionBlock:] (in IDEKit)
 18  0x0000000110a5d2a8 -[IDEWorkspaceTabController _runScheme:runDestination:invocationRecord:] (in IDEKit)
 19  0x00000001109a373b -[IDEWorkspaceTabController runActiveRunContext:] (in IDEKit)
 20  0x0000000110ab61b1 -[IDERunPauseContinueToolbarButton performRunAction:] (in IDEKit)
 21  0x00007fff850743d0 -[NSApplication sendAction:to:from:] (in AppKit)
 22  0x000000010ff08aff __37-[DVTApplication sendAction:to:from:]_block_invoke (in DVTKit)
 23  0x000000010f827ab1 DVTInvokeWithFailureHint (in DVTFoundation)
 24  0x000000010fd3a5ba -[DVTApplication sendAction:to:from:] (in DVTKit)
 25  0x000000010fefd220 -[DVTDelayedMenuButtonCell performAction:] (in DVTKit)
 26  0x00007fff850743d0 -[NSApplication sendAction:to:from:] (in AppKit)
 27  0x000000010ff08aff __37-[DVTApplication sendAction:to:from:]_block_invoke (in DVTKit)
 28  0x000000010f827ab1 DVTInvokeWithFailureHint (in DVTFoundation)
 29  0x000000010fd3a5ba -[DVTApplication sendAction:to:from:] (in DVTKit)
 30  0x000000010fe05a74 -[DVTDelayedMenuButtonCell trackMouse:inRect:ofView:untilMouseUp:] (in DVTKit)
 31  0x00007fff850d91fd -[NSControl mouseDown:] (in AppKit)
 32  0x000000010fe21832 -[DVTMainStatusAwareButton mouseDown:] (in DVTKit)
 33  0x000000010fe217c3 -[DVTRolloverTrackingButton mouseDown:] (in DVTKit)
 34  0x00007fff8505ad08 -[NSWindow sendEvent:] (in AppKit)
 35  0x00007fff84ff9744 -[NSApplication sendEvent:] (in AppKit)
 36  0x000000011089d83b -[IDEApplication sendEvent:] (in IDEKit)
 37  0x00007fff84e49a29 -[NSApplication run] (in AppKit)
 38  0x00007fff84e34803 NSApplicationMain (in AppKit)
 39  0x00007fff900245fd start (in libdyld.dylib)
 40  0x0000000000000001

abort() called

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff8a77b866 __pthread_kill + 10
1   libsystem_pthread.dylib         0x00007fff82d9b35c pthread_kill + 92
2   libsystem_c.dylib               0x00007fff8cc5ebba abort + 125
3   com.apple.dt.IDEKit             0x0000000110a9a7af +[IDEAssertionHandler _handleAssertionWithLogString:reason:] + 775
4   com.apple.dt.IDEKit             0x0000000110a9b9fd -[IDEAssertionHandler handleUncaughtException:] + 919
5   com.apple.dt.IDEKit             0x0000000110a9baa8 IDEHandleUncaughtException + 77
6   com.apple.AppKit                0x00007fff84e49ad8 -[NSApplication run] + 821
7   com.apple.AppKit                0x00007fff84e34803 NSApplicationMain + 940
8   libdyld.dylib                   0x00007fff900245fd start + 1

A:

I was the same and the problem is that it did not properly install python 2


Q:

phpQuery - скрипт выдает белую страницу

Я пытался повторить материал из видеоурока про phpQuery, сверил весь код с точностью до запятой, но у меня отображается только пустая страница в итоге.
Код вроде бы совсем простой, ошибок не нахожу
<?php
    header('Content-type: text/html; charset=utf-8');
    require 'phpQuery.php';

$url='https://privatbank.ua/ru/';
$file=file_get_contents($url);

$doc = phpQuery::newDocument($file);
$tbl = $doc->find('#course-table-pb');

echo $tbl;

Не может ли такого быть, что я версию phpQuery взял какую-нибудь не такую?
Проверяется по ходу:
$file - непустое
$doc - непустое
$tbl - пусто

A:

подытожу свои комментарии.
Вы загружаете страницу по указанной ссылке. Когда вы ее открываете в браузере там выполняется множество JS-кода, который в частности подгружает курсы валют. И в результате вы видите страницу такой, какой видите.
Когда вы эту же страницу загружаете через file_get_contents() вы получаете только исходный код страницы, JS скрипты никто не обрабатывает. Поэтому динамические данные не загружаются. Можете сохранить вывод file_get_contents в файл (или просмотреть исходный код страницы в браузере) и там вы не найдете элемента #courses-table-pb, который запрашиваете через phpQuery.
В инструментах разработчика в браузере вы можете наблюдать, что курсы валют запрашиваются по ссылке https://currency.privatbank.ua/ru/get-currencies
Дальше действуйте из ваших интересов. Если ваша задача - изучить phpQuery, то найдите другую страницу для практики. Если задача - получить курсы валют, то загрузите json-данные по ссылке выше, декодируйте их с помощью json_decode и используйте по своему усмотрению, а phpQuery для данной задачи не нужен.
$content = file_get_contents("https://currency.privatbank.ua/ru/get-currencies/");
$content = substr($content, 1, strlen($content)-2);

$data = json_decode($content);
$data = json_decode($data->content);

print_r($data->exchange->currency_pb);


Q:

Creating a PGF node in the middle of a PGF path

Consider the following LaTeX manuscript featuring a PGF path consisting of two successive diagonal line segments intercepted by a rectangular text node.
\documentclass{article}
  \usepackage{pgf}
\begin{document}
    \begin{pgfpicture}
      \pgfpathmoveto{\pgfpoint{-1cm}{-1cm}}
      \pgfpathlineto{\pgfpointorigin}
      \pgfnode{rectangle}{center}{Hello world}{}{\pgfusepath{stroke}}
      \pgfpathlineto{\pgfpoint{1cm}{1cm}}
      \pgfusepath{stroke}
    \end{pgfpicture}
\end{document}

The resulting image is

Why is the second line segment not drawn?
If I now change the node's stroke instruction to fill, the following image results:

Where has the first line segment gone?

A:

The internals are a bit convoluted but since node is using \pgfusepath all the soft path collected until that point is used and deleted.
And since there is no moveto operation at the beginning of the next path it is not drawn. Check for example
\begin{pgfpicture}
%\pgfpathmoveto{\pgfpointorigin}
  \pgfpathlineto{\pgfpoint{1cm}{1cm}}
  \pgfusepath{stroke}
\end{pgfpicture}

which draws nothing if it is left commented.


Q:

Slim 3 access response/request object from another class

I have a Utils class, I need to use $response/$request from Slim 3 to use some useful methods (ex: $request->getUri()->getPath()), how can I access to $request or $response like that:

class AppCore
{

    public static function AllowRoutePass($request, $response)
    {
        $reqMethod =$request->getUri()->getPath();
        if (in_array($reqMethod, AppConfig::IGNORE_ROUTES))
            return true;
        return false;
    }

}

Thank everyone!

A:

OK, i also create an question in Githup Slim repository here: Slim 3 access response/request object from another class.
Currently there is no way to implement the util class I was described as above. Check out the link to see more informations. In my case,  i must change my logics and implement my util class in another way.


Q:

How do I figure out what this code is doing?

I am trying to get my hands dirty by doing some experiments on Data Science using Python and the Pandas library.
Recently I got my hands on a jupyter notebook and stumbled upon a piece of code that I couldn't figure out how it works?
This is the line
md['genres'] = md['genres'].fillna('[]').apply(literal_eval).apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else [])

The dataset comes with a genres column that contains key-value pairs, the code above removes the keys and replaces everything with only the value if more than one value exists a | is inserted as a seperator between the two for instance
Comedy | Action | Drama
I want to know how the code actually works! Why does it need the literal_eval from ast? What is the lambda function doing?! Is there a more concise and clean way to write this?

A:

Let's take this one step at a time:
md['genres'].fillna('[]')

This line fills all instances of NA or NaN in the series with '[]'.
.apply(literal_eval)

This applies literal_eval() from the ast package. We can imply from the fact that NA values have been replaced with '[]' that the original series contains string representations of lists, so literal_eval is used to convert these strings to lists.
.apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else [])

This lambda function applies the following logic: If the value is a list, map to a list containing the ['name'] values for each element within the list, otherwise map to the empty list.
The result of the full function, therefore, is to map each element in the series, which in the original DF is a string representation of a list, to a list of the ['name'] values for each element within that list. If the element is either not a list, or NA, then it maps to the empty list.


Q:

Open web browser window in VS 2010 via add-in code?

I'm porting a VS Add-in to VS 2010 from VS 2008 and need to be able to open the built-in web browser.
In VS 2008, it was possible to get a handle on the web browser window with code like this:
var win = _applicationObject.Windows.Item(Constants.vsWindowKindWebBrowser);

However, the same code does not work in VS 2010 when an instance of the web browser has not already been opened. Instead it gives an ArgumentException on the Item index.

A:

This appears to work:
_applicationObject.ItemOperations.Navigate("about:blank", vsNavigateOptions.vsNavigateOptionsDefault);

This code opens the specified file in the browse window whether it's already opened or not. And then it's possible to grab a reference to the window object and wire up events such as BeforeNavigate2.


Q:

Php Curl headers not being set

I am trying to set 2 variables to the curl headers and can't seem to see what's wrong.  I am not receiving any errors in the php logs, but when I print out the curl info I can see that the headers are not being set.  Any point in the right direction would be helpful.  Thanks
The Example I'm using
PHP cURL custom headers
class GetAuctions
{
private $APIKeyID = "theIDhere";
private $APIKeyPass = "thePasswordHere";
private $BaseURL = "https://someurlHere";

public function __construct()
{
    //get list of upcoming auctions
    $get_data = $this->callAPI('GET', $this->BaseURL, false);
    //turn the response into a json
    $response = json_decode($get_data, true);
    //display the response for testing
    echo print_r($response);
    $errors = $response['response']['errors'];
    $data = $response['response']['data'][0];
    echo print_r($data);
}

function callAPI($method, $url, $data){
    $curl = curl_init();

    switch ($method){
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // OPTIONS:
    curl_setopt($curl, CURLOPT_URL, $url);
    $headers =array();
    $headers['apiKeyID'] = $this->APIKeyID;
    $headers['apiKeyPass'] = $this->APIKeyPass;
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    echo "
";
    echo print_r(curl_getinfo($curl));
    echo "
";
    // EXECUTE:
    $result = curl_exec($curl);
    if(!$result){die("Connection Failure");}
    curl_close($curl);
    return $result;
}
}

I've also tried this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        "apiKeyID: $this->APIKeyID",
        "apiKeyPass: $this->APIKeyPass"
    ));

My response looks like this:
Array ( [url] => https://MyURLHere [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0 [namelookup_time] => 0 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [redirect_url] => [primary_ip] => [certinfo] => Array ( ) [primary_port] => 0 [local_ip] => [local_port] => 0 ) 1

Connection Failure

A:

It looks like your headers are incorrectly formatted:
"apiKeyID : $this->APIKeyID",

You should remove space before your colon:
"apiKeyID: ${this->APIKeyID}",

BTW: for debugging purpose you may also use CURLOPT_VERBOSE to see what's is being send by cURL. If you cannot peek stderr at runtime, redirect it to the file:
curl_setopt($c, CURLOPT_STDERR, fopen('curl-log.txt', 'w+'));


Q:

How to compute the conditional probability in R?

Let's suppose I have these two vectors:
x = rnorm(20)
y = rnorm(20)

I want to compute the probability that y > 0 given that x > 0.
In other words, I want the frequency that my y > 0 when x > 0.
Can anyone show me how to code this in R?

A:

To make the results reproducible,  I will  use set.seed
set.seed(42)
x = rnorm(20)
y = rnorm(20)

You can just subset the data to select the ones where x>0  and then count what proportion of those have y>0
PosX = which(x>0)
sum(y[PosX] > 0)/length(PosX)
[1] 0.6


Q:

Expressão regular 6 casas decimais

Alguém me saber dizer se é possível criar uma expressão regular com as seguintes características:

valor entre 31.000000 e 43.000000
o valor pode ter 6 casas decimais, mas deve estar no intervalo de 31 a 43.

O que eu tenho é o seguinte:
^(\+|-)?(\d\.\d{1,6}|[1-6]\d\.\d{1,6}|1[1-7]\d\.\d{1,6}|43\.0{1,6})$

é possível definir um valor minimo?

A:

Concordando com todas as ressalvas que uma validação via expressão regular não é o caminho, podemos divagar no assunto.

Não custa lembrar, só porque você pode fazer, não quer dizer que deve fazer.
Vou repetir o aviso que coloquei nesta resposta, porque não custa nada alertar:

Você tem a arma, eu te dou a munição, mas você quem decide se deve atirar na própria perna ou não.

A resposta do @JJoao trata de intervalos fechados. Eu li que em seus comentários você cita que o intervalo é aberto. Então, pondero, como deveria ser para intervalos abertos?
Vamos falar aqui primeiramente em intervalos unitários, depois extrapolamos para um intervalo qualquer.
Aberto no limite superior
O primeiro caso é se o limite superior for aberto. Por exemplo, o intervalo [42, 43) aceita o valor 42.999999, mas não 43.000000.
Para reconhecer esse intervalo, com seis casas decimais, não tem segredo algum. Só extrapolar a ideia do @JJoao para o número desejado.
42(\.[0-9]{1,6})?

Essa expressão é fechada no limite inferior é aberta no superior. Aceita de 42 a 42.999999, assim como 42.0000, mas não aceita 43.
Aberto no limite inferior
E no limite inferior? Foi fácil no limite superior, será que também será no inferior?
Para isso, precisamos reconhecer qualquer string depois do . que contenha pelo menos um número diferente de zero, limitado a 6 números.
Basicamente essa é a mesma pergunta de gerar uma string de 1 a 6 dígitos em que pelo menos um desses dígitos seja diferente de zero. Consegui isto para responder, não consegui simplificar. Eu separei as alternativas abaixo, a resposta seria colocar elas todas intercaladas com |.
[1-9][0-9]{0,5}
0[1-9][0-9]{0,4}
0{2}[1-9][0-9]{0,3}
0{3}[1-9][0-9]{0,2}
0{4}[1-9][0-9]{0,1}
0{5}[1-9]

De certo modo, para um total de m casas decimais no máximo, começando com z zeros a esquerda, a fórmula de criação dessas subexpressões é:
0{z}[1-9][0-9]{0,m-z-1}

Sendo que 0 <= z <= m - 1, com z e m inteiros não negativos.
Então, para reconhecer um número no intervalo aberto inferior (e apenas inferior), a regex seria um tanto quanto grande. Para (42,43], seria:
42\.([1-9][0-9]{0,5}|0[1-9][0-9]{0,4}|0{2}[1-9][0-9]{0,3}|0{3}[1-9][0-9]{0,2}|0{4}[1-9][0-9]{0,1}|0{5}[1-9])|43(\.0{1,6})?

Já se fosse aberto em ambas as extremidades, a expressão não precisaria considerar o inteiro 43 ao final:
42\.([1-9][0-9]{0,5}|0[1-9][0-9]{0,4}|0{2}[1-9][0-9]{0,3}|0{3}[1-9][0-9]{0,2}|0{4}[1-9][0-9]{0,1}|0{5}[1-9])

Unindo intervalos consecutivos
Bem, começamos com intervalos unitários, que começam em números inteiros. E como seria a união desses intervalos caso eles sejam consecutivos?
A primeira alternativa seria colocar as expressões de cada intervalo agrupadas entre ( parentes ) e intercaladas com |.
Mas, poderíamos fazer melhor, não é?
O intervalo mais bem comportado é o intervalo fechado no limite inferior porém aberto no limite superior. Ele contém uma parte constante (a parte inteira do número) seguida da seguinte expressão:
(\.[0-9]{1,6})?

Quando estamos intercalando diversos desses intervalos, basta colocar essa expressão do lado direito e por do lado esquerdo as constantes separaras por | ou alguma outra expressão que remeta a isso. Por exemplo, [32,43) pode ser representado assim:
(3[2-9]|4[0-3])(\.[0-9]{1,6})?

Do lado direito, a expressão mágica que representa o intervalo unitário fechado no limite inferior porém aberto no superior. Do lado direito, uma expressão que representa todos os inteiros no intervalo passado.
Caso seja necessário lidar com um intervalo fechado no limite superior, basta adicionar o valor limite seguido de 0 a 6 zeros. Como se fosse uma união entre o intervalo fechado no começo porém aberto no final e do número individual: [42,43) U {43}
42(\.[0-9]{1,6})?|43(\.0{1,6})?

As outras uniões podem continuar sendo aplicadas normalmente, então fazer [32, 43] é fazer [32,42) U [42,43) U {43}:
(3[2-9]|4[0-3])(\.[0-9]{1,6})?|43(\.0{1,6})?

Para intervalo aberto, entretanto, a fórmula vai ficar grande. Não vou por como ficaria a expressão aqui, ela seria ilegível de qualquer sorte. O pensamento, entretanto, seria isolar um único intervalo unitário aberto em ambas as extremidades, então tratar o resto como intervalos fechados no limite inferior e aberto no superior. Tipo, (32,43] pode ser interpretado como (32,33) U [33,43], ou então como (32,33) U [33,43) U {43}.

A:

Não é o caminho ideal, mas tendo que ser:
^((3[1-9]|4[0-2])(\.\d{0,6})?|43(\.0{0,6})?)$


Q:

numpy and pandas datetime handling in matplotlib

I'm trying to fit the curve to a time series as it explained here: https://stackoverflow.com/a/17639070/12012445
If I do not import pandas module - everything works like a charm.
If I do, and I have to, - I get "'datetime.timezone' object has no attribute '_utcoffset'"
it seems to me that the issue is with plotting step were it returns the coefficients for a polynomial p(x) which in turn depends on datetime...
I've gone through a number of hints, including Converting between datetime, Timestamp and datetime64
I'm quite desperate (5th-hour researching)
import pandas as pd #note that I'm not even calling it anywhere... so confused

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import time

dates = [dt.datetime(1978, 7, 7),
     dt.datetime(1980, 9, 26),
     dt.datetime(1983, 8, 1),
     dt.datetime(1985, 8, 8)]

y = [0.00134328779552718,
     0.00155187668863844,
     0.0039431374327427,
     0.00780037563783297]

yerr = [0.0000137547160254577,
        0.0000225670232594083,
        0.000105623642510075,
        0.00011343121508]

x = mdates.date2num(dates)

z4 = np.polyfit(x, y, 3)
p4 = np.poly1d(z4)

fig, cx = plt.subplots()

xx = np.linspace(x.min(), x.max(), 100)
dd = mdates.num2date(xx)

cx.plot(dd, p4(xx), '-g')
cx.plot(dates, y, '+', color='b', label='blub')
cx.errorbar(dates, y,
             yerr,
             marker='.',
             color='k',
             ecolor='b',
             markerfacecolor='b',
             label="series 1",
             capsize=0,
             linestyle='')

cx.grid()
cx.set_ylim(0, 0.03)
plt.show()

expecting:

A:

If you import pandas, it would register its datetime converters to be used by matplotlib. Apparently there is a problem with those somewhere. And in case that happens, you may deregister them via
import pandas as pd
pd.plotting.deregister_matplotlib_converters()

This will ensure matplotlib converters are used and those seem to work as expected.


Q:

How to use DockStyle.Fill for standard controls in WPF?

I'm used from windows forms, that I create a panel, place controls inside it and give them DockStyle.Fill to max out their size to the surrounding panel.
In WPF I want to have the same. I have a TabControl and I want its size to fill as much of the form as possible.
I have a ribbon control (RibbonControlsLibrary) and want the rest of the form to be filled with the TabControl at max size.
(I do not want to dock controls like docking in Visual Studio, just old docking mechanisms)

A:

The WPF equivalent of WinForms' DockStyle.Fill is:
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"

This is the default for almost controls, so in general you don't have to do anything at all to have a WPF control fill its parent container:  They do so automatically.  This is true for all containers that don't squeeze their children to minimum size.
Common Mistakes
I will now explain several common mistakes that prevent HorizontalAlignment="Stretch" VerticalAlignment="Stretch" from working as expected.
1. Explicit Height or Width
One common mistake is to explicitly specify a Width or Height for a control.  So if you have this:
<Grid>
  <Button Content="Why am I not filling the window?" Width="200" Height="20" />
  ...
</Grid>

Just remove the Width and Height attributes:
<Grid>
  <Button Content="Ahhh... problem solved" />
  ...
</Grid>

2. Containing panel squeezes control to minimum size
Another common mistake is to have the containing panel squeezing your control as tight as it will go.  For example a vertical StackPanel will always squeeze its contents vertically as small as they will go:
<StackPanel>
  <Button Content="Why am I squished flat?" />
</StackPanel>

Change to another Panel and you'll be good to go:
<DockPanel>
  <Button Content="I am no longer squished." />
</DockPanel>

Also, any Grid row or column whose height is "Auto" will similarly squeeze its content in that direction.
Some examples of containers that don't squeeze their children are:

ContentControls never squeeze their children (this includes Border, Button, CheckBox, ScrollViewer, and many others)
Grid with a single row and column
Grid with "*" sized rows and columns
DockPanel doesn't squeeze its last child
TabControl doesn't squeeze its content

Some examples of containers that do squeeze their children are:

StackPanel squeezes in its Orientation direction
Grid with an "Auto" sized row or column squeezes in that direction
DockPanel squeezes all but its last child in their dock direction
TabControl squeezes its header (what is displayed on the tab)

3. Explicit Height or Width further out
It's amazing how many times I see Grid or DockPanel given an explicit height and width, like this:
<Grid Width="200" Height="100">
  <Button Content="I am unnecessarily constrainted by my containing panel" />
</Grid>

In general you never want to give any Panel an explicit Height or Width.  My first step when diagnosing layout problems is to remove every explicit Height or Width I can find.
4. Window is SizeToContent when it shouldn't be
When you use SizeToContent, your content will be squeezed to minimum size.  In many applications this is very useful and is the correct choice.  But if your content has no "natural" size then you'll probably want to omit SizeToContent.

A:

You can do what you want by just saying DockPanel LastChildFill="True" and then making sure what you want to be the filler is actually the last child!
The Grid is the beast of a layout that you can make do most anything, but the DockPanel is usually the right choice for your outermost layout panel. Here is an psuedocode example:
<DockPanel LastChildFill="True">
    <MyMenuBar DockPanel.Dock="Top"/>
    <MyStatus DockPanel.Dock="Bottom"/>

    <MyFillingTabControl />
</DockPanel>

A:

just wrap your controls in a grid with two rows. The grid will automatically use all space given to it and you can define the rows to take up all space left by giving them a height of "*". The first row in my example (Height="Auto") will take as much space as needed by the ribbon. Hope that helps.
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>

  <Ribbon Grid.Row="0" />

  <TabPage Grid.Row="1" />
</Grid>

By adding the "Grid.Row=.." attribute to child controls of the grid they get assigned to rows of the grid. Then the grid will size it's children as defined by the row definitions.


Q:

Applying aggregate function on columns of Pandas pivot table

I generated the following pivot table via taking maximum of values in Z column:
   val
X   x1     x2
Y   y1  y2 y1  y2
ID
a    9   1  5  11
b    8  10  7   6

After taking max on Z values, I need to report mean(y1,y2). The desired table is:
    val
X    x1          x2
Y    mean(y1,y2) mean(y1,y2)
ID
a    5           8
b    9           6.5

How can I achieve this using pandas?
My MWE:
#!/usr/bin/python
from pandas import DataFrame
import pandas as pd
import numpy as np

data=pd.read_table('data.txt')
pv=data.pivot_table(index=['ID'], columns=['X','Y'], values=['val'], aggfunc=np.max )
print pv

data.txt:
ID  X   Y   Z   val
a   x1  y2  z1  1
b   x1  y1  z2  2
a   x2  y2  z2  3
a   x1  y1  z4  4
a   x2  y1  z1  5
b   x2  y2  z3  6
b   x2  y1  z2  7
b   x1  y1  z3  8
a   x1  y1  z3  9
b   x1  y2  z3  10
a   x2  y2  z2  11

A:

You can pass a level param and axis to calc the mean for the desired axis level:
In [142]:
pv.mean(level='X', axis=1)

Out[142]:
X   x1   x2
ID
a    5  8.0
b    9  6.5


Q:

CMake, subdirectories and Google Test (mock) not linking properly. Tests not found

I have a directory structure like this:
ProjectFolder
\--googletest (default google test layout)
|--source
|  \--test
|  |  \--CMakeLists.txt
|  |  |--test_Some.cpp
|  |--CMakeLists.txt
|  |--some.cpp
|  |--some.hpp
|--CMakeLists.txt
|--main.cpp (normal main)
|--maintest.cpp (empty)

ProjectFolder/CMakeLists.txt:
project(ProjectFolder)

include_directories(
    ${CMAKE_CURRENT_SOURCE_DIR}/source
    ${gmock_SOURCE_DIR}/include
    ${gtest_SOURCE_DIR}/include
)
add_subdirectory(googletest)
add_subdirectory(source)

add_executable(ProjectFolderTest maintest.cpp)
target_link_libraries(ProjectFolderTest source sourceTest gmock gmock_main)

ProjectFolder/source/CMakeLists.txt
add_library(source some.cpp)
add_subdirectory(test)

ProjectFolder/source/test/CMakeLists.txt
add_library(sourceTest test_Some.cpp)

This sadly does not work. sourceTest is never really linked (it seems). When I remove the source library from target_link_libraries I normally would expect undefined references but even that doesn't happen.
When I add a #warning to test_Some.cpp I do see the warning passing by.
If I remove sourceTest from target_link_libraries and add a hard reference to add_executable directly to source/test/test_Some.cpp I do get tests added and they run just fine.
How do I get this to work using add_subdirectories without having to add all the files in one CMakeLists.txt? Or what should I be doing different overall?
(Just trying to learn how to use CMake). I can't use the proposed option to download googletest from the interwebs using ExternalProject because I am evaluating CMake for a project where we have to have specific versions inside our own VCS.

A:

I am not really sure, but it might be connected to this issue.
Since you didn't post your tests source code I cannot really tell, if your solution should work or not, however I strongly recommend the following structure:
ProjectFolder
|--googletest (default google test layout)
\--source
|  |--CMakeLists.txt
|  |--main.cpp (normal main)
|  |--some.cpp
|  |--some.hpp
\--test
|  |--CMakeLists.txt
|  |--maintest.cpp (not empty)
|  |--test_Some.cpp
|--CMakeLists.txt

Then, the test's CMakeLists.txt might look like this:
enable_testing()
set(MY_TEST_FILES maintest.cpp
    test_Some.cpp)
add_executable(ut-myTest ${MY_TEST_FILES})
target_link_libraries(ut-myTest gmock SomeOtherLibrary)
add_test(MyTest ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/ut-myTest)

And your test's main should look like this:
#include "gmock/gmock.h"

int main(int argc, char **argv) {
  ::testing::InitGoogleMock(&argc, argv);
  return RUN_ALL_TESTS();
}

EDIT =====
Just a clarification: add_test directive just allows you to run your tests with make test. You can still use your tests without it, just by executing the binary ut-myTest.