Q:

How can I find the Maclaurin series of $\frac{1}{1+x+x^2}$?

How can I find the Maclaurin series of $\frac{1}{1+x+x^2}$? At first, I found the Maclaurin series of $\frac{1}{1+x}$, which is $\sum_{n=0}^{\infty}(-1)^{n}x^{n}$ and simply replaced $x$ with $x^2 + x $, but the answer sheet says something different. It says that the answer is $\sum_{n=0}^{\infty}x^{3n}$. Which answer is right? The answer sheet? or me?

A:

Hint: When $x\ne 1$, our function is $\frac{1-x}{1-x^3}$. Expand  $\frac{1}{1-x^3}$ by using the series for $\frac{1}{1-t}$, and multiply by $1-x$.
Remark: The answer sheet, if quoted correctly, is not right. Your method works for getting the first few terms of the Taylor series, but becomes awkward for the general term. However, combined with the method of the hint, it can be used to prove a nice identity.


Q:

How to change a vertical string to a horizontal string in python?

I have tried using those script but they don't work. (x is a vertical variable)
print "".join(x.split())

and
x.replace("\n", "")

(try to explain your answer if you can)
SAMPLE INPUT-OUTPUT:
Input:

H
E
L
L
O

Output:
HELLO ABC

A:

input=(a\nb\nc\nd\nA\nB\nC\n) #<---Vertical text

result=input.replace("\n", "") #Convert the vertical text to horizontal text

print(result) #Print the horizontal text

Output:
abcABC
100% working for my program


Q:

vb.net referring to a program-created form via New

I have the following code in vb.net written in a button.
dim x as new frm_raw_infosheet

whenever I click on the button, the program does create a new instance of the form which is what I want.
My question is, how will I be able to refer to each one of those newly created forms?
for example, I clicked the button 3 times, how will I programmatically hide the 2nd form I created with the button?
I tried
x.name = "Form" & incrementingvariable

however, I'm not entirely sure how I'm going to refer to it.
To make my question more clear, let's say incrementingvariable contains the number 2
incrementingvariable = 2

x now contains the name "Form2"
however, this returns an error
Form2.enabled = false

I can't refer to Form2, Because .Net Says that "Form2" doesn't exist!
EDIT
I understand it's been a while since I asked this, but here is an update
On the listboxes are the literal names of each form which I stored using Listbox1.items.add(x.Name).
How do I call an instance in the collection then? Say I want to make a form in the list visible?

A:

It depends on how you want your program to work.
If you're only going to have one instance of the form open at any time you can save the reference returned by new in a persistent variable, e.g. an instance variable. You could then refer to the old form and close it at any later time.
If you need to keep track of more than one form then you could save the reference returned by new in a collection, which could also be an instance variable.

A:

I refer to the edited question: Instead of adding the names of the forms to the ListBox, you can add the Form objects themselves:
Listbox1.Items.Add(x)

If you set the DisplayMember property of the ListBox to Name, the name of the form is displayed in the listbox (as it was before).
Now you are able to access the form object directly through the ListBox' Items collection and call methods on them:
DirectCast(ListBox1.Items(2), Form).Enabled = False

This example accesses the third form in the ListBox (of course you will want to make sure you do not access an index that is not present; the Count property is helpful in this respect).
As the items are stored as objects, you have to cast them to a Form object before you can access members that are defined in the Form class.


Q:

regex How to remove space bewteen maj character and word

I am working on raw text from OCR processing
Antonio G uomez çapateyro

I want to remove space between a maj character and an word:
Antonio Guomez çapateyro

What I tried
(?:[A-Z])[\s]

text <- readLines("clipboard" , encoding = "latin1")
text2 <- gsub("(?:[A-Z])[\s]", "", text2)

My problem: I can match G with space but I don't know how to remove space

A:

We can use a positive lookbehind to match one or more spaces (\\s+) preceded by a capital letter ((?<=[A-Z])) and replace it with ''.
gsub("(?<=[A-Z])\\s+", "", str1, perl=TRUE)
#[1] "Antonio Guomez çapateyro"

Or without any lookaround, we can capture the capital letter as a group followed by one or more spaces and replace it with the backreference (\\1).
sub("([A-Z])\\s+", "\\1", str1)
#[1] "Antonio Guomez çapateyro"

data
str1 <- "Antonio G uomez çapateyro"


Q:

How could Jor El become heretic if he didn't have free will?

In Man of Steel Kal-El asked Jor-El:

Why didn't you come with me?

His answer was:

...Your mother, Lara, and I were a product of the failures of our world as much as Zod was tied to its fate.

If they were genetically programmed, how could Jor El have a naturally born son? If he had no free will then how could he become heretic?

A:

Assuming we stick exclusively to the 2013 "Man of Steel" film and its novelisation, then the answer to your question is that the genetic code of each newborn shapes their skills and abilities (teacher/scientist/leader/worker/etc) as well as determining their general outlook on society and their place in it.

Krypton had long ago abandoned the unpredictability of sexual reproduction—with its reckless pairings and random mixing of chromosomes—in favor of a more orderly and scientific system that allowed for complete control over each child’s genetic makeup and destiny. Nothing was left to chance. Each developing embryo was expressly designed to fulfill his or her preordained role in society—as a worker, warrior, thinker, administrator, or whatever best served the greater good.
The Genesis Chambers were the ultimate expression of Krypton’s rigid caste system, applying advanced genetic engineering to an inviolate tradition that stretched back to antiquity. Jor-El had sprouted from one such stem, many cycles ago, as had Lara, and Zod, and every Kryptonian who currently breathed upon the
  planet.
Save for one.
Man of Steel: The Official Movie Novelization

This doesn't mean that their actions are pre-determined though. It's a fundamental irony of the film that whilst Jor-El has gone from being a staunch supporter of the council to a "heretic" and Zod has gone from being a loyal General of Krypton to being shunned as a "terrorist", neither of them have actually changed their philosophical positions over the last few hundred years, just their methods.

Oh, and as to how Lara-El and Jor-El were able to conceive a child, I shall leave that to your imagination.


Q:

Should you worry about fake accounts/logins on a website?

I'm specifically thinking about the BugMeNot service, which provides user name and password combos to a good number of sites. Now, I realize that pay-for-content sites might be worried about this (and I would suspect that most watch for shared accounts), but how about other sites? Should administrators be on the lookout for these accounts? Should web developers do anything differently to take them into account (and perhaps prevent their use)?

A:

I think it depends on the aim of your site. If usage analytics are all-important, then this is something you'd have to watch out for. If advertising is your only revenue stream, then does it really matter which username someone uses?
Probably the best way to discourage use of bugmenot accounts is to make it worthwhile to have an actual account. E.g.: No one would use that here, since we all want rep and a profile, or if you're sending out useful emails, people want to receive them.

A:

Ask yourself the question "Why do we require users to register to access my site?"  Once you have business reason for this requirement, then you can try to work out what the effect of having some part of that bypassed by suspect account information.
Work on the basis that at least 10 to 15 percent of account information will be rubbish - and if people using the site can't see any benefit to them personally for registering, and if the registration process is even remotely tedious or an imposition, then accept that you will be either driving more potential visitors away, or increasing your "crap to useful information" ratio.

A:

Not make registration mandatory to read something? i.e. Ask people to register when you are providing some functionality for them that 'saves' some settings, data, etc. I would imagine site like stackoverflow gets less fake registrations (reading questions doesn't require an account) than say New York Times, where you need to have an account to read articles.
If that is not upto your control, you may consider removing dormant accounts. i.e. Removing accounts after a certain amount of inactivity.


Q:

Loading Dojo Library from AOL and Widget Codes from Local?

I just started to learn Dojo. I followed one site Widget example with some different ways to load Dojo libraries. I like to use AOL reference to load dojo.js like this:
<script type="text/javascript"
  src="http://o.aolcdn.com/dojo/1.2.0/dojo/dojo.xd.js">
</script>

and saved my widget codes in local web server like this:
scripts/
   myWidget/
     widgetExample.js
   ...
test.html

where widgetExample.js contains my widget class codes, and test.html is my testing page. The error message I got is: "uncaught exception: Could not load cross-domain resources: myWidget.widgetExample ...". I am not sure if I have to load dojo package locally? I really like to separate dojo library package as they are or loaded from AOL and only put my own codes in a local path. I tried to google about different domain loading, baseScriptUrl, and moduleMapping? Still not be able to figure out. Thanks for any detail instructions if any.

A:

This may help: http://dojotoolkit.org/forum/dojo-core-dojo-0-9/dojo-core-support/xdomain-usage-dojo-loading-not-detecting-local-modules
The summary is: you need a djConfig item registering the modulePaths you want to be local, and specify a baseUrl to "trick" Dojo into thinking it knows where those paths are relative, across hosts.
djConfig = { modulePaths: { "mine":"/js/mine" };
then you can dojo.require("mine.Thing") from /js/mine/Thing.js
Regards,
Peter Higgins


Q:

GCC x64 on Windows

I tried installing CygWin64, but I cannot find any executables to build my code with in the C:\cygwin64 directory created.
I tried Win-Builds but the setup doesn't load with any mirror I give it. It tries to connect 3 times then aborts.
I tried MinGW-W64-Builds, but I cannot figure out how to install it. I can see a .sh file there, but I believe that is for Linux, so I do not know why because it says it is for Windows
Is there even a way to use 64-bit GCC on Windows? I am trying to tie it to a Code::Blocks IDE as that one only comes with the 32-bit version of MinGW.

A:

Check out out the MinGW-w64 + GCC personal build at http://winlibs.com/.
No installation required, just unzip.
Examples on how to use are on the site, including on how to integrate with Code::Blocks IDE.


Q:

Find $f$ such that $\int_{x}^{f^{-1}(x)}f(t)dt=x^2.$

Find $f$ such that $\int_{x}^{f^{-1}(x)}f(t)dt=x^2$ for all $x\in \mathbb{R}.$ Here $f$ is a bijection of $\mathbb{R}$ in $\mathbb{R}$ and is differentiable with derivative not equal to $0.$
I tried to apply the fundamental theorem of calculus but I get $$x(f^{-1}(x))'-f(x)=2x.$$ But I am not being able to get rid of $f^{-1}(x)$ in order to get a differential equation in terms of $f(x).$ I know that $(f^{-1}(x))'=\frac{1}{f'(f^{-1}(x))}$ But this does not help either.

A:

Try this function: $f(x)=(-1+\sqrt{2})x$. I was looking for a solution in the form of $f(x)=cx$, then $f^{-1}(x)=\frac{x}{c}$ and  $\int_{x}^{f^{-1}(x)}f(t)dt=\int_{x}^{x/c}ct \:dt= \frac{c}{2}(\frac{x^2}{c^2}-x^2)=\frac{cx^2}{2}(\frac{1}{c^2}-1)=x^2$. Thus, we have an equation for $c$: $\frac{c(1-c^2)}{c^2}=2$, $1-c^2=2c$.


Q:

Stack trace skipps a method?

I have a class Foo with a method SomeMethod(). In SomeMethod(), I run: Bar bar = new Bar(); bar.BBQ();. Within BBQ(), I call the private method Name(n) which throws an exception with the message new StackTrace().GetFrame(n).GetMethod().Name.
My intention is to pass 1 to Name(n), so that it will return the value "BBQ". However, Name(0) returns "Name" and Name(1) returns "SomeMethod". In the stack trace resulting from the exception being thrown, it also reads as though Name were directly called by SomeMethod (with no mention of BBQ).
Is there a way around this? Does anyone have any idea what could be causing this error? Is there maybe a better way to accomplish getting the value "BBQ" from Name?
[TestClass]
public class Foo
{
    public Foo()
    {
    }
    [TestMethod]
    public void SomeMethod()
    {
        Bar bar = new Bar();
        bar.BBQ();
    }
}

public class Bar
{
    public Bar()
    {
    }
    public void BBQ()
    {
        Name( 1 );
    }
    private void Name( int n )
    {
        throw new Exception( new StackTrace().GetFrame(n).GetMethod().Name );
    }
}

A:

I strongly suspect the problem is that the method is being inlined by the JIT compiler. You could probably verify this by running a debug build within the debugger, and seeing if that solves the problem.
You can get the immediate calling method relatively easily, but getting a completely accurate stack trace isn't feasible in a non-debugger environment, I believe. You wouldn't want to disable inlining, after all.


Q:

NullPointerException using Array of Custom Views

I decided to optimize my code using a simple loop instead of hardcode, because previously I implemented each PickView separately and it worked fine.
Here is a problematic place:
pick = new PickView[9];
int id;
for(int i = 0; i < pick.length; i++) {
    id = getResources().getIdentifier("pick_" + i, "id", getPackageName());
    pick[i] = (PickView)findViewById(id);
    pick[i].setOnTouchListener(this); //this is MainActivity, line:54
}

...in which unexpectedly I recieved a NullPointerException:
ERROR/AndroidRuntime(8450): FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.***}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
    at android.app.ActivityThread.access$2300(ActivityThread.java:125)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:123)
    at android.app.ActivityThread.main(ActivityThread.java:4627)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:521)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NullPointerException
    at com.***.onCreate(MainActivity.java:54)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
    ... 11 more

I enclose a PickView class:
public class PickView extends RelativeLayout {

    private TextView textView;
    private ImageView imageView;
    private String text;

    public PickView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PickView);
        text = a.getString(R.styleable.PickView_text);

        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.pick_view, this);
        textView = (TextView)findViewById(R.id.pick_text);
        imageView = (ImageView)findViewById(R.id.pick_bg);
    }

    public void setText(String text) {
        textView.setText(text);
    }

    public void activate(boolean isActive) {
        if (isActive)
            imageView.setImageResource(R.drawable.pick_active);
        else
            imageView.setImageResource(R.drawable.pick);
    }
}

I will be grateful for any help!

A:

Just a small question do you have a pick_0 resource?
And anyway you should check that you are actually getting an id and that the PickView returned isn't null?


Q:

How to download file using node.js and http?

I have a file in D: Drive of my local system. I need to download the file into the E: Drive. How to do this using node.js and http request? I am a beginner in node.js. Please give me valuable suggestions.
Note: The file may be in any type.

A:

Here is an example:
// upload.js
var fs = require('fs')

var newPath = "E:\\newPath";
var oldPath = "D:\\oldPath";

exports.uploadFile = function (req, res) {
    fs.readFile(oldPath, function(err, data) {
        fs.writeFile(newPath, data, function(err) {
            fs.unlink(oldPath, function(){
                if(err) throw err;
                res.send("File uploaded to: " + newPath);
            });
        });
    });
};

// app.js
var express = require('express'), // fetch express js library
upload = require('./upload'); // fetch upload.js you have just written

var app = express();
app.get('/upload', upload.uploadFile);

app.listen(3000);

Basically there are two parts, one doing the copying from one drive to another, and the other one is for triggering. Once you run you app.js and make a GET request to localhost:3000/upload it will copy the file from newPath to the oldPath. For further information have a look to expressjs and fs.


Q:

Do work without blocking the gui thread

I have a c# windows forms application and use a library which does not provide async-await functionality.
When I press on a button I want to do some work (webrequesting).
While doing this work I dont want to freeze my gui.
I tried several approaches, for example:
public static Task<bool> LoginUser(string username, string password)
{
    return Task.Factory.StartNew(() =>
    {
        try
        {
            session = new AuthenticatedSession<User>(new User(username), Cryptography.GetMd5(password));

            return true;
        }
        catch (InvalidAuthenticationException)
        {
            return false;
        }
    });
}

When I call LoginUser("foo", "bar").Result the gui freezes until the work is done (I understand that this is not async because I can't await new AuthenticatedSession<...
So I look for something like:

Create a thread with a action as parameter
Return the value from the thread
End the thread

A:

Try forcing a new thread (or WorkerThread) instead of using the TaskFactory.
Thread t = new Thread (delegate()
{
    try
    {
        session = new AuthenticatedSession<User>(new User(username), Cryptography.GetMd5(password));
        Success();  //coded below
    }
    catch (InvalidAuthenticationException)
    {
        Fail();
    }
});
t.Start();

Your list requires that we return a value, all we really can do is call a method or set state indicating the return value or even signal (ManualResetEventSlim) if you want some blocking, but your requirements state you want non-blocking.
To resume execution or signal the GUI that your process is done you would invoke some method on the UI thread, like this:
void Success() {
  Invoke((MethodInvoker) delegate {
    SomeMethodOnTheUI();
  });
}

This is basically an async/callback strategy.


Q:

Capturing and handling HTML5 video events

I'm trying to develop custom HTML5 video player. Struggling a little bit with getting my head round as to how should I handle events that I'm capturing. For example:
//this will work
video.oncanplay = alert("can play");

//this won't work
video.oncanplay = function(){
    alert("can play");
}

//but this will work
video.oncanplay = (function(){
    alert("can play");
})();

Is a self invoking function a right approach? Or should I try something else? Tried to read w3c documentation but failed to grasp it.

A:

I add event listeners - as in this example https://gist.github.com/Offbeatmammal/3718414 - for what I want to track. You can either point all the events to a single function (which I did for that example) of attach specific ones depending on your logic


Q:

R Bar Graph Changes

I am trying to make the following changes to the graph:
(1) I would like a title for the graph that is centered. When I try adding a title, it is on the left side.
(2) I would like the y-axis label to have more than one word. Namely "Average (Per Game)". Every time I have more than one word, the graph completely changes. I would also like "Average" and "(Per Game)" to be on different lines, if that is possible.
(3) I would like the background of the graph to be gray, but with white grid lines.
Any help would be much appreciated!
df <- read.table(textConnection(
  'Statistic  Warm Avg Cold
  HR(Away) 1.151 1.028 .841
  HR(Home) 1.202 1.058 .949
  BB(Away) 3.205 3.269 3.481
  BB(Home) 3.286 3.367 3.669
  Runs(Away) 4.909 4.591 4.353
  Runs(Home) 5.173 4.739 4.608'), header = TRUE)

library(dplyr)
library(tidyr)
library(ggplot2)

df %>%
  gather(Temperature, Average, -Statistic) %>%
  mutate(Temperature = factor(Temperature, c("Cold", "Avg", "Warm"))) %>%
  ggplot(aes(x=Statistic, y=Average)) +
  geom_col(aes(fill = Temperature), position = "dodge") +
  scale_fill_manual(values = c("blue", "yellow", "red"))+
  theme_bw() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5))

A:

(1) To center the title add plot.title = element_text(hjust = 0.5) to the theme
(2) Add labs(y = "Average\n(Per game)") to add a label for the y axis. The "\n" breaks the line.
(3) Easiest solution is to remove theme_bw. Alternatively, check out http://docs.ggplot2.org/dev/vignettes/themes.html
df <- read.table(textConnection(
  'Statistic  Warm Avg Cold
  HR(Away) 1.151 1.028 .841
  HR(Home) 1.202 1.058 .949
  BB(Away) 3.205 3.269 3.481
  BB(Home) 3.286 3.367 3.669
  Runs(Away) 4.909 4.591 4.353
  Runs(Home) 5.173 4.739 4.608'), header = TRUE)

library(dplyr)
library(tidyr)
library(ggplot2)

df %>%
  gather(Temperature, Average, -Statistic) %>%
  mutate(Temperature = factor(Temperature, c("Cold", "Avg", "Warm"))) %>%
  ggplot(aes(x=Statistic, y=Average)) +
  geom_bar(aes(fill = Temperature), stat='identity', position = "dodge") +
  scale_fill_manual(values = c("blue", "yellow", "red"))+
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5),
        plot.title = element_text(hjust = 0.5)) +
  labs(title = "Title", y = "Average\n(Per game)")


Q:

Javascript: Sorting an array of objects based on a timestamp property doesn't sort one element correctly

I am trying to sort an array which contains arrays of
two elements of the form [[string, object], [string, object], ...]. Each object has a property named: currentStatusTimestamp. I am trying to sort the internal arrays based on this property. It seems that all the elements are sorted correctly except one element which stays always at the first position of the array.
You can view an example describing the problem below.
Unsorted:
Unsorted array
Sorted:
Sorted array
The first element at each line of the images corresponds to arr[0] (string) and the second to the arr[1].currentStatusTimestamp.
I have tried to sort the arrays with two different functions, but neither seem to work.
You may find the two functions below:
const sortByCurrentStatusTimestamp2 = (array) => {
array.sort((a,b) => {
    return (Number(a[1].currentStatusTimestamp) < Number(b[1].currentStatusTimestamp)) ? 1 : ((Number(b[1].currentStatusTimestamp) > Number(a[1].currentStatusTimestamp)) ? -1 : 0);} );}

const sortByCurrentStatusTimestamp = (array) => {
array.sort((a, b) => {
    return Number(a[1].currentStatusTimestamp) < Number(b[1].currentStatusTimestamp);
});}

The code which calls the functions is displayed below:
sortByCurrentStatusTimestamp2(entriesArray);

or
sortByCurrentStatusTimestamp(entriesArray);

You may find the code used to display the output which is shown in the images, below:
for (let e of entriesArray) {
console.log(e[0],e[1].currentStatusTimestamp);}

sortByCurrentStatusTimestamp2(entriesArray);

for (let e of entriesArray) {
console.log(e[0],e[1].currentStatusTimestamp);}

A:

The JS .sort function requires a comparator that returns a negative number, zero, or a positive number.   Your second returns a boolean.
Your first function fails because you do (a < b) ? 1 : (b > a) ? -1 : 0, but the two comparisons are equivalent, i.e. you got the second comparison the wrong way around.
It normally suffices to just return the difference between the two numeric values:
.sort((a, b) => +a[1].currentStatusTimestamp - +b[1].currentStatusTimestamp);

This will give the results in ascending order.   Swap a and b to reverse that.


Q:

Create lines parallel to my `geom_smooth(method = lm)` line

library(tidyverse)
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  geom_smooth(method = lm)

I would like two purple lines to run parallel to my geom_smooth(method = lm) line. Each line should be 10 units away from the geom_smooth(method = lm) line. One line would be above, and the other line below the geom_smooth(method = lm) line.
How do I accomplish this?

A:

As this answer suggests, there doesn't seem to be a natural way to shift a line. What we may do then is to use multiple geom_smooth with different offsets:
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  lapply(c(-10, 0, 10), function(o)
    geom_smooth(method = lm, formula = y + o ~ x))


Q:

CQ5, dynamically set 'defaultValue' in component's dialog using extjs?

I have a selection box in my component's dialog, with four options:

off
default
addon
overwrite

In the dialog, I want dynamically set the defaultValue property to 'off' or 'default' based on whether the URL path contains a certain characters or not.  Is this possible?
Here is the dialog.xml snippet with my attempted listener to do this:
<extra_meta_description_tag_mode
    jcr:primaryType="cq:Widget"
    defaultValue=""
    fieldLabel="SEO Description Usage"
    name="./extraMetaDescriptionTagMode"
    type="select"
    xtype="selection">
        <listeners
            jcr:primaryType="nt:unstructured"
            defaultValue="function(url) {
                url.contain("en_gb/news") ? return "default" : return "off";
            }"/>
        <options jcr:primaryType="cq:WidgetCollection">
            <off
                jcr:primaryType="nt:unstructured"
                text="Off"
                value="off"/>
            <default
                jcr:primaryType="nt:unstructured"
                text="Append pre-set text"
                value="default"/>
            <addon
                jcr:primaryType="nt:unstructured"
                text="Append input text"
                value="addon"/>
            <over_write
                jcr:primaryType="nt:unstructured"
                text="Overwrite"
                value="overwrite"/>
        </options>
</extra_meta_description_tag_mode>

A:

The listener can only have values of events, defaultValue is not one. You can use the loadContent event,which is fired when the dialog loads. CQ.WCM.getPagePath() will give the current page path:
<listeners
    jcr:primaryType="nt:unstructured"
    loadcontent="function(selection,record,path) {
        var currentPath = CQ.WCM.getPagePath();
        if(currentPath.indexOf('en_gb/news')!=-1)
        {
            selection.setValue('default');
        } else {
            selection.setValue('off');
        }"/>

This will reset the value every time the dialog loads, so you will have add conditions to prevent it if the users have overridden the default value.


Q:

Unable to add roles via PowerShell to Azure App Registration

I am using Powershell to add roles to an existing App Registration in Azure. I am using this command:
Set-AzureADApplication -ObjectId $myApp.ObjectId -AppRoles $newAppRoles

$newAppROles is an array of Microsoft.Open.AzureAD.Model.AppRole
When I execute the above command I get this error:

Set-AzureADApplication : Cannot convert 'System.Collections.Generic.List`1[Microsoft.Open.AzureAD.Model.AppRole]' to the type 'Microsoft.Open.AzureAD.Model.AppRole' required by parameter 'AppRoles'. Specified method is not supported.

The documentation for SetAzureADApplication says that it requires a list of the app roles; but I am getting this error. There seems to be no other documentation to help me out. Can someone tell me what I am doing wrong.
Below is the full code

Connect-AzureAD
$myApp = ""
$appName = "Narasimham POC Powershell - Multiple reply URLs"
if (!($myApp = Get-AzureADApplication -Filter "DisplayName eq '$($appName)'"  -ErrorAction SilentlyContinue)) {
    Write-Output "Application $appName not found"
}
else {
    Write-Output $myApp

    $currentAppRoles = $myApp.AppRoles

    $appRole = New-Object -TypeName Microsoft.Open.AzureAD.Model.AppRole
    $appRole.IsEnabled = $true
    $appRole.DisplayName = "Read Role"
    $appRole.Value = "Reader"
    $appRole.AllowedMemberTypes = "User"
    $appRole.Id = New-Guid
    $appRole.Description = "Reader Role for Narasimham POC Powershell"

    $newAppRoles = @($currentAppRoles, $appRole)
    Write-Output $newAppRoles
    Set-AzureADApplication -ObjectId $myApp.ObjectId -AppRoles $newAppRoles
}

A:

I think the issue is with the part of your script that adds a new role to current roles.
Try to replace this part of script from your question:
$newAppRoles = @($currentAppRoles, $appRole)
Write-Output $newAppRoles
Set-AzureADApplication -ObjectId $myApp.ObjectId -AppRoles $newAppRoles

with something like this instead:
$currentAppRoles.Add($appRole)
Write-Output $currentAppRoles
Set-AzureADApplication -ObjectId $myApp.ObjectId -AppRoles $currentAppRoles

Here is the full script I used to answer a very similar SO question earlier, in case this is more helpful for you. This adds a new app role to an existing registered application:
Connect-AzureAD -TenantId <Tenant GUID>

# Create an application role of given name and description
Function CreateAppRole([string] $Name, [string] $Description)
{
    $appRole = New-Object Microsoft.Open.AzureAD.Model.AppRole
    $appRole.AllowedMemberTypes = New-Object System.Collections.Generic.List[string]
    $appRole.AllowedMemberTypes.Add("User");
    $appRole.DisplayName = $Name
    $appRole.Id = New-Guid
    $appRole.IsEnabled = $true
    $appRole.Description = $Description
    $appRole.Value = $Name;
    return $appRole
}

# ObjectId for application from App Registrations in your AzureAD
$appObjectId = "<Your Application Object Id>"
$app = Get-AzureADApplication -ObjectId $appObjectId
$appRoles = $app.AppRoles
Write-Host "App Roles before addition of new role.."
Write-Host $appRoles

$newRole = CreateAppRole -Name "MyNewApplicationRole" -Description "This is my new Application Role"
$appRoles.Add($newRole)

Set-AzureADApplication -ObjectId $app.ObjectId -AppRoles $appRoles

Once you are done with above script to add AppRole, then assigning roles to a user is pretty simple and a direct command is available. Here's a sample script for that -
# Assign the values to the variables
$username = "<You user's UPN>"
$app_name = "<Your App's display name>"
$app_role_name = "<App role display name>"

# Get the user to assign, and the service principal for the app to assign to
$user = Get-AzureADUser -ObjectId "$username"
$sp = Get-AzureADServicePrincipal -Filter "displayName eq '$app_name'"
$appRole = $sp.AppRoles | Where-Object { $_.DisplayName -eq $app_role_name }

# Assign the user to the app role
New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $sp.ObjectId -Id $appRole.Id


Q:

FileSystemWatcher - will I get a buffer overflow or similar?

I need to watch a folder (on a network share) and be notified when a filename changes and the file is moved to a sub directory (all one event). This event occurs maybe twice a day. I will have multiple FileSystemWatchers to watch multiple folders for the same thing.
However, FileSystemWatcher is notoriously bad for missing events and I cannot have that happen. I've tried replicating the environment and it seems to work however I don't know whether that's because I am doing something in particular.
If I watch for only OnRenamed events, am I still likely to have issues or can I be sure that I won't miss events?

A:

In a correctly working network, you should not have any error related to missing events, but you should be aware that a simple hiccup on you network will render your FileSystemWatcher monitoring useless.
A momentary drop in the connection to the network share will trigger an Error in your FileSystemWatcher and even if the connection will be reestablished, the FileSystemWatcher will no longer receive any notification.
This is a sligtly adapted example found on MSDN
static void Main()
{
    // Create a new FileSystemWatcher and set its properties.
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = @"\\yourserver\yourshare";
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    // Only watch text files.
    watcher.Filter = "*.txt";

    // Add handler for errors.
    watcher.Error += new ErrorEventHandler(OnError);

    // Begin watching.
    watcher.EnableRaisingEvents = true;

    // Wait for the user to quit the program.
    Console.WriteLine("Press \'q\' to quit the sample.");
    while(Console.Read()!='q');
}
private static void OnError(object source, ErrorEventArgs e)
{
    //  Show that an error has been detected.
    Console.WriteLine("The FileSystemWatcher has detected an error");

    //  Give more information if the error is due to an internal buffer overflow.
    Type t = e.GetException().GetType();
    Console.WriteLine(("The file system watcher experienced an error of type: " +
                       t.ToString() + " with message=" + e.GetException().Message));
}

If you try to start this console application and then disable your network connection, you will see the Win32Exception, but if you do it again, no more error event will be seen by the running FileSystemWatcher


Q:

Authenticate by username or email fails with DBAL Exception: Undefined offset: 1

Beginning with successful authentication by email (in 4.2.4), an attempt to follow User Provider docs to add authentication by username fails with

DBAL Exception:... Undefined offset: 1

Curiously, if I run the SQL statement as shown in the debug profiler, View runnable query, the query runs properly and returns a non null result. So at least the repository can return a username.
I've tried rewriting the query builder statement using entityManager; providing a setParameters() statement with two parameters; all to no avail.
Edit #2:
Poking at the Doctrine code as identified in the trace (see below), the exception occurs at the line
[$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
The $query and $params (as shown with dd(...)) make sense to me. The $types variable, however, is opaque: it's an array [0 => 102, 1 => 102]. The exception occurs with the statement SQLParserUtils....
end Edit #2
Edit #3:
Here's what happens in Doctrine, but I have no idea of the intent of the code. In Doctrine\DBAL\SQLParserUtils, lines 129 - 133, are contained in a foreach () loop, run once for each element in the $paramsPos array [0 => 496, 1 => 513], where the values are the location of the replaceable parameters in a SQL statement. The $params array initially contains
array:2 [▼
  0 => array:1 [▼
    "username" => "gbrooks"
  ]
  1 => array:1 [▼
    "username" => "gbrooks"
  ]
]

After the code in 125 - 133 (as seen below) is executed
$needle    += $paramOffset;
$needlePos += $queryOffset;
$count      = count($params[$needle]);

$params = array_merge(
    array_slice($params, 0, $needle),
    $params[$needle],
    array_slice($params, $needle + 1)
);

the $params array contains
array:2 [▼
  "username" => "gbrooks"
  0 => array:1 [▼
    "username" => "gbrooks"
  ]
]

Note there no longer exists a key 1, so when the count($params[$needle]) statement at line 127 is encountered in the next pass through the loop (and $needle is now 1, the DBAL Exception Undefined offset: 1 is thrown.
end Edit #3
UserRepository:
namespace App\Repository;

use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository implements UserLoaderInterface
{
    public function loadUserByUsername($usernameOrEmail)
    {
        $user = $this->createQueryBuilder('u')
            ->where('u.username = :query OR u.email = :query')
            ->setParameter('query', $usernameOrEmail)
            ->getQuery()
            ->getOneOrNullResult();
    }
}

LoginFormAuthenticator contains:
public function getUser($credentials, UserProviderInterface $userProvider)
{
    $token = new CsrfToken('authenticate', $credentials['csrf_token']);
    if (!$this->csrfTokenManager->isTokenValid($token)) {
        throw new InvalidCsrfTokenException();
    }

    $user = $this->entityManager->getRepository(User::class)->loadUserByUsername(['username' => $credentials['username']]);

    if (!$user) {
        // fail authentication with a custom error
        throw new CustomUserMessageAuthenticationException('Email could not be found.');
    }

    return $user;
}

Trace:
G:\Documents\workspace\mana\vendor\doctrine\dbal\lib\Doctrine\DBAL\DBALException.php:172 {▶}
  G:\Documents\workspace\mana\vendor\doctrine\dbal\lib\Doctrine\DBAL\DBALException.php:145 {▶}
  G:\Documents\workspace\mana\vendor\doctrine\dbal\lib\Doctrine\DBAL\Connection.php:911 {▶}
  G:\Documents\workspace\mana\vendor\doctrine\orm\lib\Doctrine\ORM\Query\Exec\SingleSelectExecutor.php:50 {▶}
  G:\Documents\workspace\mana\vendor\doctrine\orm\lib\Doctrine\ORM\Query.php:334 {▶}
  G:\Documents\workspace\mana\vendor\doctrine\orm\lib\Doctrine\ORM\AbstractQuery.php:967 {▶}
  G:\Documents\workspace\mana\vendor\doctrine\orm\lib\Doctrine\ORM\AbstractQuery.php:922 {▶}
  G:\Documents\workspace\mana\vendor\doctrine\orm\lib\Doctrine\ORM\AbstractQuery.php:765 {▶}
  G:\Documents\workspace\mana\src\Repository\UserRepository.php:24 {▶}
  G:\Documents\workspace\mana\src\Security\LoginFormAuthenticator.php:74 {▶}
  G:\Documents\workspace\mana\vendor\symfony\security-guard\Provider\GuardAuthenticationProvider.php:102 {▶}
  G:\Documents\workspace\mana\vendor\symfony\security-guard\Provider\GuardAuthenticationProvider.php:96 {▶}
  G:\Documents\workspace\mana\vendor\symfony\security-core\Authentication\AuthenticationProviderManager.php:76 {▶}
  G:\Documents\workspace\mana\vendor\symfony\security-guard\Firewall\GuardAuthenticationListener.php:130 {▶}
  G:\Documents\workspace\mana\vendor\symfony\security-guard\Firewall\GuardAuthenticationListener.php:82 {▶}
  G:\Documents\workspace\mana\vendor\symfony\security-bundle\Debug\WrappedListener.php:46 {▶}
  G:\Documents\workspace\mana\vendor\symfony\security-bundle\Debug\TraceableFirewallListener.php:35 {▶}
  G:\Documents\workspace\mana\vendor\symfony\security-http\Firewall.php:90 {▶}
  G:\Documents\workspace\mana\vendor\symfony\security-bundle\EventListener\FirewallListener.php:48 {▶}
  G:\Documents\workspace\mana\vendor\symfony\event-dispatcher\Debug\WrappedListener.php:115 {▶}
  G:\Documents\workspace\mana\vendor\symfony\event-dispatcher\EventDispatcher.php:212 {▶}
  G:\Documents\workspace\mana\vendor\symfony\event-dispatcher\EventDispatcher.php:44 {▶}
  G:\Documents\workspace\mana\vendor\symfony\event-dispatcher\Debug\TraceableEventDispatcher.php:145 {▶}
  G:\Documents\workspace\mana\vendor\symfony\http-kernel\HttpKernel.php:126 {▶}
  G:\Documents\workspace\mana\vendor\symfony\http-kernel\HttpKernel.php:67 {▶}
  G:\Documents\workspace\mana\vendor\symfony\http-kernel\Kernel.php:198 {▶}
  G:\Documents\workspace\mana\public\index.php:25 {▶}

A:

The whole problem was that the argument of this->entityManager->getRepository(User::class)->loadUserByUsername(...) should NOT be an array but a scalar.
Perhaps I can make a business out of creating Alice-like rabbit holes for falling into.


Q:

use velocity ,occur "java.lang.NullPointerException"

(version:velocity-1.7,commons-collections-3.2)
I use velocity to parse vm template,and set value in request scope ,show in jsp
My app work normaly a period of time, but When users access a period of time after, this jsp show error,cannot access
here is log:
Mar 8, 2013 11:40:54 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet spring threw exception
java.lang.NullPointerException
    at org.apache.commons.collections.ExtendedProperties.clearProperty(ExtendedProperties.java:797)
    at org.apache.commons.collections.ExtendedProperties.setProperty(ExtendedProperties.java:722)
    at org.apache.commons.collections.ExtendedProperties.combine(ExtendedProperties.java:783)
    at org.apache.velocity.runtime.RuntimeInstance.setProperties(RuntimeInstance.java:657)
    at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:645)
    at org.apache.velocity.runtime.RuntimeSingleton.init(RuntimeSingleton.java:226)
    at org.apache.velocity.app.Velocity.init(Velocity.java:97)
    at com.feilong.tools.velocity.VelocityUtil.parseVMTemplateWithClasspathResourceLoader(VelocityUtil.java:67)
    at com.feilong.taglib.display.pager.PagerUtil.getPagerContent(PagerUtil.java:107)
    at com.feilong.taglib.display.pager.PagerTag.writeContent(PagerTag.java:48)
    at com.feilong.taglib.display.pager.PagerTag.writeContent(PagerTag.java:13)
    at com.feilong.taglib.base.AbstractCommonTag.doStartTag(AbstractCommonTag.java:19)
    at org.apache.jsp.pages.product.product_005flist_jsp._jspx_meth_feilongDisplay_005fpager_005f0(product_005flist_jsp.java:762)
    at org.apache.jsp.pages.product.product_005flist_jsp._jspx_meth_c_005fotherwise_005f1(product_005flist_jsp.java:433)
    at org.apache.jsp.pages.product.product_005flist_jsp._jspx_meth_c_005fchoose_005f1(product_005flist_jsp.java:243)
    at org.apache.jsp.pages.product.product_005flist_jsp._jspService(product_005flist_jsp.java:116)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

here is my util codes:
(two public method:sometimes i use to parse vm template ,sometimes i use to parse string)
/**
 * VelocityUtil
 *
 * @author feilong
  */
public final class VelocityUtil{

    private static String   RUNTIME_LOG_LOG4J_LOGGER        = "feilongVelocityLogger";

    private static String   RUNTIME_LOG_LOG4J_LOGGER_LEVEL  = "debug";

    public static String parseVMTemplateWithClasspathResourceLoader(String templateInClassPath,Map<String, Object> contextKeyValues){
        String resource_loader = "class";
        Properties properties = new Properties();
        properties.put(Velocity.RESOURCE_LOADER, resource_loader);
        properties.put(resource_loader + ".resource.loader.class", ClasspathResourceLoader.class.getName());
        properties.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, Log4JLogChute.class.getName());
        properties.put(Log4JLogChute.RUNTIME_LOG_LOG4J_LOGGER, RUNTIME_LOG_LOG4J_LOGGER);
        properties.put(Log4JLogChute.RUNTIME_LOG_LOG4J_LOGGER_LEVEL, RUNTIME_LOG_LOG4J_LOGGER_LEVEL);
        properties.put(Velocity.INPUT_ENCODING, CharsetType.UTF8);
        properties.put(Velocity.OUTPUT_ENCODING, CharsetType.UTF8);

        Velocity.init(properties);
        return parseVMTemplateAfterInitVelocity(templateInClassPath, contextKeyValues);
    }

    public static String parseVMContentWithStringResourceLoader(String vmContent,Map<String, Object> contextKeyValues){
        String resource_loader = "string";
        Properties properties = new Properties();
        properties.put(Velocity.RESOURCE_LOADER, resource_loader);
        properties.put(resource_loader + ".resource.loader.class", StringResourceLoader.class.getName());
        properties.put(Velocity.INPUT_ENCODING, CharsetType.UTF8);
        properties.put(Velocity.OUTPUT_ENCODING, CharsetType.UTF8);

        Velocity.init(properties);

        String templateName = "feilongStringVelocity";
        StringResourceRepository stringResourceRepository = StringResourceLoader.getRepository();
        stringResourceRepository.putStringResource(templateName, vmContent);
        return parseVMTemplateAfterInitVelocity(templateName, contextKeyValues);
    }

    private static String parseVMTemplateAfterInitVelocity(String templateName,Map<String, Object> contextKeyValues){
        Template template = Velocity.getTemplate(templateName, CharsetType.UTF8);
        VelocityContext velocityContext = new VelocityContext();
        if (null != contextKeyValues){
            for (Map.Entry<String, Object> entry : contextKeyValues.entrySet()){
                velocityContext.put(entry.getKey(), entry.getValue());
            }
        }
        Writer writer = new StringWriter();
        template.merge(velocityContext, writer);
        try{
            writer.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
        return writer.toString();
    }
}

A:

If you are initializing Velocity every time you render the jsp (and it looks like you are from the code you posted) this could be the issue.
I've had this issue before and resolved it by initializing the VelocityEngine once and storing it for future use.
Taken from here (credit to 'Will Glass-Husain-2' from the Velocity forum on nabble.com):

Here's the general pattern. On app start up, initialize a
  VelocityEngine. Store it somewhere. Every time you need to process a
  template, get the template, create and populate a context, using the
  velocity engine merge the template (with the context).

In your code above, you could try moving the Velocity.init call to another method (called initialize, for example) which only gets called on first use of a method in your utils class. After initialize is called once, store that in a boolean and don't call initialize again.


Q:

jQuery dollar sign is undefined

In my quest to get historical information, i tried using the below code. Chrome debugger says that Uncaught ReferenceError: $ is not defined. Can you suggest a fix, i'm really stuck. I just need this to work on Chrome, and I am tapping into YQL and Yahoo API.
here is the jsFiddle http://jsfiddle.net/pCK5q/1/

    // Note how you must specify the size of the container element explicitly!

A:

Just add a reference to the JQuery source before your script:

A:

Add this line:
google.load("jquery", "1.7.1");

Just under this one you already have:
google.load('visualization', '1', {'packages':['annotatedtimeline']});

This will load jQuery from the Google jsapi you already use. This is the best solution regarding your code.


Q:

Quando e como devo usar operador instanceof e typeof no JavaScript

Quando e como devo usar operador instanceof e typeof no JavaScript?
Em um post do Stack EN vejo a usabilidade do instanceof. Porém, em outro post do Stack EN diz que não é necessário usar nenhum outro operador além do typeof. Então gostaria de ver exemplos situacionais sobre ambos operadores.

A:

O instanceof e o typeof têm de facto maneiras de usar que se sobrepõem. Mas têm também diferenças que os tornam distintos e aplicáveis em casos diferentes.
Repara que o typeof dá object para os seguintes casos:
typeof (new Date())  // "object"
typeof [1, 2, 3]     // "object"
typeof {foo: 'bar'}  // "object"

e no caso dos exemplos em cima podes ter uma resposta mais específica com o instanceof:
(new Date()) instanceof Date // true
[1, 2, 3] instanceof Array   // true
({foo: 'bar'}) instanceof Object // true

Lembra-te no entanto que em JavaScript o seguinte também é válido:
(new Date()) instanceof Object // true
[1, 2, 3] instanceof Object    // true

Por isso é bom ser específico com a instancia com que se compara.
Outra utilização onde o instanceof é muito útil é para saber se um objeto ou classe é uma instancia/herda de outra. Repara no exemplo em baixo e nos resultados de console.log():

class Transporte {
  constructor(marca) {
    this.tipo = marca;
  }
}

class Carro extends Transporte {
  constructor(marca) {
    super(marca);
    this.tipo = 'Carro';
  }
}

class Mota extends Transporte {
  constructor(marca) {
    super(marca);
    this.tipo = 'Mota';
  }
}

const VW = new Carro('Volkswagen');
const Kawasaki = new Mota('Kawasaki');

console.log(VW instanceof Carro); // true
console.log(Kawasaki instanceof Mota); // true
console.log(Kawasaki instanceof Carro); // false
console.log(VW instanceof Transporte); // true
console.log(Kawasaki instanceof Transporte); // true

A:

O operador typeof sempre resulta numa string com o nome do tipo primitivo do objeto. Por exemplo, se você executar o seguinte comando:
var a = typeof 1;

A variável a vai ter como valor a string "number". Ou seja, se você quer executar um código caso a variável value seja do tipo primitivo number, você deve fazer:
if (typeof value === "number") {
   // ...
}

No caso acima, a expressão typeof value irá ser resolvida para uma string com o tipo de value, que em seguida será comparada com a string "number".
Já o instanceof resulta num booleano que indica se um objeto foi gerado (direta ou indiretamente) por uma função construtora: obj instanceof func.
function Carro(cor, nome) {
   this.cor = cor;
   this.nome = nome;
}

var foo = new Carro("preto", "ka");
var bar = "teste";

foo instanceof Carro; // retorna true
bar instanceof Carro; // retorna false

Portanto, se você quiser fazer um if com instanceof, deve ficar assim:
if (obj instanceof Carro) {
   //
}

já que a expressão obj instanceof Car vai ser resolvida para um boolean.
Note que no exemplo abaixo, o valor de retorno de typeof é "object", ou seja, o typeof nunca pode ser usado para testar se um objeto foi criado por uma determinada função construtora, mas somente para testar o tipo primitivo do objeto.
var foo = new Carro();
typeof foo; // retorna "object"

Espero ter ajudado!

A:

O typeof e o instanceof são complementares, além de possuírem sintaxes diferentes.
O typeof verifica o tipo primitivo de um valor, e sempre retorna uma das seguintes strings:
"undefined"
"boolean"
"number"
"string"
"object"
"function"
"symbol"

Já o instanceof percorre a cadeia de protótipos de um determinado objeto, e verifica se nessa cadeia existe referência a um segundo objeto, retornando um booleano. Isso serve para verificar se um objeto herda de outro.
Como se vê, são funções totalmente diferentes, além do fato de o typeof se aplicar a qualquer valor, e o instanceof somente a objetos. Existe alguma confusão porque o typeof nunca distingue o tipo de objeto (exceto no caso das funções e símbolos), e para isso é necessário utilizar o instanceof e/ou outras técnicas. Há ainda o caso de typeof null === "object", que pode parecer confuso mas tem explicação.
Aproveito ainda para esclarecer um mal-entendido da sua pergunta, quando você diz:

Porem em outro post do Stack EN diz que não é necessário usar nenhum outro operador alem do typeof

Na verdade não é isso que esse post diz. Ele diz apenas que, para descobrir se um valor é uma função, é melhor usar o typeof do que a função isFunction da biblioteca underscore.


Q:

Is it possible to override `__name__` derived from object?

To get a string representation of a class name we can use obj.__class__.__name__ is it possible to overload these methods so that I can return my string instead of the actual class name?

A:

Let's try!  (Yes, this works):
>>> class Foo(object):
...     pass
...
>>> obj = Foo()
>>> obj.__class__.__name__ = 'Bar'
>>> obj
<__main__.Bar object at 0x7fae8ba3af90>
>>> obj.__class__
<class '__main__.Bar'>

You could also have just done Foo.__name__ = 'Bar', I used obj.__class__.__name__ to be consistent with your question.

A:

Yep.
class A:
    def __init__(self):
        self.__class__.__name__ = 'B'

But this seems like a bad idea.


Q:

Is it normal for a double skin popup tent to leak in slight rain?

About a year ago I was given a three person dual skin popup tent. Almost new but possibly a factory second.
(It's made by "Vango" and I think it could be a "reject" because one of the four guy ropes is not attached to the tent and looks like it didn't get ripped off but was never attached.)
Anyway it's a great tent and I have used it on a grassy area, properly pegged, in reasonably solid rain with 3 people and luggage with minimal wetness.
But now I'm camping wild at the beach and water has made it into the tent twice, always from one of the corners.
When I first set it up on the beach instead of trying to use the pegs I weighed it down with rocks inside between the inner and outer skins. (The standard pegs are not heavy duty enough for dry sand and windy conditions and I was too lazy to use sand-filled plastic bottles instead of pegs.)
Another factor is the sand was on a bit of a slope so I dug down a bit at the back and used that sand to build up the front, thus making the area flat but the rear is a bit like a trench and also it's not a perfect fit for the tent. Some corners are a bit outside the flat part and the rocks between the skins could slide down a bit, especially when there's some rain, wind, or both.
When I added the tent pegs and guy ropes after the first storm, because they weren't very deep, I dug down a little so the pegs would hold better, put a rock on top to weigh them down, and covered them with a pile of packed sand. In some places I may have heaped a bit of sand over the lower edge of the tent wall too.

Were the rocks between the skins the cause of rain getting in at the corners?
Or possibly the imperfect fit in my dug out slope?
Or possibly having some sand piled on the tend walls? (not much)
Or are all of these factors usually no problem thus pointing to more possible manufacturing defects?
Or maybe Vango is known to be an inferior brand of tent?

Are there some general "dos and don'ts" for setting up a dual skin tents or popup tents or tents on sloping sand?

A:

I'm not familiar with your specific tent, but you typically don't block ventilation in a double walled tent. The outer rain fly will collect condensation from your own breathing and the tent needs to breath to reduce it.
You also need to seal the seams on a tent if the factory doesn't do it for you, and sometimes even when they do. You can find lots of products for this, including McNett Seam Grip (no affiliation):

A:

There is one thing about tents in general (well, at least I don't know any exception) - they are absolutely not waterproof!. The outer part simply soaks with water and leads it down to the ground. But if you touch it - you have a rain inside. It's just like touching the surface of the umbrella from the below.
So there is one thing you must take very seriously when preparing for rain in tent - the outer and inner layer of the tent must not touch!. If you have one-layer tent, nothing can touch the outer layer as well! A tent is actually just a big umbrella.
By 2-layer tents you should make the inner layer possibly loose, while the outer layer should be tight.

A:

Sand will be an inherently trickier environment to camp in successfully I would imagine, since it retains moisture well and isn't as solid as earth.
Personally I've never camped in sand, but I would imagine even a bit of sand piled on the tent walls could be the cause, that would be the first thing I'd try to eliminate. If the sand is moist (or becomes moist) then you have in effect a wet solid pressing against the tent, in which case water could be very likely to make its way through in small quantities.


Q:

NBA.com Tracking Stats using python?

Could anybody give me some help in my attempt to pull down the NBA.com "tracking" stats using a python script into a simple table?  This would be an example of the area of stats from the site i'm having trouble with.
http://stats.nba.com/tracking/#!/player/defense/
NBA.com makes it a bit difficult to get direct access to their stats, instead opting to make it, i think, a java formatted table that won't all show at once.  Somebody asked a similar question and was given a decent python example code for a section of nba.com stats, the team advanced stats, and the table itself isn't very clean.  It's pretty easy to alter to grab most of the code give in that to get other stats from the site, however, the "tracking" ones, which are new, i'm unable to determine the right query. The other answer is shown in the following link.
Beautiful Soup Not Getting NBA.com Data
Thanks!

A:

http://stats.nba.com/js/data/sportvu/2014/defenseData.json
http://stats.nba.com/js/data/sportvu/2014/catchShootData.json
http://stats.nba.com/js/data/sportvu/2014/drivesData.json
... and so on. Use Chrome developer tools to the the URL's. Look in the network tab, filtering by XHR makes it easier to spot usually.


Q:

How do I write a java pattern in this format: filepath (int, int) (int,int)?

For example
c:\55.bmp  (3,4) (45,7)
I want to get the filepath which is c:\55.bmp and the numbers 3, 4, 45 and 7.

A:

([A-z]:\\[^\s]*)\s\((\d*),(\d*)\)\s\((\d*),(\d*)\)
This pattern will match "c:\55.bmp (3,4) (45,7)" with subgroups:

$1 = C:\55.bmp
$2 = 3
$3 = 4
$4 = 45
$5 = 7


Q:

Postgres sql exception handling for batch insert

I have two tables and i am inserting the data from one table to other.
insert into a (id1, value1)
select id, value from b

id1 is unique and when I have repeating id in table b. How can I catch the exception for each row in PostgreSQL without halting the execution.

A:

If you can't do as @a_horse_with_no_name suggests and avoid the exception then  a PL/PgSQL procedure that loops over a query and does a BEGIN ... EXCEPTION ... block is the way to go.
This is massively less efficient than filtering out the problem rows with a WHERE clause and (if needed) join, so it should be avoided if possible.
The main time it's necessary is if, say, an exception is being thrown by validation code you can't run to produce a boolean for a where clause. Unfortunately most of PostgreSQL's data-type input functions don't have a "test" mode where you can get a NULL result or error flag for invalid input, so this is usually the case for things like date/time parsing.
You want to do something like:
DO
LANGUAGE plpgsql
$$
DECLARE
  r record;
BEGIN
  FOR r IN SELECT a, b FROM mytable
  LOOP
    BEGIN
      INSERT INTO newtable (x, y)
      VALUES (r.a, r.b);
    EXCEPTION
      WHEN check_violation THEN
        RAISE NOTICE 'Skipped row %', r.a;
    END;
  END LOOP;
END;
$$;

For details, see the PL/PgSQL manual.
Note that this does a subtransaction for every loop iteration and also requires executor state setup for every iteration, so it's way slower than doing it with an INSERT INTO ... SELECT ... WHERE ....

A:

Just don't insert those that would cause an error:
insert into a (id1, value1)
select id, value
from b
where not exists (select 1
                  from a
                  where a.id1 = b.id);

Or just select the unique ones if a is empty:
insert into a (id1, value1)
select distinct on (id) id, value
from b
order by id;


Q:

Why setting format in gl.texImage2D to gl.LUMINANCE instead of gl.RGB makes the blob made out of the canvas only ~5% smaller in filesize?

While exploring javascript, I encountered a question that is quite baffling. The preface is: I convert images of different mime types (mostly pngs/jpgs) into bitmaps with ImageBitmap interface, then transfer them to worker to convert in separate thread into blob(to do so I firstly draw them into offscreen canvas context) and then save into IDB, while main thread continues to load new images. While doing so, to broaden my horizons, I decided to use webgl2 rendering context in the canvas since GL is something I never touched.
To apply bitmap to canvas I use texImage2D function, which I seem to not understand. There I can specify format of data stored in memory being presented to GLSL (it should be rgb(right?) since bitmap was created with no alpha premultiplying), internal format and type. Since the combinations of format/internal format/type are specified by spec, I tried to make use of their multitude and chose the best(quality-/filesize-wise) for my purposes. Since images being converted to bitmap are mostly black and white, I thought that luminance is what I need. But first I used standard RGB format:
gl.texImage2D(
    gl.TEXTURE_2D, 0, gl.RGB, bitmap.width, bitmap.height, 0, gl.RGB, gl.UNSIGNED_BYTE, bitmap
);

Then I used RGB565 with UNSIGNED_SHORT_5_6_5 data type and didn't see any quality losses while blob size was decreased by ~30% from RGB. How I understand, it decreased because RGB565 is 2 unsigned short bytes per pixel, right? Then I used UNSIGNED_SHORT_5_5_5_1 RGBA and blob file size compared to standard RGB was decreased by ~43%. Even less then RGB565! But gradients on images became wonky so no 5551RGBA for me. The big difference in size between 5551 RGBA and RGB565 is something I don't understand. And what is more confusing is when using Luminance according to spec type/format/internal format combination, the decrease from standard RGB is only ~5%. Why did RGB565 decreased size for whooping ~30% while luma for a mere ~5%?
For all this I used the same floating-point sampler in fragment shader:
 #version 300 es
 precision mediump float;
 precision mediump sampler2D;

 uniform sampler2D sampler;
 uniform vec2 dimensions;

 out vec4 color;

 void main(){
      color = texture(sampler, vec2(gl_FragCoord.x/dimensions.x, 1.0 - (gl_FragCoord.y/dimensions.y)));
 }

Also the same pixelStorei and texParameteri:
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

As shows snippet below, the luma doesn't change the file size of blob if image is black and white, while if colored the decrease is apparent, though still smaller then RGBA4. Quite counterintuitive considering RGBA4 has 2 bytes per pixel, while LUMA - 1.

(async() => {
function createImage(src) {
 return new Promise((rs, rj) => {
  var img = new Image();
  img.crossOrigin = 'anonymous';
  img.src = src;
  img.onload = () => rs(img);
  img.onerror = e => rj(e);
    });
};

var jpeg = await createImage('https://upload.wikimedia.org/wikipedia/commons/a/aa/5inchHowitzerFiringGallipoli1915.jpeg');

var png = await createImage('https://upload.wikimedia.org/wikipedia/commons/2/2c/6.d%C3%ADl_html_m2fdede78.png');

var jpgClr = await createImage('https://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/%22Good_bye%2C_sweetheart%22%2C_tobacco_label%2C_ca._1865.jpg/117px-%22Good_bye%2C_sweetheart%22%2C_tobacco_label%2C_ca._1865.jpg');

var format = {
    standard: {
        internalFormat: 'RGB8',
        format: 'RGB',
        type: 'UNSIGNED_BYTE',
    },
    rgb565: {
        internalFormat: 'RGB565',
        format: 'RGB',
        type: 'UNSIGNED_SHORT_5_6_5',
    },
    rgb9e5: {
        internalFormat: 'RGB9_E5',
        format: 'RGB',
        type: 'FLOAT',
    },
    srgb: {
        internalFormat: 'SRGB8',
        format: 'RGB',
        type: 'UNSIGNED_BYTE',
    },
    rgba32f: {
        internalFormat: 'RGB32F',
        format: 'RGB',
        type: 'FLOAT',
    },
    rgba4: {
        internalFormat: 'RGBA4',
        format: 'RGBA',
        type: 'UNSIGNED_SHORT_4_4_4_4',
    },
    rgb5a1: {
        internalFormat: 'RGB5_A1',
        format: 'RGBA',
        type: 'UNSIGNED_SHORT_5_5_5_1',
    },
    luma: {
        internalFormat: 'LUMINANCE',
        format: 'LUMINANCE',
        type: 'UNSIGNED_BYTE',
    },
};

function compareFormatSize(image) {
    return new Promise((r, _) => {
  createImageBitmap(image, {
            premultiplyAlpha: 'none',
            colorSpaceConversion: 'none',
        }).then(async bitmap => {
var text = String(image.src.match(/(?<=\.)\w{3,4}$/)).toUpperCase();
            console.log(`${text === 'JPG' ? 'Colored jpg' : text}:`);
            for (let val of Object.values(format)) {
                await logBlobSize(bitmap, val);
            if(val.format === 'LUMINANCE') r();
            }
        }).catch(console.warn);
    });
};

compareFormatSize(jpeg).then(_ => compareFormatSize(png)).then(_ => compareFormatSize(jpgClr));

function logBlobSize(bitmap, { internalFormat, format, type }) {
  return new Promise(r => {
    drawCanvas(bitmap, internalFormat, format, type).convertToBlob({
      type: `image/webp`
    }).then(blob => { console.log(`Blob from ${internalFormat} is ${blob.size}b`); r(); });
  })
}

function drawCanvas(bitmap, internalFormat, format, type) {
    const gl = (new OffscreenCanvas(bitmap.width, bitmap.height)).getContext("webgl2", {
        antialias: false,
        alpha: false,
        depth: false,
    });

    function createShader(gl, type, glsl) {
        const shader = gl.createShader(type);
        gl.shaderSource(shader, glsl)
        gl.compileShader(shader);
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            console.error(gl.getShaderInfoLog(shader));
            gl.deleteShader(shader);
            return;
        }
        return shader;
    }

    const vs = createShader(
        gl,
        gl.VERTEX_SHADER,
        `#version 300 es
        #define POSITION_LOCATION 0
        layout(location = POSITION_LOCATION) in vec2 position;

        void main()
        {
            gl_Position = vec4(position, 0.0, 1.0);
        }`,
    );

    const fs = createShader(
        gl,
        gl.FRAGMENT_SHADER,
        `#version 300 es
        precision mediump float;
        precision mediump sampler2D;

        uniform sampler2D sampler;
        uniform vec2 dimensions;

        out vec4 color;

        void main()
        {
            color = texture(sampler, vec2(gl_FragCoord.x/dimensions.x, 1.0 - (gl_FragCoord.y/dimensions.y)));
        }`,
    );

    const program = gl.createProgram();
    gl.attachShader(program, vs);
    gl.attachShader(program, fs);
    gl.linkProgram(program);

    const sampler = gl.getUniformLocation(program, 'sampler');
    const dimensions = gl.getUniformLocation(program, 'dimensions');
    const position = 0; // GLSL location

    const vao = gl.createVertexArray();
    gl.bindVertexArray(vao);
    gl.enableVertexAttribArray(position);
    const vxBuffer = gl.createBuffer();
    const vertices = new Float32Array([
        -1.0,-1.0,
         1.0,-1.0,
        -1.0, 1.0,
         1.0, 1.0,
    ]);
    gl.bindBuffer(gl.ARRAY_BUFFER, vxBuffer);
    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

    const texture = gl.createTexture();
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
    gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texImage2D(
        gl.TEXTURE_2D,
        0,
        gl[internalFormat],
        bitmap.width,
        bitmap.height,
        0,
        gl[format],
        gl[type],
        bitmap
    );

    gl.useProgram(program);
    gl.uniform1i(sampler, 0);
    gl.uniform2f(dimensions, gl.canvas.width, gl.canvas.height);
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

    gl.deleteTexture(texture);
    gl.deleteVertexArray(vao);
    gl.deleteBuffer(vxBuffer);
    gl.deleteProgram(program);

 return gl.canvas;
}
})()

Thanks in advance!

A:

The canvas is always RGBA 8bit (32bit color). There is talk of adding options for having a deeper depth canvas to support HD color displays but that hasn't shipped.
So, calling canvas.converToBlob is always going to give you an RGBA32bit png (or jpeg). You create a LUMIANCE texture will give you a black and white texture but it gets drawn into an RGBA 32bit canvas. There is no option to get a 1 channel PNG.
As for RGB565, RGBA5551 etc those formats may or may not be supported directly by the hardware, the spec allows the driver to choose a format that is a higher resolution and I'm guessing most desktops expand the data into RGBA8 when you upload the data so it won't save any memory.
On the other hand uploading as RGB565 or RGBA5551 the WebGL spec requires that when you pass an image that the image is first converted to that format, so the browser is going to take your image and effectively quantize it down to those color depths which means you're loosing colors. You then draw the quantized image back to the canvas and save so of course it's likely to compress better since there are more similar colors.
From the WebGL spec for the version of texImage2D that takes an ImageBitmap

The source image data is conceptually first converted to the data type and format specified by the format and type arguments, and then transferred to the WebGL implementation. Format conversion is performed according to the following table. If a packed pixel format is specified which would imply loss of bits of precision from the image data, this loss of precision must occur.

Let's try it without WebGL

(async() => {
  function createImage(src) {
    return new Promise((rs, rj) => {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      img.src = src;
      img.onload = () => rs(img);
      img.onerror = rj;
    });
  };

  const jpeg = await createImage('https://upload.wikimedia.org/wikipedia/commons/a/aa/5inchHowitzerFiringGallipoli1915.jpeg');

  const png = await createImage('https://upload.wikimedia.org/wikipedia/commons/2/2c/6.d%C3%ADl_html_m2fdede78.png');

  const jpgClr = await createImage('https://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/%22Good_bye%2C_sweetheart%22%2C_tobacco_label%2C_ca._1865.jpg/117px-%22Good_bye%2C_sweetheart%22%2C_tobacco_label%2C_ca._1865.jpg');

  const format = {
    standard: {
      internalFormat: 'RGB8',
      format: 'RGB',
      type: 'UNSIGNED_BYTE',
      fn: p => [p[0], p[1], p[2], 255],
    },
    rgb565: {
      internalFormat: 'RGB565',
      format: 'RGB',
      type: 'UNSIGNED_SHORT_5_6_5',
      fn: p => [
        (p[0] >> 3) * 255 / 31,
        (p[1] >> 2) * 255 / 63,
        (p[2] >> 3) * 255 / 31,
        255,
      ],
    },
    rgba4: {
      internalFormat: 'RGBA4',
      format: 'RGBA',
      type: 'UNSIGNED_SHORT_4_4_4_4',
      fn: p => [
        (p[0] >> 4) * 255 / 15,
        (p[1] >> 4) * 255 / 15,
        (p[2] >> 4) * 255 / 15,
        (p[3] >> 4) * 255 / 15,
      ],
    },
    rgb5a1: {
      internalFormat: 'RGB5_A1',
      format: 'RGBA',
      type: 'UNSIGNED_SHORT_5_5_5_1',
      fn: p => [
        (p[0] >> 3) * 255 / 31,
        (p[1] >> 3) * 255 / 31,
        (p[2] >> 3) * 255 / 31,
        (p[3] >> 7) * 255 / 1,
      ],
    },
    luma: {
      internalFormat: 'LUMINANCE',
      format: 'LUMINANCE',
      type: 'UNSIGNED_BYTE',
      fn: p => [p[0], p[0], p[0], 255],
    },
  };

  async function compareFormatSize(image) {
    const bitmap = await createImageBitmap(image, {
      premultiplyAlpha: 'none',
      colorSpaceConversion: 'none',
    });
    const text = String(image.src.match(/(?<=\.)\w{3,4}$/)).toUpperCase();
    log(`${text === 'JPG' ? 'Colored jpg' : text}:`);
    for (const val of Object.values(format)) {
      await logBlobSize(bitmap, val);
    }
  };

  await compareFormatSize(jpeg);
  await compareFormatSize(png);
  await compareFormatSize(jpgClr);

  async function logBlobSize(bitmap, {
    internalFormat,
    format,
    type,
    fn,
  }) {
    const canvas = drawCanvas(bitmap, internalFormat, format, type);
    const blob = await canvas.convertToBlob({
      type: `image/webp`
    });
    const canvas2 = drawFn(bitmap, fn);
    const blob2 = await canvas2.convertToBlob({
      type: `image/webp`
    });
    log(`Blob from ${internalFormat} is ${blob.size}b(webgl) vs ${blob2.size}b(code)`);
    if (false) {
      const img = new Image();
      img.src = URL.createObjectURL(blob);
      document.body.appendChild(img);
      const img2 = new Image();
      img2.src = URL.createObjectURL(blob2);
      document.body.appendChild(img2);
    }
  }

  function drawFn(bitmap, fn) {
    const ctx = (new OffscreenCanvas(bitmap.width, bitmap.height)).getContext("2d");
    ctx.drawImage(bitmap, 0, 0);
    const imageData = ctx.getImageData(0, 0, bitmap.width, bitmap.height);
    const pixels = imageData.data;
    for (let i = 0; i < pixels.length; i += 4) {
      const n = fn(pixels.subarray(i, i + 4));
      pixels.set(n, i);
    }
    ctx.putImageData(imageData, 0, 0);
    return ctx.canvas;
  }

  function drawCanvas(bitmap, internalFormat, format, type) {
    const gl = (new OffscreenCanvas(bitmap.width, bitmap.height)).getContext("webgl2", {
      antialias: false,
      alpha: false,
      depth: false,
    });

    function createShader(gl, type, glsl) {
      const shader = gl.createShader(type);
      gl.shaderSource(shader, glsl)
      gl.compileShader(shader);
      if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        console.error(gl.getShaderInfoLog(shader));
        gl.deleteShader(shader);
        return;
      }
      return shader;
    }

    const vs = createShader(
      gl,
      gl.VERTEX_SHADER,
      `#version 300 es
        #define POSITION_LOCATION 0
        layout(location = POSITION_LOCATION) in vec2 position;

        void main()
        {
            gl_Position = vec4(position, 0.0, 1.0);
        }`,
    );

    const fs = createShader(
      gl,
      gl.FRAGMENT_SHADER,
      `#version 300 es
        precision mediump float;
        precision mediump sampler2D;

        uniform sampler2D sampler;
        uniform vec2 dimensions;

        out vec4 color;

        void main()
        {
            color = texture(sampler, vec2(gl_FragCoord.x/dimensions.x, 1.0 - (gl_FragCoord.y/dimensions.y)));
        }`,
    );

    const program = gl.createProgram();
    gl.attachShader(program, vs);
    gl.attachShader(program, fs);
    gl.linkProgram(program);

    const sampler = gl.getUniformLocation(program, 'sampler');
    const dimensions = gl.getUniformLocation(program, 'dimensions');
    const position = 0; // GLSL location

    const vao = gl.createVertexArray();
    gl.bindVertexArray(vao);
    gl.enableVertexAttribArray(position);
    const vxBuffer = gl.createBuffer();
    const vertices = new Float32Array([-1.0, -1.0,
      1.0, -1.0, -1.0, 1.0,
      1.0, 1.0,
    ]);
    gl.bindBuffer(gl.ARRAY_BUFFER, vxBuffer);
    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

    const texture = gl.createTexture();
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
    gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texImage2D(
      gl.TEXTURE_2D,
      0,
      gl[internalFormat],
      bitmap.width,
      bitmap.height,
      0,
      gl[format],
      gl[type],
      bitmap
    );

    gl.useProgram(program);
    gl.uniform1i(sampler, 0);
    gl.uniform2f(dimensions, gl.canvas.width, gl.canvas.height);
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

    gl.deleteTexture(texture);
    gl.deleteVertexArray(vao);
    gl.deleteBuffer(vxBuffer);
    gl.deleteProgram(program);

    return gl.canvas;
  }
})()

function log(...args) {
  const elem = document.createElement('pre');
  elem.textContent = [...args].join(' ');
  document.body.appendChild(elem);
}
pre { margin: 0; }

Why setting format in gl.texImage2D to gl.LUMINANCE instead of gl.RGB makes the blob made out of the canvas only ~5% smaller in filesize?

I'm not seeing these results. In your example the black and white images stay the same size as RGB vs LUMIANCE. The color image becomes 1/2 size. But of course it depends on the compression algorithm whether or not a black and white 32bit image gets compressed smaller than a color 32bit image since in all cases the canvas is 32bits when convertToBlob is called.


Q:

Fetching JSON from an external web-service - trying to refactor/tidy my code

I have a Podcast model with one attribute called :url.
A typical :url takes the following form: http://api.mixcloud.com/alivefrommaryhill/jazzcast/ and returns a JSON file
Using hashie and httparty, we can write a method (called  get_json) that uses this URL to create a hash from the JSON that it links to:
class Podcast < ActiveRecord::Base
  attr_accessible :url

  def get_json
    Hashie::Mash.new HTTParty.get("#{self.url}")
  end
end

We can then use get_json in our views to style and display the JSON:
#/views/podcasts/index.html.haml
- for podcast in @podcasts
  = link_to podcast.get_json.name, podcast_path(podcast)
  = podcast.get_json.description
  = image_tag podcast.get_json.pictures.medium

As you can see, each podcast calls get_json three times. I've got 21 podcasts and don't want to call this method more than once per visit since it connects to an external web-service which is very time-consuming. How can I minimize the number of times this method is called and speed things up?
Perhaps I should be doing more in my controller instead of calling the method from my view?
def index
  @podcasts = Podcast.all
end

Any help appreciated

A:

Well, the easiest fix for now would be to save the result of podcast.get_json in a local variable. That'd cut it down to once per podcast.
If you want to further reduce the number of calls, you'd have to figure a way to batch all your requests. I don't know if that site's API will let you do that.


Q:

How do I get my console application to run a background process on another thread without exiting?

I am aware that in .NET there are three timer types (see Comparing the Timer Classes in the .NET Framework Class Library). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable.
The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy.
The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything so the application closes.
I tried adding a while true loop, but then the main thread is too busy when the timer does go off.

A:

I would use a Barrier that waits until all threads are done. Since there is a main and a counting thread, I have 2 participants. So it will look something like this:
 Module Module1
        Dim x As New Threading.Thread(AddressOf tick)
        Dim y As New Threading.Barrier(2)

        Sub Main()
            x.IsBackground = True
            x.Start()
            y.SignalAndWait()
        End Sub

        Sub tick()
            Threading.Thread.Sleep(10000)
            y.SignalAndWait()
        End Sub
    End Module


Q:

Refactoring a regular expression check in ruby

I'm thinking there has got to be a cleaner way to check if a regular expression is not nil / is true.  This is what I have been using:
hold = (h4.text =~ /Blah/)
if !hold.nil?
  ...
end
I tried: !(h4.text =~ /Blah/).nil? but it did not seem to work.

A:

#!/usr/bin/ruby1.8

text = 'Blah blah blah'
puts "blah" if text =~ /Blah/    # => blah

text = 'Foo bar baz'
puts "blah" if text =~ /Blah/    # (nothing printed)

In a Ruby conditional statement,
anything that is neither nil nor
false is considered to be true.
=~ returns nil for no match, or an integer character position if there
is a match.
nil is as good a false; an integer is
as good as true.

Therefore, you can use the result of =~ directly in an if, while, etc.


Q:

Elm : How to make use of value with (Result String Value)

For example
fromIsoString : String -> Result String Date

fromIsoString will produce Ok (Value) ... Any methods that i can use to do something with the Value
As what i tested it is working with
text ( `Value` |> Date.add Days -1|> Date.toIsoString)

Method tried : Date.fromIsoString "2018-09-26" |> Result.withDefault 0 gives error -> expects:
Result String #Date#

Ideally i want to transform ISO date (2020-05-10) into Date format and do something with the date like -1 day.
Reference :
https://github.com/justinmimbs/date/blob/3.2.0/src/Date.elm

A:

You’re seeing this Result String #Date# error because you’ve passed Result.withDefault a number where it expects a Date. If we look at the withDefault type annotation:
> Result.withDefault
<function> : a -> Result x a -> a

withDefault expects a default of the same type a as the successful result. Because you’ve specified 0 : number as the default, its type becomes:
> \result -> Result.withDefault 0 result
<function> : Result x number -> number

Note that result's type is Result x number, which doesn't line up with fromIsoString's Result String Date output type.
TLDR: Pass a Date as the default argument, e.g.:
> defaultDate = Date.fromCalendarDate 2020 Jan 1
RD 737425 : Date
> Date.fromIsoString "2018-09-26" |> Result.withDefault defaultDate
RD 736963 : Date

Take a look at the Elm Result documentation for other functions you can call on values of type Result String Date


Q:

waypoints, animate.css and opacity on scroll issue

I am using waypoints.js and animate.css to animate elements on my page as you scroll down. I am wondering how to incorporate the built in opacity properties in the animate.css framework. In my fiddle you can see how apon entering the screen from top or bottom my image will animate but how could I make it fade in as well. notice how on the second image it fades in but flash first kinda of looks glitchy.
Here is my javascript:
//Animate from top
$('.animated').waypoint(function() {
$(this).toggleClass($(this).data('animated'));
},
{ offset: 'bottom-in-view' });
//Animate from bottom
$('.animated').waypoint(function() {
$(this).toggleClass($(this).data('animated'));
});

or
http://jsfiddle.net/3qy0hs3L/1/

A:

All that needs to be done is add the opacity:0 to your img.


Q:

Building a byte-addressable memory

I am building a memory module:

32 bits wide,
parallel, and,
byte-addressable.

I did a research and i could not find an memory IC that will suit my needs.

It must be able to:

StoreWord,
StoreHalf and,
StoreByte (RISC-V), with or without an offset.

One suggestion was to build it from four 8bits RAMs. I simulated it in Logisim-Evolution, as suggested masking out unwanted data, but even in the uncomplete state, it seems a little too large.
I plan to build it in real life, so it must have as little components as possible, but i just cannot think of a way how to build it, or how is it made in industry?

Thanks for any help

A:

...  even in the uncomplete state, it seems a little too large.

Nope, looks about right to me. I used to build motherboards for engineering workstations (overgrown PCs) in the 1980s, and this is exactly the sort of thing we had to do.
The right side of your drawing is the actual memory (note that one of your modules has a different size from the others). The left and center sections are what we call "byte steering" logic. This is what you need if your CPU isn't doing this for you internally.
You should see how much fun it is to interface a Motorola 680x0 CPU bus to an Intel (PC/AT) peripheral bus. This ended up being one of the first places we used an FPGA, because of the complexity.


Q:

saving current date and time in my iPhone application?

In my application i am using In - App purchases to provide a subscription of 1 year….now i need to save the time and date when the user buys the subscription and need to check when the subscription expires?? i have not used database before  is there any other way to store date and time in my application and retrieve it every time the application starts??

A:

You should store the purchase of a subscription on a server, with backup in place, not only on the device.
You might have noticed that if you delete any iPhone app, and later re-install it, then the next download is free. There can be many reasons as to why the user might loose your app, a system update went bad, or whatever.
Apple specifically requires that the user do not loose what they have bought. If you have promised 1 year, then you must make sure they get 1 year no matter what happens to your app. Otherwise Apple can, and will, reject your app.
Storing the expiration date on a server also give the added benefit of protection against users fiddling with your data and granting themselves extended subscriptions.
Start by looking at the In App Purchase Programming Guide.

A:

You can simply store it in NSUserDefaults:
[[NSUserDefaults standardUserDefaults] setObject:[NSDate now] forKey:@"purchaseDate"];

Then retrieve it like such:
NSDate *purchaseDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"purchaseDate"];

And when you're done with it:
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"purchaseDate"];


Q:

How to get the proper URL from this tag value?

How to get the proper url link from the tag value. I have used NSXMLParser for parsing and parsed content successfully but stucked with the url value like:
<value> http://example.site.com/%3Ca%20href%3D%22/taxonomy/term/3%22%3ETheater%3C/a%3E </value>

I have tried with some string replacement operation but not any good result.
How i format that string value and get the exact url string.
Thanks in advance :)

A:

Try this
NSString *value = @"http://example.site.com/%3Ca%20href%3D%22/taxonomy/term/3%22%3ETheater%3C/a%3E";

NSString *formattedValue = [value stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSArray *array = [formattedValue componentsSeparatedByString:@"<a"];
NSLog(@"%@",[array objectAtIndex:0]);


Q:

How to use PowerShell multithreading and still unit test with Pester Mocks

I'm trying to do a simple parallel operation in Powershell.  I am using PoshRSJobs for multithreading, though I have also tried Invoke-Parallel with the same issue.
 I need to call a couple of my own functions in the scriptbody of the job, but this does not allow me to MOCK those functions for unit testing (they end up being the original non-mocked functions).  At this point, I'm just trying to assert that they have been called the correct number of times.
Here is the original class (the functionality of the imported modules are irrelevant - the actual implementations are currently returning test strings)...
Import-Module $PSScriptRoot\Convert-DataTable
Import-Module $PSScriptRoot\Get-History
Import-Module $PSScriptRoot\Get-Assets
Import-Module $PSScriptRoot\Write-DataTable

function MyStuff (
    param(
        [string]$serverInstance = "localhost\SQLEXPRESS",
        [string]$database = "PTLPowerShell",
        [string]$tableName = "Test"
    )
    $assets = Get-Assets
    $full_dt = New-Object System.Data.DataTable
    $assets | Start-RSJob -ModulesToImport $PSScriptRoot\Convert-FLToDataTable, $PSScriptRoot\Get-FLHistory {
        $history = Get-History $asset
        $history_dt = Convert-DataTable $history
        return $history_dt.Rows
    } | Wait-RSJob | Receive-RSJob | ForEach {
        $full_dt.Rows.Add($_)
    }
    Write-DataTable $serverInstance $database $tableName $full_dt
}

Here is the Pester test...
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Describe "MyStuff" {
    BeforeEach {
        Mock Get-Assets { return "page1", "page2"}
        Mock Get-History { return "history" }
        Mock Convert-DataTable {
            $historyDT = New-Object System.Data.Datatable;
            $historyDT.TableName = 'Test'
            return ,$historyDT
        }
        Mock Write-DataTable {}
    }
    It "should do something" {
        { MyStuff } | Should -Not -Throw;
    }
    It "should call Get-FLAssetGrid" {
        Assert-MockCalled Get-Assets 1
    }
    It "should call Get-FLHistory" {
        Assert-MockCalled Get-History 2
    }
    It "should call Convert-DataTable" {
        Assert-MockCalled Convert-DataTable 2
    }
    It "should call Write-DataTable" {
        Assert-MockCalled Write-DataTable 1
    }
}

Here is the Pester test's output currently...
Describing MyStuff
  [+] should do something 1.71s
  [+] should call Get-Assets 211ms
  [-] should call Get-History 61ms
    Expected Get-History to be called at least 2 times but was called 0 times
    23:         Assert-MockCalled Get-History 2
    at <ScriptBlock>, myFile.Tests.ps1: line 23
  [-] should call Convert-DataTable 110ms
    Expected Convert-DataTable to be called at least 2 times but was called 0 times
    26:         Assert-MockCalled Convert-DataTable 2
    at <ScriptBlock>, myFile.Tests.ps1: line 26
  [+] should call Write-DataTable 91ms

So ultimately, I'm looking for a way to do parallel operations in PowerShell and still be able to mock and unit test them.

A:

I don't consider this a full answer, and I don't work on the Pester project, but I would say that this is simply not a supported scenario for Pester. This might change when/if concurrent programming becomes part of PowerShell proper (or it may not).
If you're willing to change your implementation you might be able to write around this limitation to support some sort of testing.
For example, maybe your function doesn't use an RSJob when it only has 1 thing to do (which conveniently might be the case when testing).
Or maybe you implement a -Serial or -NoParallel or -SingleRunspace switch (or a -ConcurrencyFactor which you set to 1 in tests), wherein you don't use a runspace for those conditions.
Based on your example it's difficult to tell if that kind of test adequately tests what you want, but it seems like it does.


Q:

How to set the working directory for a  task to something other than the basedir?

I have an Ant script with a junit target where I want it to start up the VM with a different working directory than the basedir. How would I do this?
Here's a pseudo version of my target.
<target name="buildWithClassFiles">
    <mkdir dir="${basedir}/UnitTest/junit-reports"/>
    <junit fork="true" printsummary="yes">
        <classpath>
            <pathelement location="${basedir}/UnitTest/bin"/>
            <path refid="classpath.compile.tests.nojars"/>
        </classpath>
        <jvmarg value="-javaagent:${lib}/jmockit/jmockit.jar=coverage=:html"/>
        <formatter type="xml" />
        <test name="GlobalTests" todir="${basedir}/UnitTest/junit-reports" />
    </junit>

</target>

A:

Have you tried:
 <junit fork="true" printsummary="yes" dir="workingdir">


Q:

Refactoring large code base legacy C++ project that mixed with C style

Background:
Currently I am working on a C++ project. It's for business use, so this project is not open sourced. However, this is a project with a fairly large code base (around 10k lines of code) and a couple of external linked libraries and binaries. The problem is nearly 80% of the code base is written in C style rather than C++ style, but the main interface is written in C++11 standard and needs to be compiled in C++11. One of the most inconvenient parts of the C style code is plenty of goto statement are used, and I can tell the purpose of using goto is to ensure the code is thread safe and clean up the garbage right in time. (They worked) When I first learned C++, I started with C++11, and I think RAII is the modern fashion to replace the hacky style to ensure the code is thread safe and resources being used are cleaned up in time.
Puzzle:
I am assigned to add a series of new functions in the project. Some of my changes have to make in these C style code base. And if I changed one of them, why not refactor all of them in C++1x style? The conflict is given limited time, I can't finish refactoring all of them, not even 80%. And these C style code bases are also using some C style based libraries, I don't know if I changed my code from C style to C++ style, will these external libraries work as before? Will there be equivalent C++ libraries to replace those deprecated C libraries? So my puzzles are: Given limited time, how to refactor large code base legacy C++ project from C style to C++ style effectively? What is the trade off? Is the trade off worth considering?

A:

C code using the goto cleanup style like this:
int function(int argument)
{
  int result;
  opaque_handle handle = NULL;
  char* text = NULL;
  size_t size;

  handle = extlib_create();
  if (!handle) {
    result = extlib_failed;
    goto cleanup;
  }
  size = extlib_size(handle, argument);
  text = malloc(size);
  if (!text) {
    result = oom;
    goto cleanup;
  }
  extlib_read(handle, text, size, argument);
  // etc.

  result = success;
  goto cleanup;

cleanup:
  if (handle) extlib_destroy(handle);
  if (text) free(text);
  return result;
}

can always refactored to C++ by wrapping each resource in a RAII wrapper and perhaps using some exception wrappers.
class extlib_handle {
  opaque_handle handle;
public:
  explicit extlib_handle(opaque_handle handle) : handle(handle) {}
  extlib_handle(const extlib_handle&) = delete;
  extlib_handle& operator =(const extlib_handle&) = delete;
  ~extlib_handle() { extlib_destroy(handle); }
  operator opaque_handle() const { return handle; }
};

template <typename V>
bool resize_nothrow(V& v, typename V::size_type sz)
try {
  v.resize(sz);
  return true;
} catch (std::bad_alloc&) {
  return false;
}

int function(int argument)
{
  extlib_handle handle(extlib_create());
  if (!handle) return extlib_failed;

  size_t size = extlib_size(handle, argument);
  std::vector<char> text;
  if (!resize_nothrow(text, size)) return oom;

  extlib_read(handle, text.data(), size, argument);
  // etc.

  return success;
}

This refactoring does not affect any code outside the function in any way, and allows you to slowly build up a collection of reusable RAII wrappers.
You can use this technique to refactor exactly the parts of the C code you actually touch, not any others. Touching any others introduces unnecessary risks (you could make a mistake and add a bug in code that would otherwise be untouched - this risk is mitigated in the code you have to touch anyway because there could already be new bugs there anyway, so it will receive more attention from testers, and because it makes writing new code less error-prone).
As usual, if you can, write tests. But chances are the code is not amenable to testing because the 3rd party dependencies can't be substituted. Refactoring for that is a time-consuming task.


Q:

How many $3$ digit even numbers can be formed by using digits $1,2,3,4,5,6,7$, if no digits are repeated?

How many $3$ digit even numbers can be formed by using digits $1,2,3,4,5,6,7$, if no digits are repeated?
ATTEMPT
There are three places to be filled in _ _ _
I wrote it like this
_ _ $2$
_ _ $4$
_ _ $6$
Now each of the two blanks can be filled in $P(6,2)$ ways. So adding results of three cases i have $3$. $P(6,2)$ which gives me $90$ ways. But the textbook states $60$ ways. Can someone suggest how ?
Thanks.

A:

For the first digit you only have $3$ possibilities, $2,4$ or $6$. For the second digit, having chosen the first digit you only have $6$ possibilities left. For the third digit, having chosen the first two digit you have $5$ possibilities left. In total you have $3 \times 6 \times 5$ possibilities.


Q:

recursive find number in between in C

I want to find the number within a range in an array and must be in a recursive way. The function variables couldn't be modified.
Let's say in the range of 2 and 3
The input is : int a[] = {4, 1, 3, 1, 3, 2};
and the output will be = {3,3,2} , 3 found
Not sure how to code the recursive function in this case. The below I have tried not working.
int within(int a[], int N, int lower, int upper, int result[])
{
 if(N == 1 && N <= upper && N>= lower)
    return a[0];

 return within(&a[1], N-1, lower, upper, result);
}

int main()
{
    int a[] = {4, 1, 3, 1, 3, 2};
    int result[6] = {0};
    int i, nResult;

    nResult = within(a, 6, 2, 3, result);

    printf("%d data passed the bounds\n", nResult);
    for (i = 0; i < nResult; i++){
        printf("%d ", result[i]);
    }
    printf("\n");

    return 0;
}

A:

I want  to find the number within a range in an array
Let's say in the range of 2 and 3

Normally a for loop or similar would be so much easier here
If it has to be recursive....
// need to have another number - r - number in range
//  r starts at zero
//
// normally lower case for variable and capitals for things you #define
// N starts at the number of elements of a less one
//
int within(int a[], int N, int lower, int upper, int r, int result[])
{
  if(a[0] <= upper && a[0]>= lower) {
     result[r]= a[0];
     r++;
  }
  if(N==0) {
     return r;
  } else {
     r = within(&a[1], N-1, lower, upper, r, result);
    return r;
  }
}

the function will give a return value of the number of values found within the range.
The code above is recursive, but so much more complicated and fragile than a simple loop... such as the fragment below
  for (i=0;i<N;i++) {
    if(a[i] <= upper && a[i]>= lower) {
     result[r]= a[i];
     r++;
    }
  }

If it has to be recursive wihtout r...
// need to have another number - result[0] - number in range
//  result[0] starts at zero
//
// normally lower case for variable and capitals for things you #define
// N starts at the number of elements of a less one
//
int within(int a[], int N, int lower, int upper, int result[])
{
  if(a[0] <= upper && a[0]>= lower) {
     result[0]++;
     result[result[0]]= a[0];
  }
  if(N==0) {
     return result[0];
  } else {
     result[0] = within(&a[1], N-1, lower, upper, result);
    return result[0];
  }
}

now result conatins
{number in range, first number in range, second number in range....}