text:
Q: Intensity of an ultrasound beam? I am working through question 9.1 (link to Google Books) of 'Fundamental Physics for Probing and Imaging' by Wade Allison. The question involves finding the varies quantities (such as pressure difference, particle velocity) etc. of a ultrasound wave of a given frequency $f$, intensity $I$, density $\rho$ and phase velocity $v_\phi$.
To do this question I have been using velocity potential $\phi=Ae^{i(kx-\omega t)}$. From which the pressure is given by:
$$p=\rho A i \omega e^{i(kx-\omega t)}$$
and velocity:
$$v=Aik e^{i(kx-\omega t)}$$
From this we can find the intensities as:
$$I=\left<pv\right>$$
$$=\frac{\rho_0}{2} A^2 \omega k$$
From which I can find $A$ and therefore the amplitude of the pressure and velocity. I have crossed checked this method with other sources and it seems to work ok. But in this case my values of $p$ and $v$ seem to be a factor of $\sqrt{2}$ out from what they should be (i.e compared to those given in the book (link to Google Books)). I was wondering if their was a reason for this discrepancy? Are there for example two different ways to define intensity or do reflected waves also need to be considered?


text:
Q: ERROR: BUILD:10:1: //:greeter: no such attribute 'src' in 'java_library' rule Got the following exception when compiling a Java project via Bazel.
BUILD:10:1: //:greeter: no such attribute 'src' in 'java_library' rule

BUILD file:
load("@rules_java//java:defs.bzl", "java_binary")

java_binary(
        name="ProjectRunner",
        srcs = ["src/main/java/com/example/ProjectRunner.java"],
        main_class = "com.example.ProjectRunner",
        deps = [":greeter"],
)

java_library(
        name="greeter",
        src=["src/main/java/com/example/Greeting.java"],
)

A: The problem is caused by the fact that the attribute name in the java_library rule in the BULID file is: srcs not src.
load("@rules_java//java:defs.bzl", "java_binary")

java_binary(
        name="ProjectRunner",
        srcs = ["src/main/java/com/example/ProjectRunner.java"],
        main_class = "com.example.ProjectRunner",
        deps = [":greeter"],
)

java_library(
        name="greeter",
        **srcs**=["src/main/java/com/example/Greeting.java"],
)

Compiled and now running.
INFO: Analyzed target //:ProjectRunner (1 packages loaded, 4 targets configured).
INFO: Found 1 target...
Target //:ProjectRunner up-to-date:
  bazel-bin/ProjectRunner.jar
  bazel-bin/ProjectRunner
INFO: Elapsed time: 0.079s, Critical Path: 0.00s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve filter data on DjangoObjectType Good morning,
I have created with graphene django a DjangoObjectType that returns several pieces of information.
Among which I have integrated django_filters to filter the data.
Is it possible to retrieve the values of the filters inserted on the frontend side to read them in DjangoObjectType and so return some information?
thanks


text:
Q: Method argument validation of complex types I'm a fan of argument validation in methods. Something like this is commonly seen in my code:
public void Foo(string someString)
{
    #region parameter validation
    if(string.IsNullOrWhiteSpace(someString))
        throw new ArgumentNullException("someString");
        // Let's ignore the .NET 4.6 nameof-feature for the sake of this question.
    #endregion

    // do things
}

Now let's say the method doesn't accept a string, but a complex object. Let's say I want the method to validate whether a property of this complex object is set. What would be the correct way to do this? Up until now I've done it like this:
public void Foo(Person person)
{
    #region parameter validation
    if(person == null)
        throw new ArgumentNullException("person");
    if(string.IsNullOrWhiteSpace(person.Name))
        throw new ArgumentNullException("person.Name");
    #endregion

    // do things
}

Is there some best practice for this? Is ArgumentNullException the correct way to go? Is checking properties like this even recommended?

A: In my case, all my models have a Validate method, this way I just call it and if it returns false (which means I got errors) I call another method to get the errors from it and display to the user, something like this:
if (person == null)
    throw new ArgumentNullException (nameof (person));

// Validates only 1 property.
if (!person.Validate (nameof (person.MyProperty)))
    DisplayErrors (person);

// Validates all properties.
if (!person.Validate ())
    DisplayErrors (person);

The reason behind it is that in most cases I have to allow the model to be invalid while the user is filling the information. I use these method with the interface INotifyDataErrorInfo for WPF to enable the UI to refresh when errors occur.
When only part of object is required for a method or operation, a facade model is the solution where you create a new class that envelopes your more complex one, and the facade class have the Validate method too to do partial validation.

A: You might consider code contracts.  Certainly, checking as you have shown is a perfectly fine way to validate parameters ... assuming that you are only validating the fields that you are using.  Validating fields that you don't reference is asking for trouble (unless that is the explicit purpose of the method).
The newest version of C# provides a '?.' operator which lets you do things like this:
int? length = customers?.Length;

or
string name = person?.Name;

This allows you to protect yourself from null reference exceptions and may in some cases be preferable to pre-validation.
Oh, and running the code analysis tool generally flags using parameters before they are validated, so at least that tools considers it a best practice.
Update (in response to comment):
It largely depends on what you are trying to do.  If you are creating an API and want to return the best error message possible, then what you have suggested it probably about the best you can do.  This assumes you are mainly concerned with communicating with your API's consumer.
If your main interest is insuring that the data provided to your method is valid and will not cause your method to behavior poorly (CYA) you should look into contracts.  Contracts have the advantage of providing post conditions (assuring your method didn't return something unexpected) and invariant conditions (assuring to haven't changes something you didn't intend to).    Contracts can provide both static (compile time) assurances as well as runtime assurances.  There is a fairly fine grained way to manage contract options.  Runtime contract violations generate contract exceptions which people may be less familiar with.  Compile time complaints may also not be familiar to users.
This assumes you are mainly concerned with assuring proper operation or not getting blamed for misuse of your API.
You can use both, for example using Contracts for compile time checks and simpler 'if' checks for runtime.

A: To me, sounds like a design issue for 99% of the cases. Is a person valid without a name? I suspect not. And if not, why do you allow one to be created without one? And if you (for some reason) do allow it, isn't it the responsibility of the object to maintain it's own "valid-ness"? I would lean on something like data annotations to markup with metadata the required states, and simply check that the passed in person is "valid"

A: It seems there is no offical correct way of doing this, so I will stick to my own way, which is
if(myComplexObject.SomeProperty == null)
    throw new ArgumentNullException("myComplexObject.SomeProperty");

The caller will instantly know what's wrong.
Note that I don't use the nameof-operator, because that again would just give me SomeProperty instead of myComplexObject.SomeProperty. I could do nameof(myComplexObject) + "." + nameof(myComplexObject.SomeProperty, but I need to give that some more thought, doesn't look right on the first glance.
And here are my reasons why I think the other approaches are worse than mine:
Some said I should validate in the model, which I won't do because the model does not know how the object has to be validated for methods it doesn't know. If it's the overall object instance validity, sure, stick it in the model or if you ask me even a business layer for business validations, but this is not that situation.
Others said I could just use the null-coalescing operator (?. in C#), which I also won't do, because it's not a "if null then just work with that" scenario, but a "I will not do a thing if this is null, and you should feel bad for giving me null, fix your code" scenario.
Then there are code contracts, which provide a sweet way of validating arguments and have some more really nice benefits, but ultimately the same question arises: how can I tell the caller which value exactly of a complex object is invalid? He needs to know that property X of argument Y is wrong, nothing less. Although code contracts aren't the answer to my question, I think my answer can be used there as well, if the same situation occurs.
And then there was a suggestion that I should not validate the properties of objects in that place, but in the function where it's needed. The thing is, the property is barely used to be passed as a single separated value to another function. Plus it would kind of battle the idea of interfaces.


text:
Q: Enable Handler Class Methods to Yield Instance Attribute in Pyosmium This question is regarding the package pyosmium specifically. I was just wondering if the following functionality is possible, and if not how it could be implemented.
I want to stream/yield certain instance attributes instead of updating them in-memory.
Currently we can do the following:
class Handler(osmium.SimpleHandler):
    def __init__(self):
        osmium.SimpleHandler.__init__(self)
        self.edge_and_nodes = []
    def way(self, w):
        self.edge_and_nodes.append({'edge_id': w.id,
                                        'nodes': [w.nodes[i].ref for i in range(len(w.nodes))]})
h = Handler()
h.apply_file("test.osm.pbf")
print("Edges and their connected nodes: {}".format(h.edge_and_nodes))

However, when dealing with large regions this is not scalable.
I would like a way of yielding a dictionary object that includes WayIds and related NodeIds (as well as tags, etc) for every WayObject. Is this possible?
I am looking for something like this:
class StreamHandler(osmium.SimpleHandler):
    def __init__(self):
        osmium.SimpleHandler.__init__(self)
        self.edge_and_nodes = []
    def way(self, w):
        yield {'edge_id': w.id,
               'nodes': [w.nodes[i].ref for i in range(len(w.nodes))]}
h = StreamHandler()
h.apply_file("test.osm.pbf")
for row in h.way(w):
    print(row)

But I am not sure how to pass the w parameter (WayObject) since that seems to be dealt with internally using the apply_file() method (and I can't seem to find the source code for that method).


text:
Q: Dúvidas sobre o uso do Git Criei um novo projeto no Github e depois tentei dar o git push para subir os arquivos que estavam na minha máquina. Fiz os procedimentos básicos necessários (acho) para dar certo, mas está dando erro de failed to push some refs.
Segui mais ou menos este tutorial (a partir do 2º passo, o restante já havia feito).
Outra coisa que não entendo são os conceitos de master, branches e merge. Já olhei este guia, mas ainda estou perdido.

A: Você precisa primeiro puxar as alterações que as outras pessoas fizeram (com git pull), integrá-las ao seu projeto para então subir as suas alterações (com git push).
Outra coisa: esse procedimento vale para o Git, e não necessariamente para a hospedagem do Github. Pode ser também Bitbucket ou mesmo uma solução in-house.
Sobre sua dúvidas quanto ao uso do Git, recomendo esses dois links:

*

*http://try.github.io/ – um tutorial interativo sobre os comandos mais comuns do Git, e

*https://www.atlassian.com/git/workflows – um documento descrevendo diversas maneiras de se trabalhar com Git, todas elas muito bem explicativas!

A: Recomendo que você leia Git Guide. Algumas considerações:

*

*Você pode criar uma repositório local, e depois adicionar uma origem

*você pode clonar um projeto

No final os 2 acima darão o mesmo resultado.
Depos de ter um projeto, você precisa versionar o seu código (suas alterações):

*

*Você tem de adicionar os arquivos na index do git, algo assim:
c:\>projeto\git add *

*Dar o commit:
c:\>projeto\git commit -m "Coisas que fiz no código"

*Neste momento o seu código já esta versionado! Mas esse versionamento é local para enviá-lo para o servidor você tem de fazer um push :
c:\>projeto\git push origin master


text:
Q: Operator overloading crash So I'm following along with this book called SDL Game Development by Shaun Mitchell. I've ran into a few hiccups with code from the book but have so far been able to figure it out and correct on my own but this one has got me in a bind.
The program compiles fine but crashes with a seg fault.
This is the Vector2D class that the book has me write:
#ifndef __Vector2D__
#define __Vector2D__

#include <math.h>

class Vector2D
{
public:
    Vector2D(float x, float y) : m_x(x), m_y(y) {}

    float getX() { return m_x; }
    float getY() { return m_y; }

    void setX(float x) { m_x = x; }
    void setY(float y) { m_y = y; }

    float length() { return sqrt(m_x * m_x + m_y * m_y); }
    Vector2D operator+(const Vector2D& v2) const
    {
        return Vector2D(m_x + v2.m_x, m_y + v2.m_y);
    }
    friend Vector2D& operator+=(Vector2D& v1, const Vector2D& v2)
    {
        v1.m_x += v2.m_x;
        v1.m_y += v2.m_y;

        return v1;
    }
    Vector2D operator*(float scalar)
    {
        return Vector2D(m_x * scalar, m_y * scalar);
    }
    Vector2D& operator*=(float scalar)
    {
        m_x *= scalar;
        m_y *= scalar;

        return *this;
    }
    Vector2D operator-(const Vector2D& v2) const
    {
        return Vector2D(m_x - v2.m_x, m_y - v2.m_y);
    }
    friend Vector2D& operator-=(Vector2D& v1, const Vector2D& v2)
    {
        v1.m_x -= v2.m_x;
        v1.m_y -= v2.m_y;

        return v1;
    }
    Vector2D operator/(float scalar)
    {
        return Vector2D(m_x / scalar, m_y / scalar);
    }
    Vector2D& operator/=(float scalar)
    {
        m_x /= scalar;
        m_y /= scalar;

        return *this;
    }
    void normalize()
    {
        float l = length();
        if (l > 0)
        {
            (*this) *= 1 / 1;
        }
    }
private:
    float m_x;
    float m_y;
};

#endif // __Vector2D__

This is a Player class' input handling event where the program begins to crash:
void Player::handleInput()
{
    Vector2D* vec = TheInputHandler::Instance()->getMousePosition();

    m_velocity = (*vec - m_position) / 100;
}

It crashes at m_velocity = (*vec - m_position) / 100; which of course traces back to my Vector2D class' operator-. m_velocity and m_position are both Vector2Ds. Replacing the - with + produces the same crash.
Any help with what may be wrong would be super appreciated.

A: Vector2D* vec = TheInputHandler::Instance()->getMousePosition();

You made it a pointer, but never allocated memory for it. (unless that's what that function does..?)
There is no need to make this a pointer if you're not going to pass it anywhere.


text:
Q: How to capture syntax errors from formula entries in cells? I have a sheet which logs formula attempts by my students on another sheet in the same workbook. I want to see their different formula attempts when they submit the logs to me, but I'd especially like to see their syntax errors, although I'm not sure of the object or attribute to get the formula from before it is checked for syntax. The normal range("A1").formula is not changed when the syntax error occurs.
Example:
In cell A1, =TODAY(B1) generates a syntax error and results in a message box with a warning. The user is then returned to the worksheet with the cell still in edit mode. I suspect no attribute of range("A1") has changed.
Do I need to get the attribute of a different object to find the formula the user attempted before the warning message?
I googled for days, and no luck. Any insight much appreciated.


text:
Q: After precompiling assets for production, I get "File to import not found or unreadable: fonts." error in development I have a Rails 4 app with a fonts directory in the assets folder, along with the usual stuff. I precompiled my assets for production, but now when I try to work locally I get:
Sass::SyntaxError
File to import not found or unreadable: fonts.

The whole error looks like this:

Haven't had much luck finding an answer. Thanks.
EDIT
I tried moving my assets into the assets block in the gemfile but that did nothing. Before that they weren't in any block, didn't work there either.
application.rb
require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Atbp
  class Application < Rails::Application
    config.assets.paths << Rails.root.join("app", "assets", "fonts")
  end
end

A: In your config/application.rb, look at your config.assets.paths line. It should include 'fonts'.
config.assets.paths << Rails.root.join("app", "assets", "fonts")

Edit
After that, your fonts should be available with the font-path helper:
@font-face
  font-family: 'FontName'
  src: url(font-path('font-name.eot'))
  ...

A: Turns out I was trying to @import "fonts", which is a directory and not a file. So as @nickcoxdotme suggested, I added
config.assets.paths << Rails.root.join("app", "assets", "fonts")

to application.rb
In addition, I was calling my fonts in the scss file like so:
@font-face {
  font-family: 'hamilton19';
  src: asset_url('hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.eot');
  src: asset_url('hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.eot?#iefix') format('embedded-opentype'),
    asset_url(hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.woff') format('woff'),
    asset_url('hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.ttf') format('truetype'),
    asset_url('hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.svg#MonoSocialIconsFont') format('svg');
  src: asset_url('hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

When I needed to be calling them with font_url and '/assets/ in the path.
@font-face {
  font-family: 'hamilton19';
  src: font_url('/assets/hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.eot');
  src: font_url('/assets/hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.eot?#iefix') format('embedded-opentype'),
     font_url('/assets/hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.woff') format('woff'),
     font_url('/assets/hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.ttf') format('truetype'),
     font_url('/assets/hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.svg#MonoSocialIconsFont') format('svg');
  src: font_url('/assets/hamilton_wood_type_foundry_-_hwtunitgothic-719-webfont.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}


text:
Q: Disable "Place order" button for specific shipping method in WooCommerce I would like to disable the "Place order" button when a specific shipping method is selected, a bit like in "Disable "Place order" button for specific shipping zone in WooCommerce" answer to my previous question, but for a specific Shipping Method instead of a Shipping Zone.
The name of the related shipping method is "LATAM".
Any help is appreciated.

A: First you need to inspect the shipping methods radio buttons, to find out the shipping method ID corresponding value to "LATAM"…

To make it work for a specific shipping method ID you will use the following:
add_filter('woocommerce_order_button_html', 'disable_place_order_button_html' );
function disable_place_order_button_html( $button ) {
    // HERE define your targeted shipping method id
    $targeted_shipping_method = "flat_rate:14";

    // Get the chosen shipping method (if it exist)
    $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');

    // If the targeted shipping method is selected, we disable the button
    if( in_array( $targeted_shipping_method, $chosen_shipping_methods ) ) {
        $style  = 'style="background:Silver !important; color:white !important; cursor: not-allowed !important; text-align:center;"';
        $text   = apply_filters( 'woocommerce_order_button_text', __( 'Place order', 'woocommerce' ) );
        $button = '' . $text . '';
    }
    return $button;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.


text:
Q: Linked Table Shows As read only I am using C# to create a SQL Server view, then open an access database and link the table into access.  The create view statement, open database statement and link statement work great BUT the catch here is it will always link the table as read-only.  What piece o'code do I need to add or update current so that the view is not always linked as read-only?
string MasterDatabase = "R:\\Testing\\MasterDatabase.mdb";
DAO.Database dd;
DAO.DBEngine db = new DAO.DBEngine();
DAO.TableDef tdf9;
bool found = false;
DAO.TableDef tdf1;
string Table = "ServiceEntranceLog";
string TableAccess = "Service_Entrance_Log";

using (var connection = new SqlConnection(ConnectionStringHere))
using (var command = connection.CreateCommand())
{
            using (var command4 = connection.CreateCommand())
            {
                            command4.CommandText = "CREATE VIEW HelperView" AS SELECT * FROM monster.ServiceEntranceLog";
                            command4.ExecuteNonQuery();
            }
}
if (_combobox1.SelectedItems.Contains("MasterDatabase"))
{
            dd = db.OpenDatabase(CRDB);
            try
            {
                            string[] tableNames = new string[1] { TableAccess };
                            for (int q = tableNames.GetLowerBound(0); q <= tableNames.GetUpperBound(0); q++)
                            {
                                            foreach (DAO.TableDef tabledef in dd.TableDefs)
                                            {
                                                            string name = tableNames[q];
                                                            if (tabledef.Name == name) { found = true; }
                                                            try { if (found) { dd.TableDefs.Delete(name); } }
                                                            catch { }
                                            }
                            }
            }
            catch { }
            tdf1 = dd.CreateTableDef(TableAccess);
            tdf1.Connect = connectionString;
            tdf1.SourceTableName = Table;
            dd.TableDefs.Append(tdf1);
}

A: Alritey, so it seems the issue is I needed to define a primary key when linking in the table into access so that the table would be updateable.  Using this syntax does the trick
dd.Execute "CREATE UNIQUE INDEX SomeIndex ON SomeTable (PrimaryKeyColumn) WITH PRIMARY"


text:
Q: CKEditor 4 in Vue - how to prevent word breaking? In my Vue project I have a CKEditor. The problem with it is that it breaks words instead of breaking spaces:

In code inspector it looks like this:

I can't find a way to make it break on spaces instead of words. I tried to put white-space: nowrap; on the body (in the debugger, just to see if it works), but it just made all this text appear in one line. word-break: keep-all; didn't do anything.
One thing I must notice - I don't have defined width on the editor component. It just uses all available space.
Is there anyway to still make it break white spaces instead of words? Any suggestions?

A: Found sort of a solution, perhaps could be useful to somebody. The issue is with   entities. Basically CKEditor creates one very long string, which doesn't have spaces. I solved it by running the following method, which replaces all the  s with regular spaces, on every content change and passing the content as argument:
const removeNBSP = (text: String) => {
  return text.replace(/ /g, " ")
}


text:
Q: How to call the html function while loading the html file in webview? I was facing an issue for calling the htmnl function from xcode ,Here i am writing the code of both Html and objective-c ,
This is html function
<script type="text/javascript">
        function load(val)
        {
            alert(val);
            document.getElementById("h_dvid").value=val;
        }

   </script>

In viewcontroller viewdidload i am calling that function like this,
- (void)viewDidLoad
{
    [super viewDidLoad];
    web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 360)];
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
                                                                          pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];
    [self.view addSubview:web];

    NSString* str=[NSString stringWithFormat:@"load('%@')",@"hi"];

    [web stringByEvaluatingJavaScriptFromString:str];

    web.delegate=self;
    // Do any additional setup after loading the view, typically from a nib.

}
then i was not getting call the load function due to html file is not loaded fully so,
I had taken a button when i clicked on that button then i called the html function then its working fine.BUT i need to call HTML function in viewdidload itself.I am waiting for your answer.

A: When you call loadRequest: on UIWebView it will start loading the URL. This is asynchronous process. Until this completes, UIWebView will not have effect by calling stringByEvaluatingJavaScriptFromString: method.
Implement this UIWebViewDelegate method and call the required JS function.
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString* str=[NSString stringWithFormat:@"load('%@')",@"hi"];
    [web stringByEvaluatingJavaScriptFromString:str];
}

Hope that helps!


text:
Q: How to get the sum based on multiple conditions in power bi? Hi I'm a beginner in power BI and would like some help with a problem I have.
I need to have the sum of value for each combination of "order no", "line no", "rel no" ONLY for the highest value of "shipment no" and where "is last snapshot" = 1
So for example:
data
here I want to only sum the marked values
I tried the following:
result
But I wanted to only see the marked values and the sum should be 3000.
How can I do this in power BI? Any help will be greatly appreciated!

A: You can use a measure like this:
Value Measure =
VAR _tbl =
    SUMMARIZE (
        'Table' ,
        'Table'[order no] ,
        'Table'[line no] ,
        'Table'[rel no] ,
        "value",
        VAR _shipment = MAX ( 'Table'[shipment no] )
        RETURN CALCULATE (
            SUM ( 'Table'[value] ) ,
            'Table'[is last snapshot] = 1 ,
            'Table'[shipment no] = _shipment
        )
    )
RETURN
SUMX (
    _tbl ,
    [value]
)

It's not pretty, perhaps it can be done in a better way. Result in a table visual:


text:
Q: How confident are we that we live in a universe that has at least a 4th spatial dimension? Modern pop culture would have us believe that there is such a thing as the 4th spatial dimension. And yes it's easily shown that $n$ dimensions is possible using math alone and 3 just happens to be our specific case. But as far as modern science goes, how confident are we that there are more than 3 spatial dimensions? Are there currently any accepted theories that rely on a 4th spacial dimension? (I'm particularly interested in this answer) I was provoked when I looked up how at the quantum level particles seem to pop in and out of existence. A simple write off that pop culture uses is that these particles are just "passing through" our 3D space as they travel fully through their higher dimensions. Is there much of a consensus on this?
Also please let's avoid discussion of time being the 4 dimension if at all possible. I'm speaking of space only.


text:
Q: How to count observations satisfying specific criteria in R I have the following dataframe:
  df <- structure(list( data = structure(1:10, .Label = c("Ind_1", "Ind_2", "Ind_3" , "Ind_4" , "Ind_5" , "Ind_6"
, "Ind_7" , "Ind_8" , "Ind_9" , "Ind_10" ), class = "factor"),
    hoursworked_week = c(4,9,12,45,23,18,23,45,16,7), job_status = c(4,2,1,7,4,5,3,2,4,4)),
                class = "data.frame", row.names=c(NA,-10L))

     data hoursworked_week job_status
1   Ind_1                4          4
2   Ind_2                9          2
3   Ind_3               12          1
4   Ind_4               45          7
5   Ind_5               23          4
6   Ind_6               18          5
7   Ind_7               23          3
8   Ind_8               45          2
9   Ind_9               16          4
10 Ind_10                7          4

I wish to count how many have hoursworked_week <= 20 & job_status == 4
I tried
count(df$hoursworked_week <= 20 & df$job_status == 4 but it doesn't work


text:
Q: Pandas: Flatten dict values in DataFrame I've come across this problem very often now: I've got a nested dict (typically from an API / JSON payload) and need to flatten in for consumption as tabular data.
Example:
invoices = [
    {
        'id': 1,
        'currency': 'GBP',
        'lines': [
            {'line_id': 1, 'product': 'pencils', 'quantity': 100, 'price': 20},
            {'line_id': 2, 'product': 'erasers', 'quantity': 50, 'price': 10}
        ]
    },
    {
        'id': 2,
        'currency': 'USD',
        'lines': [
            {'line_id': 1, 'product': 'TV', 'quantity': 2, 'price': 800}
        ]
    }
]

pd.DataFrame(invoices) gives me a DataFrame with two lines, i.e. one per invoice. I can expand that to a per-line DataFrame as pd.DataFrame(invoices).explode('lines'), but then I have dicts in the lines column. How do I split/explode those dict keys into DataFrame columns?

A: Turns out that the latest version of pandas allows custom accessors, which you can use to make this possible:
# create per-line dataframe, as in the question
df = pd.DataFrame(invoices).explode('lines')

pd.concat([
    df.drop(columns=['lines']),  # remove nested column
    df['lines'].dict.explode()   # add flattened columns
], axis=1)

In order to be able to do this, you first need to define the .dict accessor:
@pd.api.extensions.register_series_accessor('dict')
class DictAccessor:
    def __init__(self, pandas_obj):
        self._obj = pandas_obj

    def __getitem__(self, key):
        return self._obj.apply(curried.get(key))

    def explode(self):
        return self._obj.apply(pd.Series)

This accessor also allows you to access individual keys in the dict, e.g.:
df = pd.DataFrame(invoices).explode('lines')

# total quantity across all invoices
df['lines'].dict['quantity'].sum()

# total cost per invoice
df.groupby('id').apply(lambda group: group['lines'].dict['price'].sum())

A: A refinement to my previous answer.  This one retains the identifying columns:
df = pd.DataFrame(invoices).explode('lines')
df.apply(lambda x: x[['id','currency']].append(pd.Series(x['lines'])), axis=1)

Which delivers:
   id currency  line_id  product  quantity  price
0   1      GBP        1  pencils       100     20
0   1      GBP        2  erasers        50     10
1   2      USD        1       TV         2    800


text:
Q: Insert element into vector of string sets c++ How to insert a element into vector of sets. Set is structure where I can not use indexing, or begin(), end(). I could only use insert(), and erase() methods. And how is this structured in memory?
This part of code is not working, it shows error in timovi[i].insert('A'), also in timovi.insert('A'); I am trying to print those elements to. I have also included sets, vectors and everything that is used in programm.
For explanation,
timovi means teams, br_timova is number of teams and vel_tim is number of elements in set.
std::vector<std::set<std::string>> timovi;
     for(int i (0); i < br_timova ; i++){
            timovi.push_back(std::set<std::string>());
            for(int j (0); j < vel_tim ; j++ ){
                timovi[i].insert( 'A' );
            }
        }

        for(int i (0); i < timovi.size();i++){
            for(auto x : timovi[i]) std::cout<<x<<" ";
            std::cout<<std::endl;
        }

A: This code
timovi[i].insert('A')

has an issue that can be simplified to:
std::set<std::string> s;
s.insert( 'A' );

problem is that std::set::insert() in this case expects std::string but you  provide single char 'A' and there is no implicit conversion from char to std::string. You can create string from a single char:
s.insert( std::string( 1, 'A' ) ); // one char

or simply using string literal:
s.insert( "A" ); // note double quotes

or maybe you suppose to have std::set<char> instead.


text:
Q: In the server it is uploading but the pdf is not opening it says the attachment has some error I generated the pdf in my iphone app, now i want to send that pdf to server. for that i am converting to NSData and i am sending.
I searched in google and i find solution by using "POST" but it is working for images.
In the server it is uploading but the pdf is not opening it says the attachment has some error
In the following code i did this:
NSData *pdfdata = [[NSData alloc] initWithData:[self.pdfFilePath dataUsingEncoding:NSASCIIStringEncoding]];
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MainUrl,@"updatefile.php"]]];
[request setDelegate:self];
        [request setPostValue:appDelegate.userId forKey:@"userid"];
         [request addData:pdfdata forKey:@"file"];
[request startSynchronous];

//self.pdfFilePath = /var/folders/a0/a01nF1oGGkebQxw7H0YsBU+++TI/-Tmp-/MyAccount.pdf;
Please guide me,
Thanks in advance.

A: Instead of this
[request addData:pdfdata forKey:@"file"];
use the below code
[request setFile:self.pdfFilePath forKey:@"file"];


text:
Q: How to pass object from array and another object in javascript I need to update the data in local db based upon the response from the server but i am getting lot of data from the server which is not needed for local db so i have manually deleted those unwanted values but i would like to do this in a dynamic way. so i have taken the columns name from local db using pragma and i compared the values which i got from the server with the names which i had stored in the array.But i would like to store the key and value in a object.can anyone tell me how to do it?
columns = ['id', 'name', 'category'];
category = {id: 122, name: 'ABD', category: 'Food', created_at: '2014-05-20', is_deleted: 'false'};

I need the result as:
  var data = {id: 122, name:'ABD', category: 'Food'};
Code:
for (var j = 0; j < columns.length; j++) {
          $log.log('Merged data is', value.category[columns[j]]);
          $log.log('Data is', data);
        }

A: You can iterate over the array and check if the element is a property in the object. If not then you can delete that property from the object.
for (var j = 0; j < columns.length; j++) {
      if(category[columns[j]] === undefined){
        delete category[columns[j]];
      }
}

Edit:
As asked in comments, if you don't want to delete the properties you can create a new object with the required properties:
var data = {};
for (var j = 0; j < columns.length; j++) {
    data[columns[j]] = category[columns[j]];
}
console.log(data);

A: A lodash one-line solution if you like:
var data = _.map(category , _.partialRight(_.pick, ['id', 'name', 'category']));

lodash docs here https://lodash.com/docs/4.17.4


text:
Q: Database Migrations and Views I am using migrator.net to handle database migrations for SQL Server, and I like it so far.  The only issue I've run into is how best to migrate changes to views.  Thus far, I've been managing each update as a separate script file (which recreates the view).  This lets me go back to previous versions of the view without duplicating the code.
This approach is working okay for now, but it seems like a lot of work to make a small change to a view.  Has anyone else run into this type of problem?  Are there any libraries out there that handle view migrations more robustly?
Thanks!

A: Whenever I have to change a view, I script the change into a DROP IF EXISTS and CREATE. That's my preference, and while it seems to be more work than other methods (ALTER scripts also work), it allows version control, as you suggest.

A: Views get stored in SQL Server as a block of text, so you can refer back to them.  I can't remember what the table and column is where you will find them.  But basically that's how I understand we do not have commands to update the odd line in the proc.


text:
Q: Troubleshooting failed API Certification I have been unable to promote one of my integrator keys to production for the past few days.
I have enabled logging and can verify that I have 20+ consecutive error free API calls. Unfortunately, the review results don't give many details.
"Please ensure you have 20 or more consecutive error-free API transactions." I do.
"Verify that your transactions comply with API rules and limits." I believe am in compliant. I am not making over 1,000 api requests per hour. I am not exceeding 1 GET request per 15 minutes.
Per the documentation I've read, I feel that my integrator key should pass the review.
I am at a loss for how else I can troubleshoot the issue. Does anyone have any suggestions? Anything I may have overlooked? Are there other logs I should be looking at?
Thanks in advance.

A: I'd recommend reaching out to go-live@docusign.com and inquire about your Certification. Be sure to include your integrator key.

A: I was counting the wrong actions in my logs. While reviewing the logs, I was counting all of the actions that were made via the Docusign UI. I should have only been counting the PostEnvelope action based on my workflow.
I went through and made 20+ calls to PostEnvelope and I'm happy to say that my integrator key is now pending approval.


text:
Q: Remove SharePoint 2010 library authorization using powershell? I know it's possible to modify a library authorizations using the SharePoint UI following the steps bellow:

*

*Stop authorizations inheritance.

*Modify users authorizations.

*Select/Unselect the desired checkboxes.

*OK.
I want to add Reader authorization and remove Contributor.
How to achieve that using PowerShell?
So far, I succeeded to add new authorizations with PowerShell.
Here is the code.
$web = Get-SPWeb "http://www.whatever";
$list = $web.Lists["MyList"];
$list.BreakRoleInheritance($true,$true);
$group = $web.Groups["Members of the site"];
$roleToAdd = "Reader";
$role = $web.RoleDefinitions | where {$_.Type -eq $roleToAdd};
$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($group);
$assignment.RoleDefinitionBindings.Add($role);
$list.RoleAssignments.Add($assignment); // How to remove instead ?
$list.Update();
$web.Dispose();

Note: I do know that at least one authorization should be selected.
A solution could be to use this method. Unfortunately it's not working.
$roleToLet = "Reader"
$role = $web.RoleDefinitions | where {$_.Type -eq roleToLet };
$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($group);
$list.RoleAssignments[1].ImportRoleDefinitionBindings($assignment.RoleDefinitionBindings);
$list.Update();

A: The list assignments are obtained using the wrong method. Moreover, the assignments were not updated after modifications. Finally I used $web.SiteGroups instead of $web.Groups. It should be as following:
$group = $web.SiteGroups["Members of the site"];
$rolesToRemove = "Contributor";
$role = $web.RoleDefinitions | where {$_.Type -eq $rolesToRemove};
$assignment = list.RoleAssignments.GetAssignmentByPrincipal($group);
$assignment.RoleDefinitionBindings.Remove($role);
$assignment.update();
$list.Update();


text:
Q: Obtener el valor de una variable en una clase desde ajax, de momento el valor que obtengo es undefined estoy intentando hacer un programa con singleton, lo que se me pidio fue:
"Implementar el patrón de diseño creacional Singleton en backend, con lo que un request ya sea POST o GET, asíncrono o no, el objeto con Singleton sea accesible."
Lo primero que hice fue crear la clase singleton en c#
public class Singleton
    {
        private static Singleton instance = new Singleton();
        private Singleton() { }

        public static Singleton Instance
        {
            get { return instance; }

        }

        public string DoSomething()
        {
            string x = "Singleton funciona";
            return x;
        }
    }

despues en un aspx.cs le llamo a esta clase:
 [System.Web.Services.WebMethod()]
        public static string SingletonCall()
        {
            string x;
            Singleton mySingleton = Singleton.Instance;
            x = mySingleton.DoSomething();
            return x;
        }

y en mi html tengo un boton
<button name="btn-delete" type="button" class="btn btn-warning" onclick="Sing()" >Singleton</button>

y la funcion sing() es esta

en el succes de la funcion me aparece el alert, solo que el dato que me muestra es un "undefined" alguien tiene idea de que es lo que estoy haciendo mal? No se si estoy mal en el ajax o en el singleton


text:
Q: Python Error:Commands out of sync; you can't run this command now Here is the scenario,
I am facing the error
Error:Commands out of sync; you can't run this command now

I need to pass the string to MYSQL which is a mixture of double and Single quotes. But when the mysql parsing the string it couldnt process the parameters because Python converting "" to ''.
for example
temp = "users= JSON_ARRAY_APPEND(users, '$', 'user1'), users= JSON_ARRAY_APPEND(users, '$', 'user2')"

converted to
temp = 'users= JSON_ARRAY_APPEND(users, \'$\', \'user1\'), users= JSON_ARRAY_APPEND(users, \'$\', \'user2\')'

sql = "Insert into User(internal_id, users) values(16, IFNULL(users->'$',JSON_ARRAY())); Update User SET " + temp + " where internal_id = 16;"

How to hanndle this Scenario?
Thanks

A: Based on searching past Stack Overflow questions related to the error:

Commands out of sync; you can't run this command now

This problem is caused by executing multiple SQL statements in the same call to execute(). You can't do that unless you pass the argument multi=True.
This is the same solution as the one reported in Commands out of sync you can't run this command now
But there is no reason to use multi-statements. It is easier and more clear to write your code to execute one SQL statement at a time.
The former Engineering Manager for MySQL once told me, "there is no reason for MySQL to support multi-statements." They just make writing code more difficult, and they don't give you any advantage to performance or anything else.


text:
Q: how to increase speed of this mysql query? How I can increase speed of this search query?
This search bring news based on time and title and text. each item has own factor.
SELECT * , MATCH (`title`) AGAINST ('tax in work') * 1.65 AS `titlescore` ,
(

    (

       CASE
          WHEN time >=1432173380 THEN 21
          WHEN time >=1432162580 THEN 18
          WHEN time >=1432097780 THEN 15
          WHEN time >=1431903380 THEN 11
          WHEN time >=1431320180 THEN 7
          ELSE 0
       END
    ) * 1.75 ) AS `timescore` ,

    MATCH (`text`) AGAINST ('tax in work') * 0.65 AS `textscore`

    FROM `news`
    HAVING `titlescore` + `timescore` + `textscore` >= 35
    ORDER BY `titlescore` + `timescore` + `textscore` DESC
    LIMIT 0 , 25

Now this takes (4 to 20)sec relay on search query!
Explain query result:
id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE         news     ALL     NULL            NULL    NULL       NULL 1656038     Using where; Using filesort

Table structure:
CREATE TABLE IF NOT EXISTS `news` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` text COLLATE utf8_persian_ci NOT NULL,
  `text` varchar(400) COLLATE utf8_persian_ci DEFAULT NULL,
  `time` int(10) unsigned NOT NULL,
  `cat_id` int(10) unsigned NOT NULL,
  `source_id` int(10) unsigned NOT NULL,
  `visit` int(10) unsigned NOT NULL,
  `url` text COLLATE utf8_persian_ci NOT NULL,
  `sha1` varchar(40) COLLATE utf8_persian_ci NOT NULL,
  `title_slug` text COLLATE utf8_persian_ci NOT NULL,
  `date` varchar(10) COLLATE utf8_persian_ci DEFAULT NULL,
  `day_time` tinyint(4) DEFAULT NULL,
  `week_day` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `sha1Uniq` (`sha1`),
  KEY `cat_id` (`cat_id`),
  KEY `source_id` (`source_id`),
  KEY `time` (`time`),
  KEY `date` (`date`),
  FULLTEXT KEY `searchIndex` (`title`,`text`),
  FULLTEXT KEY `title` (`title`),
  FULLTEXT KEY `text` (`text`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=2386224 ;

A: First retrieve id and the computed scores, then sort and join the result back to news:
SET @line = 0;
SET @last = 25;
SELECT B.*,titlescore,timescore,textscore FROM
(
    SELECT id,titlescore,timescore,textscore,combinedscore,(@line:=@line+1) line
    FROM
    (
        SELECT id,
            MATCH (`title`) AGAINST ('tax in work') * 1.65 AS `titlescore`
            (
                CASE
                    WHEN time >=1432173380 THEN 21
                    WHEN time >=1432162580 THEN 18
                    WHEN time >=1432097780 THEN 15
                    WHEN time >=1431903380 THEN 11
                    WHEN time >=1431320180 THEN 7
                    ELSE 0
                END
            ) * 1.75 ) AS `timescore`,
            MATCH (`text`) AGAINST ('tax in work') * 0.65 AS `textscore`,
            MATCH (`title`) AGAINST ('tax in work') * 1.65+
            (
                CASE
                    WHEN time >=1432173380 THEN 21
                    WHEN time >=1432162580 THEN 18
                    WHEN time >=1432097780 THEN 15
                    WHEN time >=1431903380 THEN 11
                    WHEN time >=1431320180 THEN 7
                    ELSE 0
                END
            ) * 1.75 ) + MATCH (`text`) AGAINST ('tax in work') * 0.65
            AS combinedscore
        FROM news
    ) AA WHERE combinedscore >= 35
    ORDER BY combinedscore DESC
) A LEFT JOIN B news USING (id)
WHERE line <= @last;

Give it a Try !!!

A: SELECT * , MATCH (`title`) AGAINST ('tax in work') * 1.65 AS `titlescore` ,
    (
      ( CASE
          WHEN time >=1432173380 THEN 21
          WHEN time >=1432162580 THEN 18
          WHEN time >=1432097780 THEN 15
          WHEN time >=1431903380 THEN 11
          WHEN time >=1431320180 THEN 7
          ELSE 0
       END
      ) * 1.75
    ) AS `timescore` ,

    MATCH (`text`) AGAINST ('tax in work') * 0.65 AS `textscore`

    FROM `news`

    WHERE MATCH(title, `text`) AGAINST ('tax in work')  -- Added this

    HAVING   `titlescore` + `timescore` + `textscore` >= 35
    ORDER BY `titlescore` + `timescore` + `textscore` DESC
    LIMIT 0 , 25;

All I did was to add the WHERE clause.  I expect this to significantly cut down on the number of rows actually looked at.


text:
Q: On the natural homomorphism $\nu:R\longrightarrow S^{-1}R$ Let $R$ be a commutative ring with $1_R$ and $S$ an multiplicatively closed set. We  define the natural homomorphism
\begin{align*}
\nu:R &\longrightarrow  S^{-1}R, \\
a&\longmapsto \nu(a):=\frac{a}{1_R}.
\end{align*}
where $ S^{-1}R$ is the localization of $R$ on $S$.
In a proposition, I found that $\forall s\in S\subseteq R\implies \nu(s)\in U( S^{-1}R)$, because
$$\nu(s)\cdot \frac{1_R}{s}=\frac{s}{1_R}\cdot \frac{1_R}{s}=\frac{s}{s}=1_{ S^{-1}R} $$
But should it be $\forall s\in S^*:=S\backslash \{0_R\}$?
I mean that if we take $s=0_R$, then $\nu(0_R)=\frac{0_R}{1_R}=0_{ S^{-1}R}$.
 So, it is not unit.
Thank you.

A: Note that, if $0\in S$, then $S^{-1}R$ is a zero ring where everything trivially is a unit.


text:
Q: Distributing Erlang binaries to new EC2 instances I am using tools such as Chef and Puppet in order to bootstrap new EC2 instances. In order to autoscale, I try to keep the install times as fast as possible. For something such as Ruby, I compiled it on one box, then tarballed the binaries and distribute them to new instances via Amazon S3 for quick installs. I'd like to do the same for Erlang since Erlang takes quite a long time to compile and for me to autoscale app servers, I need to keep launches down to a few minutes at most. The problem is, Erlang distributes binaries and other files in a myriad of locations on the filesystem. I'm wondering if there is a trivial way to package it up so that I can simply fetch a tar ball of all required files and untag them on a machine of the same OS/architecture?

A: You should use your distro's packaging mechanism to package up Erlang itself; your application can be deployed in whatever way you choose, but following the OTP principles gets you one tree of files which can be easily copied into place, no muss, no fuss.


text:
Q: CASTING Session.Query() in Nhibernate How and What type should I cast result to User or Role or Permission?
A User has Roles and A Role has Permissions
var result = session.Query<User>()
                    .Where(c => c.UserName == userName)
                    .FetchMany(c => c.Roles)
                    .ThenFetchMany(o => o.Permissions);

A: Methods like Fetch (for simple properties) and FetchMany(for collections properties) method will create an join in the t-sql query executed by nhibernate and fill the property up after the execution. It will avoid the Lazy Loading to the property. But after you call these methods, you still have an IQueryable<User> (in your case), because you started with it.
To get a result (or make a cast), depend of how you concrete your query linq, for sample:
For a List<User>, you could call ToList():
var result = session.Query<User>()
                    .Where(c => c.UserName == userName)
                    .FetchMany(c => c.Roles)
                    .ThenFetchMany(o => o.Permissions)
                    .ToList();

// and you could loop it:
foreach (var user in result)
{
      // code...
}

For a single User object, you could call FirstOrDefault():
var result = session.Query<User>()
                    .Where(c => c.UserName == userName)
                    .FetchMany(c => c.Roles)
                    .ThenFetchMany(o => o.Permissions)
                    .FirstOrDefault();

// and you could use this User object,
// but make sure it is not null
if (result != null)
{
   // code...
}

You also can change the output using the Select() to a DTO object, an anonnymous object, an specific value, etc. For sample, to return an anonymous object (generally to use in a local scope and execute a simple query), using Select() method.
var result = session.Query<User>()
                    .Where(c => c.UserName == userName)
                    .FetchMany(c => c.Roles)
                    .ThenFetchMany(o => o.Permissions)
                    .Select(u => new { u.Id, u.UserName })
                    .ToList(); // or FirstOrDefault();


text:
Q: Overlapping contenido y footer me encuentro desarrollando un sitio y tengo un problema con la plantilla AdminLTE. No soy un experto en CSS ni mucho menos, pero el problema surge que mi contenido, solo un div que gracias a ACE Editor se convierte en un editor de texto, sobrepasa los márgenes dados y se superpone al footer.
Dejo algunas imágenes para mostrar el inconveniente; he intentado solucionarlo aplicando algunas reglas pero sin resultado positivo.
#html, body
    height:100%;
    margin:0;
    display: flex;
    flex-direction: column;

#editor
position: absolute;
    height: 73%;
    width: 81%;
    font-family: Monaco,Menlo,"Ubuntu Mono",Consolas,source-code-pro,monospace !important;
    font-size:16px;

Supongo que internamente la plantilla de AdminLTE hará uso de mediaqueries para poder ajustar el ancho-alto de cada pantalla. El problema surge cuando se re-ajusta la pantalla, el div central solapa al footer.
Desde ya, muchas gracias por todo y cualquier comentario (constructivo/educativo) es bienvenido :).

A: Después de mucho buscar, ya se había respondido algo similar.
Lo dejo para quien le sirva :)
Solución


text:
Q: Passing a string between pages in Windows Phone 8 I need to pass a simple string between two pages in Windows Phone 8. I've been searching around, trying to find the best way of doing it - but the ones i tried turned out to not work as they should - so i ask you: What is the best way to pass a simple string between two pages in Windows Phone 8. This is the method I use to navigate to the other page:
NavigationService.Navigate(new Uri("/newpage.xaml", Urikind.Relative));

A: I have to say that for simple data @McGarnagle is probably a better solution.
That said, this is also an extreamly fast and dirty way to do this. This method can also take complex objects as well.
I like using PhoneApplicationService.State which is a Dictionary<String,Object>
PhoneApplicationService.State.add("KeyName",YourObject);

Then in page two you do this
var yourObject = PhoneApplicationService.State["KeyName"];

MSDN Documentation

A: If you are using MVVM architecture,then you can pass string after registering using Messenger.
Create a model class (say PageMessage) with a string(say message) variable.
You want to pass string from homepage.xaml to newpage.xaml,then in homepage.xaml just send the message like this
Messenger.Default.Send(new PageMessage{message="Hello World"});

In the newpage.xaml,u should register the messenger like this,
Messenger.Default.Register<PageMessage>(this, (action) => ReceiveMessage(action));

 private object ReceiveMessage(PageMessage action)
 {
    string receivedMessage=action.message;
    return null;
 }

Like this you can pass anything even navigation in MVVM architecture.

A: Hy,
another solution and to create a static class with one or more properties of type string depending on what you need, it enhances the way that it is available where you need.

A: For a string variable, it's easiest to use a query string parameter:
NavigationService.Navigate(new Uri("/newpage.xaml?key=value", Urikind.Relative));

Pick it up on the target page using NavigationContext.QueryString:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if (NavigationContext.QueryString.ContainsKey("key"))
    {
         string val = NavigationContext.QueryString["key"];
         // etc ...
    }
}

Note: if your string contains only alphanumeric characters, then the above will work without modification.  But, if your string might have URL-reserved characters (eg, &, ?), then you'll have to URL-encode them.  Use the helper methods Uri.EscapeDataString and Uri.UnescapeDataString for this.
To escape:
string encodedValue = Uri.EscapeDataString("R&R");
NavigationService.Navigate(new Uri("/newpage.xaml?key=" + encodedValue, Urikind.Relative));

To unescape:
string encodedValue = NavigationContext.QueryString["key"];
string val = Uri.UnescapeDataString(encodedValue);

A: Take a look at Caliburn.micro. It is really simple to set up and lets you pass parameters through views in a strongly typed manner, like this:
public void GotoPageTwo() {
        navigationService.UriFor<PivotPageViewModel>()
            .WithParam(x => x.NumberOfTabs, 5)
            .Navigate();
}

http://caliburnmicro.codeplex.com/wikipage?title=Working%20with%20Windows%20Phone%207%20v1.1&referringTitle=Documentation


text:
Q: UITapGestureRecognizer not attaching action I created a separate class for View.
I left all the functions in the Controller.
But when I add a click on the picture, it doesn't work for some reason.
import UIKit

class APOTDView: UIView {

    var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(APOTDViewController.imageTapped(_:)))
        imageView.addGestureRecognizer(tap)

        return imageView
    }()
}

import UIKit

class APOTDViewController: UIViewController {

    let av = APOTDView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // ... add subview and constraint
    }

    @objc func imageTapped(_ sender: UITapGestureRecognizer) {
        print("good job")
    }
}

What's the matter? Please help me figure it out

A: Your selector in the UITapGestureRecognizer is wrong. You can not call the APOTDViewController directly.
APOTDViewController.imageTapped would be a static function, which is not available.
You can use a delegate instead.
Delegate Protocol and View.
protocol APOTDViewDelegate: AnyObject {
    func viewDidTapImage()
}

class APOTDView: UIView {
    weak var delegate: APOTDViewDelegate?

    var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
        imageView.addGestureRecognizer(tap)

        return imageView
    }()

    @objc func imageTapped() {
        delegate?.viewDidTapImage()
    }
}

ViewController:
class APOTDViewController: UIViewController, APOTDViewDelegate {
    let av = APOTDView()

    override func viewDidLoad() {
        super.viewDidLoad()
        av.delegate = self
        // ... add subview and constraint
    }

    @objc func viewDidTapImage() {
        print("good job")
    }
}

A: This will not work, because you are calling the UIViewController method directly without any class reference or object. The solution is to use protocol or clouser to get action from view to class.
class
class APOTDView: UIView {
    @objc var imageViewAction: ((UITapGestureRecognizer) -> Void)? = nil

    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.backgroundColor = .blue
        imageView.translatesAutoresizingMaskIntoConstraints = true
        imageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector((imageTapped(_:))))
        imageView.addGestureRecognizer(tap)
        return imageView
    }()

    @objc private func imageTapped(_ sender: UITapGestureRecognizer) {
        self.imageViewAction?(sender)
    }
}

ViewController
class APOTDViewController: UIViewController {
    let av = APOTDView()

    override func viewDidLoad() {
        super.viewDidLoad()
        av.imageViewAction = { sender in
            print("good job")
        }
    }
}


text:
Q: Trying to pick the coin with the highest bias toward heads after uneven numbers of trials of 2 coins I'm a stats noob and this isn't a homework question, but I'm just looking for a way to approach problems like this anyway - not an actual answer.

Question:
Two random coins are selected from a bag of coins which have random biases. All possible biases are equally likely.
The first coin is flipped 5 times, and the second is flipped 10 times. Here's an example of what we might get:

*

*5 flips, 5 heads

*10 flips, 9 heads

Now, the question is: Which coin should we choose if we want to maximise the chance of picking the coin that is most biased toward heads?

Attempt 1:
I think we should determine the probability distribution of the possible biases for each coin and determine which one's average/expected bias value is higher. I think these are the (relative?) probability distributions of each coin in the example I gave above:

Solving the integral of the first for half the area gives a bias of ~0.89 and the second gives ~0.85. So I think we should choose the first coin (5 flips, 5 heads) if we want to maximise the chance of picking the coin that is most biased towards heads.
Attempt 2:
Following @whuber's first comment, I see that solving the integral for the bias value at half the area will give us the median, and that's not correct. The median doesn't take into account the size of the bias values on either side of it - only how many there are.
To concretely show that the median isn't what we're looking for, here's an example of two bias distributions that have the same median bias (0.5):

The latter has a mean bias that is higher than the first one, and this seems to be the metric that I want to use to rank the distributions. I think that I can get the mean by scaling/normalising the previous bias distributions so that they're actual probability distributions, then multiplying by the bias and integrating - basically summing all possible biases weighted by their relative probabilities. Keeping everything unsimplified for explicitness:

*

*First coin: $\int_0^1 6\,b\,b^5(1-b)^0 \,db \approx 0.857$

*Second coin: $\int_0^1 110\,b\,b^9(1-b)^1 \,db \approx 0.833$

So if those calculations are correct, the first coin is the one to choose.
Does the correctness of this answer depend on the loss function that we choose? I'm not well acquainted with loss/reward stuff, but if we said that the loss/reward is equal to the difference between the chosen coin's bias and the other one's bias (such that the score is positive if our chosen coin has a higher bias, and negative if lower), then does the above solution hold? It seems like it should. What if the loss/reward weren't proportional to the difference and instead the reward was +1 if we chose the higher-biased coin, and -1 if we chose the lower one? Would this make the above approach incorrect? Perhaps I need to do some more thinking and learning about this loss function stuff and ask a separate question if I get stumped.


text:
Q: Android Blood pressure graph implementation? Thanks for reading the question, I need to implement the Blood pressure graph in my Android sample application, I attached the sample image below, Can i use third party libraries like achart engine and MPChart Android for making the graph,Any ideas and suggestions kindly share those details,

Thanks ,
Naren.S

A: I would suggest you http://www.android-graphview.org/ library. It's super easy to use. However I'm not sure how to implement the vertical lines among points since you'd have to introduce two LineGraphSeries.
But if you don't need that vertical lines, the GraphView library would be wise and easy solution :)


text:
Q: Laravel Raw Query Not Returning a Result Hard-coded query
$stock = DB::select("SELECT * FROM reports_finra WHERE symbol = ? ", array('CWCO'));     // works and returns valid result set

Array (
[0] => Array ( [query] => SELECT * FROM symbols [bindings] => Array ( ) [time] => 37.4 )
[1] => Array ( [query] => SELECT * FROM reports_finra WHERE symbol = ? [bindings] => Array ( [0] => CWCO ) [time] => 27.07 )

)
# result set when var_dump($stock)  ( [1]'s query )
array(11) {

[0]=> object(stdClass)#5939 (7) { ["date"]=> int(20140116) ["symbol"]=> string(4) "CWCO" ["id"]=> int(1498) }
[1]=> object(stdClass)#5940 (7) { ["date"]=> int(20140117) ["symbol"]=> string(4) "CWCO"  ["id"]=> int(8515) }
[2]=> object(stdClass)#5941 (7) { ["date"]=> int(20140121) ["symbol"]=> string(4) "CWCO" ["id"]=> int(15526) }

...

}

Dynamically binded variable being passed to query
$symbol = $symbol->symbol;

echo $symbol;
echo '
';

$stock = DB::select("SELECT * FROM reports_finra WHERE symbol = ? ", array($symbol));

$query = DB::getQueryLog();
print_r($query);
echo '
';
var_dump($stock); exit;

Results
CWCO             // the result from echoing $symbol

Array (         // getQueryLog()
[0] => Array ( [query] => SELECT * FROM symbols [bindings] => Array ( ) [time] => 36.06 )
[1] => Array ( [query] => SELECT * FROM reports_finra WHERE symbol = ? [bindings] => Array ( [0] => CWCO ) [time] => 27.55 ) )

array(0) { }    // var_dump($stock);

As you can see, when I pass the value of symbol into the query as a hard-coded value, I get the desired result set. However, when I pass the value in dynamically, the query returns an empty result set.
I have been going back and forth with this for quite a while now and am out of ideas on how to further troubleshoot this. Even more perplexing is the fact that these exact queries work in my dev environment but not when I pushed to prod.
Through troubleshooting, prior to realizing that when I pass in the raw, hard-coded value, that I was getting a valid result set, I ensured that there were only minor PHP / MySQL version differences between dev and prod ENVs. I triple checked that the user had the proper DB permissions. And, I tailed out my log files. None of these actually help shed any light onto what is actually going wrong here though.
As I just recently started to get back into development and have only  been playing with L4 for a week or two, I'm hoping someone with more experience will see what it is that is causing this (I have an odd feeling that it is going to be an ID10T error..).
I look forward to any advice and insight you may have to offer.
-- Edit --
As the query is returning an (empty) result back (and not throwing an error), the query appears to be "working" as far as MySQL is concerned. However, it is not returning the result set for whatever reason. I am not sure if this has to do with PDO, Eloquent, or something else entirely. It's a basic SELECT * query on a non-related table; it shouldn't be this much hassle.
And, I'm quite perplexed why the other select statements work without an issue, but this one is not. Granted, I am querying a table that is not related to the model (there is no DB/L4 relationships defined; this is a once-off Select statement in order to do some essential math).
Unfortunately, I can't proceed until I get this worked out...

A: I stated in the question that I thought this might be an ID10T error, and it was.
After doing a var_dump($symbols) on it again, and paying a little closer attention, I realized that there was a trailing space behind each of the $symbols which didn't match anything in the table. Aha! So, the query was executing successfully and returning the correct results all along; go figure. ;)
Interesting thing to note, I should have done a trim on the $symbols before inserting them into the DB table using Laravel's http://laravel.com/docs/eloquent#accessors-and-mutators as pointed out by the awesome AndreasLutro in #laravel.


text:
Q: GBM model : why is the validation accuracy fluctuating on grid search in h2o R I'm using the package H2O in R and i'm trying to improve my score with gbm model. I tried a grid search using a training and a valid sets.
But when it finished, the log loss curves between the two sets is very different. Indeed there's overfitting on my train set so the accuracy is higher than my valid set
Here on H2O, my gbm's parameters :
ntrees = 100,
max_depth = 3,
learn_rate = 0.01,
nfolds = 5,
seed = 1234

Could you give me some way to resolve my problems ?

A: For help on tuning a H2O GBM in R I would recommend reviewing this tuning guide: https://github.com/h2oai/h2o-3/blob/master/h2o-docs/src/product/tutorials/gbm/gbmTuning.Rmd.
There are a lot of reasons you could be seeing overfitting from the predictors you use, the features you engineer, the way you split up your data, and finally the way you tune your model.
Without seeing your specific dataset and the specific code you ran, it would be hard do give you an exact reason for why you are having issues with overfitting.


text:
Q: WebStorm + nvm + Typescript + ts-node + Breakpoint Debugging - Randomly Stops Working I have an issue with WebStorm that I can't seem to figure out and JetBrains hasn't been much help either.
It appears to sometimes show up, sometimes go away, and just flat out make zero sense. Debugging breakpoints in WebStorm will flat out stop working if they're inside of a non spec file function.
I'm using mocha, and my setup is as follows:

*

*nvm - using node 14.16.1

*mocha 9.02

*User interface: BDD

Env. Variables:
NODE_ENV=development;TS_NODE_FILES=true;TS_NODE_TRANSPILE_ONLY=true;TS_NODE_PROJECT=tsconfig.tests.json

Extra Mocha Options:
--require ts-node/register

Test file patterns:
src/tests/unit/**/*.ts

JetBrains had thought it was my code base, however, if I were to take and setup my other laptop with it, it breakpoints and works fine. However with WebStorm it randomly stops allowing me to breakpoint debug into nested functions...
I've tried uninstalling the nvm node version and reinstalling, wiped out node_modules and reinstalling, tried installing different node version and rebuilding node_modules. Nothing seems to resolve it.
One interesting piece, breakpoints work as expected when I don't run Spec files and run the app normally.


text:
Q: After upgrade, Duplicity with B2 Backblaze error I just upgraded to 21.04 and started getting an error with using Duplicity with B2.
Duplicity is version 0.8.17
b2 is version 2.5.0
b2sdk is 1.9.0
Each seems to work individually. When I try to run a simple test backup, the following happens
duplicity test.png b2://xxxxxx:xxxxxxxxxx@my-bucket
BackendException: B2 backend requires B2 Python SDK (pip install b2sdk)

Similar questions have been asked in the past, but the issue there seemed to be with a previous version of Duplicity, so I'm not sure what is happening there. The answers suggested in the linked question did not work for me.
I have also tried removing and reinstalling each of Duplicity, b2, and b2sdk.
Any help would be appreciated!

A: Prompted by a comment checking in on this, I will provide what ended up working for me. I removed slashes from my B2 key as suggested by this answer. I did likewise for the encryption key, passphrase, etc. just to be safe. Been working fine since then.


text:
Q: Django - How to query a related translated model? I have two models that are many to many related. Article and Tag models. Both are TranslateableModel using django-parler.
models.py
class Article(BaseModelMixin, TranslatableModel):
    translations = TranslatedFields(
        title=models.CharField(max_length=255),
        short_description=models.CharField(max_length=255),
        body=HTMLField(),
        slug=models.SlugField(max_length=255, blank=True, null=True, unique=True),
    ),
    tags = models.ManyToManyField("Tag", related_name="articles")

class Tag(TranslatableModel):
    translations = TranslatedFields(
        slug=models.SlugField(max_length=55, blank=True, null=True),
        name=models.CharField(_("Tag name"), max_length=50),
    )

I would like to get all tags together with articles_count for the current language.
For example if a user comes to the page /en/blog I would like them to see tags together with the number of articles written in english for that tag. Something like Django (7 articles), Ruby on rails (4 articles) For django there might be 10 articles but only 7 are translated to english.
What I have is something like this:
Tag.objects.translated()
           .annotate(articles_count=(Count("articles__translations")))

But this gives me the count of total translations. If an article exists both in english and in french, it counts double.
How can I make it so that it gives me the number of articles only in the current language in a given tag?

A: You can filter on the language_code, so:
from django.utils.translation import get_language

language = get_language()

Tag.objects.annotate(
    articles_count=Count(
        'articles__translations',
        filter=Q(articles__translations__language_code__iexact=language)
    )
)
This will only retain articless with the exact same language code. This thus means that if the language is en-US, it will not consider en to be valid.
You can retain only the language and not the country, and then filter with:
# culture-invariant languages

from django.utils.translation import get_language

language = get_language().split('-', 1)[0]

Tag.objects.annotate(
    articles_count=Count(
        'articles__translations',
        filter=Q(articles__translations__language_code__istartswith=language)
    )
)


text:
Q: Как с помощью innerHTML изменить слово и нажав еще раз на событие вернуть его в прежнее значение Я недавно начала изучать js, и вот когда дело дошло к DOM я столкнулась с одной маленькой проблемой, которую не могу решить. Имееться код:

function f1(){
  var a = document.getElementByTagName("p")[0].innerHTML = "home";
}

car

Тогда слово "car" измениться на слово "home". Но, что если я хочу при нажатии на тег
 так же изменить слово на "home", но когда нажму на тег еще раз, хочу что бы он изменилься обратно на "car". Может для вас это никакой проблемы не составит, но я вот уже час не могу понять, как это сделать. Буду благодарна за ответ.

A:

var a = document.getElementsByTagName("p")[0];
var text = a.innerText;

function f1() {

  if (a.innerText == 'home') {
    a.innerText = text;
  } else {
    a.innerText = 'home';
  }

}

car

document.getElementByTagName("p")[0].innerHTML - добавьте букву s после "Element"

A: В функцию f1 передаём ссылку на элемент, по которому кликнули.

function f1(element){
  console.log('Наш элемент: ', element);
  if ( element.textContent === 'car') {
    element.textContent = 'home';
  } else {
    element.textContent = 'car';
  }
}

car

UPD: В вашем коде ошибка. Вместо getElementByTagName необходимо написать getElementsByTagName. После написания любого скрипта, смотрите консоль броузера!

A: Лучше заранее обозначить все возможные варианты содержимого тега, чем сверять каждый раз его текущее значение:

var values = ['car', 'home', 'whatever'];
var current = 0;

function f1(element){
  if (++current == values.length) current = 0;
  element.textContent = values[current];
}

car


text:
Q: Converting an SQL Containing inner and Outer Joins into Linq I need to convert an SQL query to Linq/Lambda expression, I am trying doing the same but not getting the desired results.
SQL:
 SELECT b.*, n.notes
 FROM Goal_Allocation_Branch as b
 INNER JOIN Goal_Allocation_Product as g
      on b.Product = g.ProductID
     and b.Year = g.Year
 left join Goal_Allocation_Branch_Notes as n
      on b.branchnumber = n.branch
     and n.year = ddlYear
 WHERE b.Year = ddlYear
   and g.Show = 1
   and branchnumber = ddlBranch

I am new to Linq , I am getting error on Join Clause , and X is not containing any data from first Join
var result = (from br in _DB_Branches.Goal_Allocation_Branches
                          join pr in _DB_Product.Goal_Allocation_Products on  new { br.Product, br.Year } equals new {Product= pr.ProductID, Year= pr.Year }
                          join n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(n => n.Year == ddlYear) on br.BranchNumber equals n.Branch into Notes
                          from x in Notes.DefaultIfEmpty()
                          select new BranchNotesViewModel
                          {
                              Year = x.Year,
                              BranchNumber = x.Branch,
                              ProductID = x.ProdID
                          }
                          ).ToList();

Update: My First Join clause initially giving error "The type of one of the expression in Join Clause is incorrect " is resolved, when I Changed On Clause
from
"on  new { br.Product, br.Year } equals new {pr.ProductID, pr.Year}"
"on  new { br.Product, br.Year } equals new {Product=pr.ProductID,Year= pr.Year}"
still not getting desired results as expected from above SQL query. Please advise..

A: It should be something like this (see note):
var result =
 (from br in _DB_Branches.Goal_Allocation_Branches
  join pr in _DB_Product.Goal_Allocation_Products
    on br.Product equals pr.ProductID
  from n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(x=>
    x.branch == br.branchnumber
    && x.year == ddlYear
  ).DefaultIfEmpty()
  where
    br.Year == ddlYear
    && and br.Year == pr.Year
    && pr.Show == 1
    && br.branchnumber == ddlBranch
  select new BranchNotesViewModel
  {
    Year = ...,
    BranchNumber = ...,
    ProductID = ...
  }
 ).ToList();

Note: Change the select, to the properties you want.
Edit: fixed some syntax errors.

A: I finally figured out the correct answer. Working absolutely fine
var result = (from br in _DB_Branches.Goal_Allocation_Branches
                          join pr in _DB_Product.Goal_Allocation_Products on new { br.Product, br.Year } equals new { Product = pr.ProductID, Year = pr.Year }
                          join n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(n=>n.Year==ddlYear) on br.BranchNumber equals n.Branch into Notes
                          where br.Year==ddlYear
                          && pr.Show== true
                          && br.BranchNumber==ddlBranch
                          from x in Notes.DefaultIfEmpty()
                          select new BranchNotesViewModel
                          {
                             Year=x.Year,
                              BranchNumber=x.Branch,
                              ProductID=br.Product,
                              Notes = x.Notes,
                             //All other fields needed
                           }
                          ).ToList();


text:
Q: Add a field to a wave dataset I have a defined wave dataset. The object has a new field I would like to use for lenses, dashboards, etc. How do I update the dataset to incorporate this new field?
thanks

A: You can download the .json file from the dataset and edit the file and you can add the field and upload the worlflow json back
You will find this in data monitor >data flow

A: I know this is a bit old but in case it could you or new users as I think there is an easier way now.
From wave you need to go to data manager, by clicking in the gear icon data manager

From there you go to dataflow & recipes tab and click in the dataflow

From there you need to click in the "arrow" > of where you want to add fields, and this will pop up a similar window as when you were importing the fields, if you click in fields you should be able to cherry pick the fields


text:
Q: Is there another method besides the minimum modulus theorem than can help me solve this problem? The question is, find the minimum of $|exp(z^2)|$ for those z with $|z|\leq 1$. Im aware the modulus theorem would solve this, but we haven't gotten there yet. The section of the book this question is on is differentiation of elementary complex functions. Don't solve for me, just hints please

A: I would do it like this:
Write $z = x+iy$ where $|z| = \sqrt{x^2 + y^2} \leq 1$.
1) How do we simplify $|e^{z^2}|$ in terms of $x$ and $y$?
2) How can we use the bounds on $x$ and $y$ implied by the inequality?

A: The function $g(z):=z^2$ assumes the same values in $\bar D$ as does $f(z)=z$. Now $\bigl|e^z\bigr|=e^x\geq{1\over e}$ in $\bar D$, and the minimal value is taken at $z=-1$. In the original problem we therefore should choose $z$ such that $z^2=-1$, which is $z=\pm i$.


text:
Q: Interrupts using member function
*

*I am trying to use a member function in an interrupt. The function uses member variables so I created a global instance of that class to use it in a static function.
The problem is that I created a child class that should have the same interrupt. The interrupt is enabled in the constructor of the parent class, so it will be also enabled in the child class but with the wrong instance.

*To use the interrupt functions in both classes, I put them in a separate header file "Utilities.h" so that I can included it in both source files. But doing void called_from_interrupt () { Instance_1.do_something(); } requires including the class header, which will create multiple definitions errors.
I'll put a short example of what I am trying to do, the original code is really long.
parent_class.h :
#ifndef PARENT_CLASS_H
#define PARENT_CLASS_H

class parent_class {

public :

    parent_class();
    ~parent_class();
    void do_something();
};

extern parent_class instance_1;

#endif

parent_class.cpp :
#ifndef PARENT_CLASS_CPP
#define PARENT_CLASS_CPP

#define LIBCALL_ENABLEINTERRUPT
#define EI_ARDUINO_INTERRUPTED_PIN
#include "EnableInterrupt.h"

#include utilities.h

parent_class instance_1;

parent_class::parent_class() {

    enableInterrupt(PIN_1, called_from_interrupt, FALLING);
}

parent_class::~parent_class() {}

parent_class::do_something() {

    //manipulate some member variables
}

#endif

child_class.h :
#ifndef CHILD_CLASS_H
#define CHILD_CLASS_H

class child_class {

public :

    child_class();
    ~child_class();
};

extern child_class instance_2;

#endif

child_class.cpp :
#ifndef CHILD_CLASS_CPP
#define CHILD_CLASS_CPP

#include utilities.h

child_class instance_2;

child_class::child_class() {}

child_class::~child_class() {}

#endif

utilities.h :
#ifndef UTILITIES_H
#define UTILITIES_H

#include "parent_class.h"

#define PIN_1  10

static void called_from_interrupt() {
    instance_1.do_something();
}

#endif

Do you have please an elegant solution for that ?

A: Calling the static member of the base class should work.
You just have to make sure the Instance pointer is correct.
This can be done with the singleton pattern.
Be aware of potential reentrancy risk with this approach though.

Example (disclaimer: I have not dealt with this exact problem before):
https://godbolt.org/z/a6qj3c
class Base {
protected:
    static Base *instance;
    Base(){}
    virtual ~Base(){}
public:
    static Base* getInstance(){
        return instance;
    }
    static void setInstance(Base* p){
        instance = p;
    }
    virtual void run();
};

Base* Base::instance;

class Child : public Base {
public:
    Child(){
        Base::setInstance(this);
    }
    ~Child() override {
        Base::setInstance(nullptr);
    }
    void run() override;
};

void Base::run(){
    cout << "the base thing" << endl;
}

void Child::run() {
    cout << "the child thing" << endl;
}

extern "C" void isr(){
    if(Base::getInstance() != nullptr)
        Base::getInstance()->run();
}

int main()
{
    Child b;
    isr();
    return 0;
}

Returns:
the child thing

Now, big red flag, you can call Child::run() from two contexts. Your main thread and your interrupt routine. This means that Child::run() can be called while executing Child::run(), this a reentrancy problem.

A: If you are hell-bent on using C++ for some reason, then the correct solution is not to create one big "goo" class but to use OO design. Place the ISR as a static function - optionally it can be static member - inside a dedicated singleton "interrupt class", which does nothing but handling the interrupt for that specific hardware peripheral. Re-entrancy protection and interrupt enable/disabled is also handled by that class.
Then include the interrupt class as a private one inside the general hardware peripheral driver code.
This way you can also potentially expose the "interrupt class" to the vector table, so that the ISR name is known to it - without exposing any other internals of the hardware peripheral class. You will find out that the ISR needs to be exposed to the vector table regardless - after which you realize it would have been easier just to make the ISR a plain file scope function like you would have done in C.


text:
Q: Type of a double Learning Haskell, in ghci:
Prelude Data.Ratio> :type 0.15
0.15 :: Fractional a => a

Prelude Data.Ratio> 0.15
0.15
it :: Double

Why are types different? Are those two instances of 0.15 actually different types?

A: This due to the dreaded monomorphism restriction.  Basically, GHCi likes to choose default types when executed (the default Fractional type is Double), but when you ask the type using :type it chooses the most general version.  You can disable this behavior with the NoMonomorphismRestriction extension:
> :set -XNoMonomorphismRestriction
> :set +t
> 0.15
0.15
it :: Fractional a => a
> :t 0.15
0.15 :: Fractional a => a

While this this extension has one of the scarier names, it's rather simple when you break it down:
Mono  -> One
Morph -> shape (type)
ism   -> thingy
Monomorphism -> one shape thingy -> one type thingy -> thing with a single type

So basically it's a really long word that means "single type".  Then with "restriction", you get that the monomorphism restriction is restricting things to a single type.  In this case, it's restricting numbers (the things) to the type Double.  Without this restriction, the type of the numbers is only constrained by a type class, which can in theory be an infinite number of types.


text:
Q: How can I get zsh completion to expand environment variables like bash does? When using bash, if I have an environment variable called SOMEPATH which contains a path (e.g. SOMEPATH=/usr/local/lib), then if I type
ls $SOMEPATH/
and hit tab then bash expands the environment variable so my command line now says
ls /usr/local/lib/
If I do the same thing in zsh it instead escapes the $ sign so after tab completion the command line looks like
ls \$SOMEPATH
How can I get zsh to behave like bash does in this regard?
I've done a lot of googling but I haven't managed to find anything that exactly addresses this issue. I've also tried reading the zsh documentation but again I couldn't find anything that obviously relates to this.
Thanks for any pointers.


text:
Q: Predict one random variable from another with same seed Given the same seed, is it possible to predict one output from the other, with different type and range?
e.g.
np.random.seed(100)

x = np.random.randint(0, 16, 2)

np.random.seed(100)

y = np.random.randint(0, 256)

In this example I have x as a 2-element integer array with range 0-15 and y as a integer scalar with range 0-255.
My question is in general, not limited to the example above, under which condition it is possible to predict y given x? Assume the observer knows x, type and range of x and y, but not the seed itself.
Any discussion of sufficient or necessary conditions for predictability will be useful.

A: If you know the seed, you can predict any value at any position, because the seed is used to build reproducible pseudo random sequences. If you do not know the seed, you cannot predict a value from the previous values.
If you have 2 sequences from the same seed and they are trivially bound, you can predict one sequence from the other one or at least know that the values will be from a smaller set.
Your example contain trivially bound sequences. Both are int sequences, one (x) uses 4 bits, one (y) uses 8 bits. At same rank, x = y % 16. That means that x is fully known if you know y, but if you know x, each y value has 16 possibilities (instead of 256).
Demo:
np.seed(100)
np.random.randint(0, 256, 3)
-> np.array([8, 24, 67])
np.seed(100)
np.random.randint(0, 16, 3)      # we have y % 16
-> np.array([8, 8, 3])

Another example or trivially bound sequences is when one is just shifted by a constant value
np.seed(100)
np.random.randint(2, 258, 3)    # we will have y + 2 here...
-> np.array([10, 26, 69])

Any two sequences from the same seed will have some kind of dependency, but if their relation is not trivial, you will only be able to know that dependency through a detailed knowledge of the pseudo-random implementation... And as far as I am concerned I have not that knowledge ;-), so I can only speak for trivial cases.


text:
Q: Get question mark in beginning of request with mod_rewrite in .htaccess Scenario:
When the user enters myhomepage.com/username he/she should be redirected to myhomepage.com/?username.
Respectively: myhomepage.com/index.html?username
if the user enters the url with the question mark : myhomepage.com/?username, mod_rewrite should be ignored.
EDIT:
This is what i tried:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.html?$1

A: Search for an empty querystring in a RewriteCond
RewriteEngine On
# Rule only applies when we have an empty querystring
RewriteCond %{REQUEST_QUERYSTRING} ^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.html?$1


text:
Q: Java 8 doesn't allow generic type using operator? I'm using Java 8 and try to write a generic class utility which enables +-/* operators for all supported classes, like this:
class MyMath<T> {
    public static <T> T add(T x, T y) { return x + y; }
    public static <T> T sub(T x, T y) { return x - y; }
    public static <T> T mul(T x, T y) { return x * y; }
    public static <T> T div(T x, T y) { return x / y; }
}

It doesn't compile, saying that
The operator / is undefined for the argument type(s) T, TJava(536871072)

How to fix my code to get it compiled?


text:
Q: How to download result directly from Design Automation? I am running a Design Automation job that generates an output.json file. Upon successful completion of the job, I would like to download directly that file without DA to store it on OSS or other cloud storage. All tutorials I can find seem to place the file on OSS. Direct download was doable with DA v1, do you happen to have an example for me?

A: Direct download was doable with DA V2, no more with DA V3, you need to provide an upload storage URL, no other option for you.

A: Yep, this feature was discontinued because it muddied the data retention picture. DA V3 never retains your data beyond the conclusion of your workitem. DA V2 had a temporary storage for outputs.


text:
Q: The program is not able to show the output from second iteration onwards for(int i=0;i<T;i++)   // t test cases
{
    int flag=0;        //flag variable to check the output
    char A[3][3];

    for(int j=0;j<3;j++)        //Taking
        for(int k=0;k<3;k++)     //Input
           cin>>A[j][k];          //in a character Array

    //checking for letter 'l' in the character array and if other l's  also exist or not

    for(int j=0;j<2;j++)
      for(int k=0;k<2;k++)
    {
        if(A[j][k]=='l')
        {
            if(A[j+1][k]=='l' && A[j+1][k+1]=='l')
                flag++;
        }
    }

     if(flag>0)
            cout<<"yes"<<endl;
}

return 0;

}

This is my code, the problem was to check if in a 3*3 character array, if there is a pattern like
l
ll
It works for the 1st iteration correctly or for the 1st test case but it's showing no result from 2nd onwards.

A: It works properly, as you can see here: onlinegdb.com/r1VCS-FxN.
You are not seeing the result when it fails because you don't have a "no" cout.
The code in the link, just in case it stops working:
#include <iostream>
using namespace std;

int main() {
    const int T = 3;
    cout << "T: " << T << endl;

    for(int i=0;i<T;i++)   // t test cases
    {
        int flag=0;        //flag variable to check the output
        char A[3][3];

        for(int j=0;j<3;j++)        //Taking
            for(int k=0;k<3;k++)     //Input
                cin>>A[j][k];          //in a character Array

        //checking for letter 'l' in the character array and if other l's  also exist or not

        for(int j=0;j<2;j++)
            for(int k=0;k<2;k++) {
                if(A[j][k]=='l') {
                    if(A[j+1][k]=='l' && A[j+1][k+1]=='l')
                        flag++;
                }
            }
        cout << "Flags: " << flag << endl;

        if(flag>0)
            cout<<"yes"<<endl;
        else
            cout << "nope" << endl;
    }
    return 0;
}


text:
Q: Recursive association with inheritance If my inherited table has recursive association does the foreign key point to the primary key of this table or the parent table?
In my scenario:

*

*Person inherits Employee.

*Employee can manage 0:many Employees and an Employee can have 1 manager. (recursive association).

Is this table correct or should the second constraint reference Person(person_id) instead?
create table Employee(
  person_id int not null,
  salary float not null,
  etype varChar(25) not null,
  manager_id int not null,
  dept_id int not null,

  primary key(person_id),
  constraint fkemp foreign key(person_id) references Person(person_id),
  constraint fkmanager foreign key(manager_id) references Employee(person_id),
  constraint fkdept foreign key(dept_id) references Department(dept_id),
);

Also the CEO has nobody managing him does that mean I need to compromise with my data integrity and allow a null value?

A: I think the table is correct.  For the purposes of the hierarchy, managers are Employees (their People properties aren't really relevant here).
Secondly, you can make manager_id nullable and not compromise your data integrity.  Clearly, there are situations where an employee does not have a manager (i.e. the CEO), so it isn't really any sort of logical violation to allow manager_id to be null.
If it makes you feel safer, you could add a is_manager bit not null column to the Employee table, and then have a constraint that only allows a null manager_id if is_manager is true.


text:
Q: ES6 class method not present in instance I am updating my old node.js project to include ES6 features in order to eventually migrate to typescript, but I can't get this class to work. I have defined a class in a separate file:
class Database {

constructor(connectionPool) {
    this._connectionPool = connectionPool;
}

_getConnection () {
    console.log("getting connection");
    return new Promise((resolve, reject) => {
        this._connectionPool.getConnection((err, connection) => {
            if (err) {
                reject(err);
                console.log("connection rejected");
            } else {
                console.log("connection resolved");
                resolve(connection);
            }
        });
    });
}
}
module.exports = Database;

I am then importing this class into another file and trying to create a Database instance:
const mysql = require('mysql');
const Database = require('./database');

module.exports = databaseInitializer;

function databaseInitializer(config) {

    const pool = mysql.createPool(config);
    const db = new Database(pool);
    console.log(Database.toString());
    console.log(db.__proto__);
    return db;
}

Finally, i am using above function to get the database instance:
const database = require('./models/databaseInitializer')(mysqlConfig);
console.log(database);

Now, my database instance has a _connectionPool property, but no prototype and more importantly, no _getConnection property.
What am I missing?
Thanks and best regards

A: _getConnection property belongs to the prototype of database and hence this property is the non-enumerable property of database.
You can access this property by doing
console.log(database._getConnection) //should show the function


text:
Q: Using switch() with variables as cases I'm trying to use switch() where the 'cases' are parameters.
Something like:
const1 <- 'c1'
const2 <- 'c2'

action <- 'c1'

switch(action,
       const1 = 1,
       const2 = 2)

This can be useful when there's a need to change the value of const1, it will require a change only in one place in the code.
I know I can use if-else instead, but I'm wondering is there's a workaround?

A: I don't think this is a particular clear way of coding, but you could use:
do.call(switch, c(action, setNames(list(1, 2), c(const1, const2))))


text:
Q: Computation hangs: rstan, plyr, and doMC I am trying to run a simple rstan example using plyr and doMC for parallel computation. The following code completes normally if I comment out registerDoMC(cores = 2) near the bottom, but as is, my R session hangs indefinitely on the call to adply. I am using R version 3.3.0 with the R GUI on Mac OS 10.11.5.
EDIT: Oddly enough, this works on a Linux server and my Mac via R CMD BATCH on the command line. Still no R GUI, though.
library(rstan)
library(doMC)
library(plyr)

model = stan_model(model_code = "
data {
  int k; // number of observations per subject
  real theta; // hierarchical mean of the mu's, estimated beforehand (empirical Bayes)
  vector[k] subject; // subject-specific data
}
parameters {
  real mu; // subject-specific mean
}
model {
  mu ~ normal(theta, 1) ;
  for(i in 1:k)
    subject[i] ~ normal(mu, 1);
}")

single_subject = function(model, subject, theta){
  diverge = TRUE
  attempt = 1

  while (diverge) {
    print(paste("Attempt", attempt))
    .mcmc = sampling(model, pars = "mu", iter = 2000*attempt, thin = attempt, verbose = F,
                     data = list(k = length(subject), theta = theta, subject = subject))
    .summary = summary(.mcmc)$summary
    diverge = any(.summary[,"n_eff"] < 1000)
    attempt = attempt + 1
  }

  .summary["mu",]
}

n = 100 # number of subjects
k = 32 # number of observations per subject
dataset = matrix(rnorm(n*k), ncol = k)
theta = 0 # could be estimated from the data beforehand

start = proc.time()
out = adply(dataset, 1, function(subject) single_subject(model, subject, theta))
serial_time = proc.time() - start

start = proc.time()
registerDoMC(cores = 2)
out = adply(dataset, 1,
  function(subject) single_subject(model, subject, theta),
  .parallel = T,
  .paropts = list(.export=c("single_subject", "model", "subject", "theta"),
                  .packages="rstan"))
registerDoSEQ()
parallel_time = proc.time() - start

cat("Serial time:\n")
print(serial_time)

cat("Parallel time:\n")
print(parallel_time)

write.csv(out, "mu.csv")