text:
Q: Word level sentence generation using keras I am new to keras. I am trying to build word level sentence generation module using keras.
I use a vocabulary size of 8000 and one-hot-vector representation of words in my corpus.
This is my model
model = Sequential()
model.add(LSTM(200, return_sequences=False, unroll=True, stateful=False,input_shape=(1,len(itw))  ))
model.add(Activation('tanh'))
model.add(Dense(len(itw)))
model.add(Activation('softmax'))
optimizer = RMSprop(lr=0.01)
model.compile(loss="categorical_crossentropy",optimizer=optimizer,metrics=["accuracy"])
a,b =batch1()
model.fit(a,b,batch_size=45,nb_epoch=5,verbose=1)

here input dimension is 3 (as keras lstm expects 3d input)  input shape such that (batch_size,1,8000). I made the 2nd dimension as 1 because I want to feed word by word.
Batch_size is 45 because that is the avarage length of a sentence in the corpus.
All sentences are pretended with a "START_TOKEN" and appended with a "END_TOKEN".
len(itw) returns length of vocabulary which in my case is 8000
Now after training I wished to loop the generated words back as input until a stop token is encountered to generated a sentence.
But it seems that the model only considers the current input.
I hoped the model to consider the inputs before also and not just the current one.
So how should I change my model
Also is Keras unfit for nlp applications involving varying time serise
How to change the model such that it will generate the next word given n words.
Where n is any natural number


text:
Q: (static initialization/template instantiation) problems with factory pattern Why does following code raise an exception (in createObjects call to map::at)
alternativly the code (and its output) can be viewed here
intererestingly the code works as expected if the commented lines are uncommented with both microsoft and gcc compiler (see here), this even works with initMap as ordinary static variable instead of static getter.
The only reason for this i can think of is that the order of initialization of the static registerHelper_ object (factory_helper_)and the std::map object (initMap) are wrong, however i cant see how that could happen, because the map object is constructed on first usage and thats in factory_helper_ constructor, so everything should be alright shouldnt it ?
I am even more suprised that those doNothing() lines fix the issue, because that call to doNothing() would happen after the critical section (which currently fails) is passed anyway.
EDIT: debugging showed, that without the call to factory_helper_.doNothing(), the constructor of factory_helper_ is never called.
#include <iostream>
#include <string>
#include <map>

#define FACTORY_CLASS(classtype) \
extern const char classtype##_name_[] = #classtype; \
class classtype : FactoryBase<classtype,classtype##_name_>

namespace detail_
{
    class registerHelperBase
    {
    public:
        registerHelperBase(){}
    protected:
        static std::map<std::string, void * (*)(void)>& getInitMap() {
            static std::map<std::string, void * (*)(void)>* initMap = 0;
            if(!initMap)
                initMap= new std::map<std::string, void * (*)(void)>();
            return *initMap;
        }
    };

    template<class TParent, const char* ClassName>
    class registerHelper_ : registerHelperBase {
        static registerHelper_ help_;
    public:
        //void doNothing(){}
        registerHelper_(){
            getInitMap()[std::string(ClassName)]=&TParent::factory_init_;
        }
    };
    template<class TParent, const char* ClassName>
    registerHelper_<TParent,ClassName> registerHelper_<TParent,ClassName>::help_;
}

class Factory : detail_::registerHelperBase
{
private:
    Factory();
public:
    static void* createObject(const std::string& objclassname) {
        return getInitMap().at(objclassname)();
    }
};

template <class TClass, const char* ClassName>
class FactoryBase {
    private:
        static detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName> factory_helper_;
        static void* factory_init_(){ return new TClass();}
    public:
        friend class detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName>;
        FactoryBase(){
            //factory_helper_.doNothing();
        }
        virtual ~FactoryBase(){};
};

template <class TClass, const char* ClassName>
detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName> FactoryBase<TClass,ClassName>::factory_helper_;

FACTORY_CLASS(Test) {
public:
    Test(){}
};

int main(int argc, char** argv) {
    try {
        Test* test = (Test*) Factory::createObject("Test");
    }
    catch(const std::exception& ex) {
        std::cerr << "caught std::exception: "<< ex.what() << std::endl;
    }
    #ifdef _MSC_VER
        system("pause");
    #endif
    return 0;
}

A: The problem is not related to initialization order, but rather to template instantiation.
Templated code is instantiated on demand, that is, the compiler will not instantiate any templated code that is not used in your program. In particular, in your case the static class member FactoryBase<>::factory_helper_ is not being instantiated and thus it does not exist in the final binary, it does not register itself... (you can check this with 'nm' from the gnu toolchain, that will show the list of symbols present in your executable)
Try changing the FactoryBase constructor to this:
template <class TClass, const char* ClassName>
class FactoryBase {
   //...
   FactoryBase(){
      factory_helper_;
   }
   //...
};

This will force the compiler into actually instantiating the static member in the binary and you should be set. There is no need to create an empty method and calling it.
EDIT: As an answer to the comment, towards the end of paragraph §14.7.1[temp.inst]/1 in the current standard:

Unless a member of a class template or
  a member template has been explicitly
  instantiated or explicitly
  specialized, the specialization of the
  member is implicitly instantiated when
  the specialization is referenced in a
  context that requires the member
  definition to exist; in particular,
  the initialization (and any associated
  side-effects) of a static data member
  does not occur unless the static data
  member is itself used in a way that
  requires the definition of the static
  data member to exist.

A: #define FACTORY_CLASS(classtype) \
class classtype; \
extern const char classtype##_name_[] = #classtype; \
template detail_::registerHelper_<FactoryBase<classtype,classtype##_name_>,classtype##_name_> FactoryBase<classtype,classtype##_name_>::factory_helper_; \
class classtype : FactoryBase<classtype,classtype##_name_>

explicitly instantiating factory_helper_ fixed the issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check for ENTER key press in curses. curses.KEY_ENTER not working I am trying to get user input in curses (python), and for some reason it cannot detect when I press the ENTER key.
while True:
        key = stdscr.getkey()
        if key == curses.KEY_ENTER:
            TASK += 1
            break
        elif key.lower() == 'q':
            quit(stdscr)
            break

the if part is not working and the elif part is working fine.

A: curses.KEY_ENTER would be the numeric-keypad Enter key

*

*if curses keypad mode is enabled and

*if the terminal description has the corresponding code and

*if the terminal actually sends what the terminal description says. (Keypad coverage on some terminal emulators is an area for improvement).

It's not related to the Enter key on the main keyboard.
You'll get better results if you add a comparison for \n and \r (this is probably a duplicate).


text:
Q: How to find common neighbours among nodes? I want to return a list of all members and count of their common neighbours with one specific node. So far I get the following:
MATCH (m:Member {name: 'Adam Smith'})-[]->(adamObjects)
MATCH (m2)-[]->(adamObjects)
WHERE m <> m2
RETURN m2.name, COUNT(adamObjects)

However, I am not sure if this is actually returning what I want. Any help is more than welcome!

A: Provided that all :Member nodes are two relationships from each other, and that no other nodes of a different label are exactly two relationships from a :Member node, then your query is returning :Member nodes that are two relationships away from Adam, and the count of the nodes that are in common between them (at one relationship distant, outgoing from both members).


text:
Q: Deleting contents from geodatabase in ArcPy? I have a geodatabase and I would like to be able to delete layers in there easily using ArcPy. Also select which type of files.
Example: delete all file tables from the gdb or all layers.
Code:
env.workspace = r"path.gdb"
for i in arcpy.ListFeatureClasses():
    #how to delete?

A: env.workspace = r"path.gdb"
fc_list = arcpy.ListFeatureClasses()
tables = arcpy.ListTables()
ds_list = arcpy.ListDatasets()

#feature classes
for fc in fc_list:
    arcpy.Delete_management(fc)

#tables
for table in tables:
    arcpy.Delete_management(table)

#data sets
for ds in ds_list:
    arcpy.Delete_management(ds)

There are many options to modify each of list so head to help links to get more info.
Help links:
feature clases - http://pro.arcgis.com/en/pro-app/arcpy/functions/listfeatureclasses.htm
tables - http://pro.arcgis.com/en/pro-app/arcpy/functions/listtables.htm
data sets  - http://pro.arcgis.com/en/pro-app/arcpy/functions/listdatasets.htm
delete - http://pro.arcgis.com/en/pro-app/tool-reference/data-management/delete.htm


text:
Q: making one computers bash prompt match anothers The computer who's prompt I'm trying to copy:
[root@CompanyName-LAMP-DEV:/current/path]$

We'll call that computer computer A.
The prompt my computer - computer B - currently has:
[root@ip-x-x-x-x /current/path]#

Both are using bash.  I copied the /etc/bashrc file from computer A to computer B, to no avail.  If I do echo $HOSTNAME, both are of the form ip-x-x-x-x.
Any ideas?

A: Prompts are set by environment variables in bash including PS1 and PS2. If the variables are defined in the configuration files you copied over make sure you have sourced them with the dot command (. .profile) or logout and login to make sure they are reloaded.
You can check their values with shell commands like: echo PS1="$PS1" PS2="$PS2".
Ref: http://tldp.org/HOWTO/Bash-Prompt-HOWTO/setps.html

A: The prompt is in the $PS1 environmental variable (which will be set in /etc/bashrc, or ~/.bashrc).  Do a echo $PS1 on either machine, compare and constrast.


text:
Q: Rendering html string to canvas without showing the html itself I would like to convert an html string to image similar to how it's done here:
html2canvas creates a canvas with a width and height of zero?
However I don't want to show anything other than result image on the page. Thus I can't simply add the html string to the DOM as suggested there. I assume what I'm trying to achieve is possible because html2canvas test console does just that.
I tried the following which produces empty result:

var doc = document.implementation.createHTMLDocument();
doc.open();
doc.write("
test
");
doc.close();

html2canvas(doc.body, {
    onrendered:function(newCanvas) {
        document.body.appendChild(newCanvas);
    }
});

Can anyone suggest the way of doing this?

A: I figured that out. Here is the link which headed me to the right direction. It is also worth checking the source code of this page which illustrates the idea.
We set the
style="overflow:hidden"

attribute for the container and move the contents we want to render outside of the viewport with
style="position:absolute;top:0px;left:3000px;"

Hope that helps someone.


text:
Q: What are the safe limits of the Ant-Man suit? Typically, Ant-Man shrinks to roughly the size of an ant (I bet you never guessed that!) for most of his adventures. We learn in the movie that the Ant-Man suit can only safely shrink so far due to its regulator device. This is to prevent the user from becoming too small and entering the "Quantum Realm" (or Microverse in the comics).
What is the safe size/scale limit before he risks danger of falling into the Quantum Realm?

A: tl;dr: As far as the MCU is concerned, the science in Ant-Man is both vague and contradictory enough that we can't really answer this question any better than what you already said.

The movie is rather vague about just how small Scott can get before it becomes problematic. I assume this is intentional, since any attempt to be specific would just invite criticism of the science :)
However, within the limited experience of the single movie thus far, it looks like the suit is already set up shrink Scott as small as he can safely get: about the size of an ant. We never see Scott use the suit to shrink to any other size -- nothing smaller or bigger than the one fixed size. The only time he tries to go smaller, he is forced to disable the "regulator" to make it happen.
Of course, it's possible (even likely) that the regulator is set a bit conservatively, for safety reasons. So we don't know how much smaller Scott could get before it would be unable to recover. However, note that both times the issue comes up, the same phrase is used:

shrink between the molecules

This would imply that the suit cannot safely shrink smaller than the molecular level. That's a vague definition, because molecules come in a huge range of sizes. However, going "between the molecules" of a solid metal would most likely mean shrinking down to nearly the size of individual atoms.
Unfortunately, this isn't really what Scott

 and Janet

does when he tries it; he simply shrinks small enough to fit

 through a seam between two sheets of titanium in the YellowJack suit.

Once there, he's still clearly much bigger than molecular level, since we can see him being the size of typical electronic components -- which are often bigger than ants in the first place.
So, the ultimate conclusion is: the movie gets the molecular-level science pretty badly wrong, so there's no way of knowing exactly what size a person has to reach before the end up "going quantum".


text:
Q: Airflow webserver not starting-UnicodeDecode error Im attempting to set up airflow on my mac.I got the basic setup up and running.I was able to create a DAG and schedule it.
All of a sudden I started getting the following error when I start the server:
File "/Users/xxx/Library/Python/2.7/lib/python/site-packages/airflow/www/templates/airflow/traceback.html", line 27, in top-level template code
{{ nukular }}Node: {{ hostname }}

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 6: ordinal not in range(128)

Im not sure how to debug this.The server refuses to start.
Thanks!


text:
Q: How to make the h1 tag responsive to the background image (along with the background, the h1 tags shrinks & expand) I have a background image in the jumbotron along with h1 tags. As I resize the image, the h1 tags do not resize, and overlap with the image in the background

.jumbotron h1 {
  font-size: 45px;
}
.jumbotron {
  background-image: url("header.jpg");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  margin-bottom: 0px;
  padding-top: 20px;
  padding-left: 48px;
  padding-right: 48px;
}

 Hello, how May I help you.

Happy to help you

A: You will have to use javascript to shrink the font-size with the jumbotron.
If you are currently resizing the whole window to shrink the image, then you can just add the following:
window.addEventListener('resize', function() {

    var h1 = document.getElementById("jumbo-h1");  //I made up an id for simplicity
    var width = document.getElementsByClassName("jumbotron")[0].offsetWidth;

    if (width > 600) {
       h1.style['font-size'] = "45px";
    } else if (width > 400 && width <= 600) {
       h1.style['font-size'] = "35px";
    } else {
       h1.style['font-size'] = "25px";
    }
}

if you are using jQuery, this becomes much cleaner:
$(window).on('resize',function(){
    var $h1 = $(".jumbotron h1");         //note that ID is not needed
    var width = $(".jumbotron").width();
    if (width > 600) {
        $h1.css({"font-size": "45px"});
    } else is (width > 400 && width <= 600) {
        $h1.css({"font-size": "35px"});
    } else {
        $h1.css({"font-size": "25px"});
    }
});

Obviously, play with the sizes/cutoff points to your hearts content to get the look you are after.
If you are resizing the jumbotron in other ways, simply move the code in the handler I provided into its own function and call that when needed (while also passing a reference to the window resize handler)

A: I have two demos on Codepen that explore the concept of scaling text.
http://codepen.io/denmch/pen/MYZqXB
http://codepen.io/denmch/pen/EaGMYZ/
You can check the CSS and play with the concept on your own, but the basic idea is to calculate the font size using a combination of normal measures (em, rem, px…) and vw (viewport width-based measurement), which will produce a proportional text size that responds to the viewport. Here's an example:
h1 {
  font-size: calc(1rem + 3.5vw);
}

This idea has also been explored by Mike Riethmuller who has done a lot of great work and even apparently has videos on the subject.
It's considered experimental, but you should be good everywhere but Opera Mini.


text:
Q: How to use a (random) *.otf or *.ttf font in matplotlib? How can I use any type of font in my font library on my computer (e.g. *otf or *ttf) in all my matplotlib figures?

A: See the example here: http://matplotlib.sourceforge.net/examples/api/font_file.html
In general, you'd do something like this if you're wanting to use a specific .ttf file. (Keep in mind that pointing to a specific font file is usually a bad idea!)
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

prop = fm.FontProperties(fname='/usr/share/fonts/truetype/groovygh.ttf')
ax.set_title('This is some random font', fontproperties=prop, size=32)

plt.show()

Usually, you'd just point to the name of the font, and let matplotlib worry about finding the specific file. E.g.
import matplotlib.pyplot as plt

plt.plot(range(10))
plt.title('This is some random font', family='GroovyGhosties', size=32)

plt.show()

If you want to have matplotlib always use a particular font, then customize your .matplotlibrc file. (font.family is what you'd want to set. Note that you should specify the name of the font, not the path to a specific .ttf file.)
As an example of doing this dynamically (i.e. without setting up a specific .matplotlibrc file):
import matplotlib as mpl
mpl.rcParams['font.family'] = 'GroovyGhosties'

import matplotlib.pyplot as plt

plt.plot(range(10))
plt.title('Everything is crazy!!!', size=32)
plt.show()

A: On *nix, you can use all your system fonts by enabling matplotlib's fontconfig backend.
However matplotlib does not really talk to fontconfig libraries it emulates its behaviour by running fontconfig cli utilities.
Therefore, nuking the matplotlib fontconfig cache so it discovers new fonts can be a lifesaver (the existence of this cache is direct proof of lack of complete fontconfig integration).

A: You can specify the font and override the default font family in matplot config as well, e.g. for *nix
~/.matplotlib/matplotlibrc
font.family: sans-serif
font.sans-serif: your font,sans-serif


text:
Q: How to fix long .zshrc PATH to avoid command not found errors? My main problem is that I am getting the error zsh: command not found $ when I run $ gulp serve. This is after installing a Yeoman webapp generator.
I've checked these other sources:

*

*commands not found on zsh'

*zsh command not found issue

*Command not found - Oh-My-Zsh

*How to specify a custom path for my .zshrc file?

*zsh: command not found: modernizr
I'm not sure which one is most relevant to me. It seems like most of the issues people have are caused by the PATH being messed up. I also believe my issue is with my PATH. When I run echo $PATH, this is what I get:

echo $PATH
  /usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/thisisme/.rvm/gems/ruby-2.2.1/bin:/Users/thisisme/.rvm/gems/ruby-2.2.1@global/bin:/Users/thisisme/.rvm/rubies/ruby-2.2.1/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/X11/bin:/usr/local/mysql/bin:/Users/thisisme/.rvm/bin:/Users/thisisme/.rvm/gems/ruby-2.2.1/bin:/Users/thisisme/.rvm/gems/ruby-2.2.1@global/bin:/Users/thisisme/.rvm/rubies/ruby-2.2.1/bin:/usr/local/bin:/usr/local/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/mysql/bin:/usr/local/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/mysql/bin:/Users/thisisme/.rvm/bin:/Users/thisisme/.rvm/bin

When I look in my ~/.zshrc file, I get
export PATH=$PATH:"/Users/thisisme/.rvm/gems/ruby-2.2.1/bin:/Users/thisisme/.rvm/gems/ruby-2.2.1@global/bin:/Users/thisisme/.rvm/rubies/ruby-2.2.1/

and so on... (It goes on and on from there, but hopefully you get the idea.) One of these answers suggested using exec zsh -1; now I get
$ gulp serve
zsh: command not found: $
[1]    34254 exit 127   $ gulp serve

My user PATH looks kind of crazy. I have Python and Ruby installed because I installed Jekyll in the past but I don't use them often.
It's been a while since I used Terminal, but I wrote myself this note to use rvm reinstall 2.1.4. Unfortunately, I got an error Error: /usr/local/opt/makedepend not present or broken
Please reinstall makedepend. Sorry :(. So, this is another problem that I am not sure is necessary to fix this problem. But I tried it, so I'm including it.
If anyone has tips on where to look or how to help, preferably some place with instructions with steps because I'm still learning, that would be very helpful.
Edit: The answer was that the generator did not install gulp when it built out the scaffolding for the webapp.

A: Dumb question maybe, but are you actually typing the $ in your shell? This would explain zsh: command not found $. Is it a typo or do you have an opening " at PATH=$PATH" and no closing "? I think you actually don't need "".


text:
Q: calling an async method inside a non-async method I have a class that i'm inheriting from, and i have NO access to the base class.  I'm overriding a method of that base class, and this method is not async, but i need it to call an async method i've created.  Like so:
public class OverridingClass : BaseClass
{
    public override bool TestMethod()
    {
        var res = engine.DoAsyncFunction().Result;
        //do stuff with res value
    }
}

is it better to use this method, where i take out the 'result' value, or should i add a new, synchronous method to the engine instead and ignore it's async function entirely, like so?
public class OverridingClass : BaseClass
{
    public override bool TestMethod()
    {
        var res = engine.DoFunction();
        //do stuff with res value
    }
}

or is there something else i can do entirely to the overridden function to make it async?  If i try to make the overridden method:
public async override Task<bool> TestMethod()...

then i will get a compile error saying that the method doesn't match the base signature.

A: You can wrap it in a Task.Run() like following, if you want it to be called asynchrounously:
public override bool TestMethod()
{
    var task = Task.Run(async () => {

       return await engine.DoAsyncFunction();

    });

   var Result = task.Result; // use returned result from async method here
}


text:
Q: (AUTOIT) Au3Recoder failing to launch in Win7 64bit I'm trying to automate few software installations. I came to know about AutoIt Au3Recoder, but its failing to launch in Win7 64bit. It through me an error message while launching
"MSVCR100.dll Not Found"

I tried with downloading the same .dll file and adding into system32 and C:\Windows\SysWOW64 folder but still I'm facing the same.
(Either I should resolve this or I should go with some other software, If you know any other software please suggest me)

A: Just install the following package and this error should be gone:
http://www.microsoft.com/en-us/download/details.aspx?id=14632


text:
Q: Multi threading for reading CSV Files in Julia Is there a way to implement multi-threading on CSV.read in Julia? A good example to read big files has been presented in Parallelism for reading a large file in Julia.
But since I have to frequently change my datasets these approaches may not be applicable.
using CSV
file = ("C:\\Users\\User\\Desktop\\Datasets\\X_train_sat4.csv")
@time df = CSV.read(file, DataFrame)

Output:
69.469112 seconds (6.29 M allocations: 9.767 GiB, 0.76% gc time)
29723 rows × 2456 columns

I have used the steps recommended here Speed up loading and compilation time but these improves only the first loading time.
Thanks in advance!

A: CSV.jl supports multi-threading. You can select how many threads you want to use with tasks keyword argument. You cannot use more than number of threads that your Julia process was started with.
Here is a sample timing on reading a file having 10^8 rows and 10 columns:
julia> @time CSV.read("test.csv", DataFrame, ntasks=1); # one thread
 75.190387 seconds (23.24 M allocations: 9.253 GiB, 1.24% gc time)

julia> @time CSV.read("test.csv", DataFrame, ntasks=2); # two threads
 43.078513 seconds (4.34 M allocations: 8.044 GiB, 2.30% gc time)

By default number of tasks used is set to Threads.nthreads().


text:
Q: What is the issue in my code? I am working on an application in which I am using a frame layout. In the frame layout there are three classes as follows:

*

*creating image

*checking the pixel of the image the user touches

*drawing the image

But when I am touching on the same color, it is giving me a different color value. If anyone wants to see my code then it is there. If you want to check which image is used by me then the images are as follows:

the second image which is used for getting the pixel:

Can any one tell me why it is not giving me correct value of the color on touch on the image
?
Edited1
my edited code of the imagein class is as follow [code after editing4

A: My guess is that you are making assumptions based on the the pixel coordinates of the image, and not translating the coordinates as they exist once Android resizes your art.  You should see what Android thinks the image size is, after it's drawn to your View and make sure that the spot you're touching is the same spot that you're expecting to be touching.


text:
Q: Dual-axis Inclinometer Im working on a project where im designing a device that can be worn on the arm (using the elbow as the fixed angle). Once the device measures 45 degrees I want to program it to vibrate. My question is how can I integrate a dual-axis inclinometer to measure two axis instead of a tilt sensor that only measures one. What else do I use along with the inclinometer to make it operate? Also would i still need a comparator, voltage regulator, npn mosfet? Can I add a usb rechargeable battery?disclaimer I am not an electrical engineer. If there is any more information I can add let me know.

A: Much depends of the actual sensor you select.  Some sensors will output an analog voltage which may require additional circuitry, (or require an analog I/O port on a micro-controller).  Other sensor modules may have most of the circuitry included and may even have a simple digital output.
If you research available sensors the manufacturer may have data sheets or application sheets that gives a typical schematic, extra circuitry, interface components, or software that may be required to use the device.
Analog examples:
http://www.analog.com/media/en/reference-design-documentation/reference-designs/CN0189.pdf
http://www.meas-spec.com/downloads/E2-Series.pdf
USB example:
http://www.meas-spec.com/product/Position/DOG2-MEMS-Series-USB.aspx
RS232 example:
http://www.leveldevelopments.com/wp/wp-content/uploads/documents/LCH-45_Inclinometer_Sensor.pdf
Alternately have you considered just using two simple single axis tilt sensors?  Two simple digital inputs might be all that is required for a simple interface.
Lastly, be sure you want a inclinometer and not an accelerometer.  The first may only measure a changing angular position (eg.: a slowly moving arm), while the other can measure fast motion/acceleration and possibly multiple directions (eg.: a fast swinging arm).


text:
Q: Create gradle friendly project structure for android im learning android development and at the moment i want to start using the sdk through the command line, at the moment i dont want to use android studio  im following the tutorial at 'developers.android.com' on how to create my first application i used the command 'android create project..' and everthing was fine, until i reached the part where i had to run the app using gradle, i downloaded gradle and when i was building my project using 'gradle assembleDebug' and it gave me this error 'task assembleDebug not found in root project', i read about other people asking similar questions here at stackoverflow, but my question is how can i create a gradle friendly structure using the command line and not using android studio thx in advance
jrod

A: If you are following the official tutorial, you are using this command:
android create project --target <target-id> --name MyFirstApp \
--path <path-to-workspace>/MyFirstApp --activity MyActivity \
--package com.example.myfirstapp

This comand creates your project with the structure used by Eclipse/Adt Bundle.
To use gradle, you have to create your project with a gradle structure.
In accordace with this answer, you have to create your project with a command like this:
android create project -a Main -k com.example.app -t 19 -g -v 0.10 \
-p AppWithGradleTemplate

After that, you will see that your project has the files gradlew and gradlew.bat. Then, you can run:
Linux/Mac
chmod +x gradlew
./gradlew assembleDebug

Windows:
gradlew.bat assembleDebug

A: Probably the easiest thing to do is to create a simple starter project in Android Studio, and then study the structure of that project.
One of the things that you will notice is that there's a 'top level' to the project, and then an 'app level' below that. This allows for multi-module projects.
There's are gradle build files at both levels. You will typically build from the top level. There's also typically 'gradlew' file at the top level, that invokes the build process, using a local gradle installation in the 'gradle' directory of the project.

A: This article will help you to get started
http://tools.android.com/tech-docs/new-build-system/user-guide
You should also checkout the Google IO 2013 Talk on the new android build system (it was new back then). Here's the link https://www.youtube.com/watch?v=LCJAgPkpmR0
However if you want to see some samples, I have some starter projects. There you go:
https://github.com/mushfek0001/javafest-gradle-webiner/tree/master/currency-converter
https://github.com/mushfek0001/javafest-gradle-webiner/tree/master/currency-converter-modular
https://github.com/mushfek0001/javafest-gradle-webiner/tree/master/AndroidComplexBuild


text:
Q: ThreeJS ColorMaps (LookUpTables -- LUTs) I'm converting a project from canvas2D to webgl/webgl2, and looking at using ThreeJS.
One issue is using colormaps. I typically use a 256 colormap, thus colors are Uint8 Attribute arrays as indexes into a Uniform colormap: an array of 256 colors.
This requires the Vertex shader to convert the Uint8 color Attribute (the 1 byte index into the Uniform array of colors) into a Varying color to be passed to the Frag shader which then uses it for the color.
How do I do this in Three? Or possibly I should a different 3D library (https://twgljs.org/, say)
More generally, I need to understand how to integrate or create extensions for three.js. Any docs or help of any sort? The three.js site does not, I think, include this.


text:
Q: Finding the related FK property of a Navigation Property At run time I would like to find whether an EntityObject also has a foreign key property for a given NavigationProperty. I have this in two steps below. I imagine this is going to require some metadata querying.
I am unsure how to test whether a metadata class points to the type of a particular EntityObject type: ie I know conceptually but not programmically the relationship between an EntityType instance and an EntityObject instance.
So far I have:
    /*puesdo code class representing edm example*/
    class Possesion: EntityObject
    {

        //Nav prop
        public Person Owner { get; set; }

        //related FK prop
        public int OwnerId { get; set; }

    }

    public static NavigationProperty GetNavigationProperty<TObjectContext, T>(
        this ObjectContext context,
        Expression<Func<T, Object>> targetProperty)
        where TObjectContext : ObjectContext
    {
        //eg: possession => possession.Owner  property type would be person
        PropertyInfo targetProp = GetPropertyType(targetProperty);
        //target type would be Possesion
        Type targetType = targetProp.DeclaringType;

        var containerName = context.DefaultContainerName;
        var model = DataSpace.CSpace;
        var workspace = context.MetadataWorkspace;
        var container = workspace.GetEntityContainer(containerName, model);

        EntitySetBase entitySet = container.BaseEntitySets
            .Where(e => e.Name == context.GetEntitySetNameFromType(targetType))
            .FirstOrDefault();

        if (entitySet == null)
            return null;

        //materialize nav props for testing
        var navigationProps = entitySet.ElementType.Members
            .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.NavigationProperty
            )
            .Cast<NavigationProperty>()
            .ToList();

        //The question: how to filter the nav props for that which pertains
        // to the target property?
        NavigationProperty navProp = navigationProps
            .Where(
            //how do we select the nav property based on the Passed EntityObject's type
            //ie how to we link the Metadata type to the concrete type??
            n => n.FromEndMember.TypeUsage.???????? == targetProp.PropertyType)
            .FirstOrDefault();

        return navProp;
    }

    public static String GetPossibleFKPropertyName(Type entityObjectType, NavigationProperty property)
    {
        //Check each end for the target type
        //with this end ie To or From, determine if there is a Property on the entityObject that equated to the PropertyRef column
        //return this.

        var toEnd = property.ToEndMember.GetEntityType();
        //Again how do I determine that the Person metadata is a Person EntityObjectType?
        if (toEnd.SomeTypeMember???? == entityObjectType)
            return toEnd.KeyMembers[0].Name; //Testing HACK, return name for now.

        var fromEnd = property.FromEndMember.GetEntityType();
        if (fromEnd.SomeTypeMember???? == entityObjectType)
            return fromEnd.KeyMembers[0].Name;

        return "";

    }

A: I ended up simply doing a text comparison on the FullName of the ElementType
ie:
n =>((RefType)n.ToEndMember.TypeUsage.EdmType).ElementType.FullName
                               == targetProp.PropertyType.FullName)

also the ToEnd being the property I am targeting then once I had the NavigationProperty, calling GetDependentProperties() seems to yield what I am after being the FK property name ie:
    public static String GetFKPropertyName(this NavigationProperty property)
    {
        var depProp = property.GetDependentProperties().FirstOrDefault();

        if (depProp == null)
            return "";

        return depProp.Name;

    }


text:
Q: Why is Joda Time serialized form so large, and what to do about it? On my machine, the following code snippet:
DateTime now = DateTime.now();
System.out.println(now);
System.out.println("Date size:\t\t"+serialiseToArray(now).length);
System.out.println("DateString size:\t"+serialiseToArray(now.toString()).length);
System.out.println("java.util.Date size:\t"+serialiseToArray(new Date()).length);
Duration twoHours = Duration.standardHours(2);
System.out.println(twoHours);
System.out.println("Duration size:\t\t"+serialiseToArray(twoHours).length);
System.out.println("DurationString size:\t"+serialiseToArray(twoHours.toString()).length);

Gives the following output:
2013-09-09T15:07:44.642+01:00
Date size:      273
DateString size:    36
java.util.Date size:    46
PT7200S
Duration size:      107
DurationString size:    14

As you can see, the org.joda.time.DateTime object is more than 5 times larger than its String form, which seems to describe it perfectly, and the java.util.Date equivalent. The Duration object representing 2 hours is also much larger than I would expect, as looking at the source it seems like its only member variable is a single long value.
Why are these serialized objects so large? And is there any pre-existing solution for getting a smaller representation?
The serialiseToArray method, for reference:
private static byte[] serialiseToArray(Serializable s)
{
    try
    {
        ByteArrayOutputStream byteArrayBuffer = new ByteArrayOutputStream();
        new ObjectOutputStream(byteArrayBuffer).writeObject(s);
        return byteArrayBuffer.toByteArray();
    }
    catch (IOException ex)
    {
        throw new RuntimeException(ex);
    }
}

A: Serializing has some overhead. In this instance the overhead that you notice the most is that the class structure is described in the actual output. And since Duration has a base class (BaseDuration) and two interfaces (ReadableDuration and Serializable), that overhead becomes slightly larger than the one of Date (which has no base class and just a single interface).
Those classes are referenced using their fully-qualified class names in the serialized file and as such create quite some bytes.
Good news: that overhead is only paid once per output stream. If you serialize another Duration object, the difference in size should be rather small.
I've used the jdeserialize project to look in the result of serializing a java.util.Date vs. a Duration (note that this tool does not need access to the .class files, so all information it dumps is actually contained in the serialized data):
The result for java.util.Date:

read: java.util.Date _h0x7e0001 = r_0x7e0000;
//// BEGIN stream content output
java.util.Date _h0x7e0001 = r_0x7e0000;
//// END stream content output

//// BEGIN class declarations (excluding array classes)
class java.util.Date implements java.io.Serializable {
}

//// END class declarations

//// BEGIN instance dump
[instance 0x7e0001: 0x7e0000/java.util.Date
  object annotations:
    java.util.Date
        [blockdata 0x00: 8 bytes]

  field data:
    0x7e0000/java.util.Date:
]
//// END instance dump

The result for Duration:

read: org.joda.time.Duration _h0x7e0002 = r_0x7e0000;
//// BEGIN stream content output
org.joda.time.Duration _h0x7e0002 = r_0x7e0000;
//// END stream content output

//// BEGIN class declarations (excluding array classes)
class org.joda.time.Duration extends org.joda.time.base.BaseDuration implements java.io.Serializable {
}

class org.joda.time.base.BaseDuration implements java.io.Serializable {
    long iMillis;
}

//// END class declarations

//// BEGIN instance dump
[instance 0x7e0002: 0x7e0000/org.joda.time.Duration
  field data:
    0x7e0001/org.joda.time.base.BaseDuration:
        iMillis: 0
    0x7e0000/org.joda.time.Duration:
]
//// END instance dump

Note that the "class declaration" block is quite a bit longer for Duration. This also explains why serializing a single Duration takes 107 bytes, but serializing two (distinct) Duration objects takes only 121 bytes.

A: From the source:

Internally, the class holds two pieces of data. Firstly, it holds the
  datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z.
  Secondly, it holds a Chronology which determines how the millisecond
  instant value is converted into the date time fields. The default
  Chronology is org.joda.time.chrono.ISOChronology which is the agreed
  international standard and compatible with the modern Gregorian
  calendar.

The ISOChronology derives from AssembledChronology, most of which (but not all) is declared as transient fields.


text:
Q: compatibility with modern motherboards? (ATX 12V vs EPS 12V) I have the Seasonic S12-600 in my current PC, which I'm thinking of upgrading from its ageing s939 Athlon CPU to a Core i5-based system.
My question is whether or not my PSU is compatible with modern motherboards? For example, this P55 Gigabyte board has:

*

*1 x 24-pin ATX main power connector

*1 x 8-pin ATX 12V power connector

The datasheet for the S12-600 suggests it has the 24-pin ATX main power connector, but it has a 4-pin ATX 12V power connector and an 8-pin EPS 12V power connector.
Will I be able to use my existing PSU to power this board, or am I going to have to replace it?
I've seen discussion (e.g. on Tom's hardware) that an EPS 12V cable can be used with an ATX 12V power connector, is that right?
Many thanks for any and all help!
UPDATE: Reading around more, I've come to the conclusion that the connector is pin and voltage compatible with the socket on the board. I was confused by the 8-pin connector being called an EPS 12V. I took that to mean it wasn't compatible with ATX, as opposed to what it actually means (which is that its inclusion is in accordance with the EPS standard).
A nice summary of the PSU/motherboard compatibility can be found here.
I'm going to accept Wil's answer, since it provides the same conclusion that I've come to independently.

A: From that specification sheet, it should be compatible with any modern computer on the market.
It has many outputs and then some... Seems fine by me.


text:
Q: Extension of function with values in a Banach space I want to prove the following

Let $E,X$ be Banach spaces, and $Y\subset E$ a closed subspace with codimension $1$. Let $T:Y \to X$ be a continuous linear function. Then there exists a continuous linear extension  $\bar{T}$ of $T$ defined on $E$

my attempt: Let's say that $E=Y \oplus \mathbb{R}e$, for some $e \in E\setminus{Y}$. Define for $r \in \mathbb{R} $  and $y \in Y$
$$
\bar{T}(y+re):=T(y)
$$
so I tried to prove that
$$
\sup_{x \in B_E} \|\bar{T}(x)\|=\sup_{\|y+re\|\leq 1} \|T(y)\|< \infty
$$
I'd like to say something like this: There exists $M>0$ such that
$$
\|y+re\|\leq 1\, \text{for some $r\in \mathbb{R}$}\Longrightarrow \|y\|\leq M
$$
which, I suppose, comes from the fact that $Y$ is closed. If I had that, I could say the following
$$
\sup_{\|y+re\|\leq 1} \|T(y)\|\leq \sup_{\|y\|\leq M}\|T(y)\|
$$
and conclude the proof. Any hint would be welcome.
Thanks in advanced.


text:
Q: iOS User preferences saving and updating I think this question is going to be very difficult to ask so bear with me and if it doesn't make sense, just let me know.
I will start by explaining the situation and then show some code. So I have an app that has an array of "default" settings to display on a user's dashboard.  The user can modify these settings to enable or disable certain items that appear on their dashboard.
I want to be able to update the "default" settings and if I add a new item then it will automatically update the user's settings as well, but without overwriting their personal enable/disable setting.
So I have this array of dictionaries, the "default":
dashboardItems = @[
                   @{
                       @"id" : @"1",
                       @"order" : @"0",
                       @"title" : @"Steps Traveled",
                       @"unit" : @"",
                       @"type" : HKQuantityTypeIdentifierStepCount,
                       @"sampleUnit" : @"count",
                       @"enabled" : @"1"
                   },
                   @{
                       @"id" : @"2",
                       @"order" : @"1",
                       @"title" : @"Flights Climbed",
                       @"unit" : @"",
                       @"type" : HKQuantityTypeIdentifierFlightsClimbed,
                       @"sampleUnit" : @"count",
                       @"enabled" : @"1"
                   },
                   @{
                       @"id" : @"3",
                       @"order" : @"2",
                       @"title" : @"Distance Traveled",
                       @"unit" : @"mi",
                       @"type" : HKQuantityTypeIdentifierDistanceWalkingRunning,
                       @"sampleUnit" : @"mi",
                       @"enabled" : @"1"
                   },
                   @{
                       @"id" : @"4",
                       @"order" : @"3",
                       @"title" : @"Active Calories",
                       @"unit" : @"",
                       @"type" : HKQuantityTypeIdentifierActiveEnergyBurned,
                       @"sampleUnit" : @"kcal",
                       @"enabled" : @"1"
                   },
                   @{
                       @"id" : @"5",
                       @"order" : @"4",
                       @"title" : @"Weight",
                       @"unit" : @"lbs",
                       @"type" : HKQuantityTypeIdentifierBodyMass,
                       @"sampleUnit" : @"lb",
                       @"enabled" : @"1"
                   },
                   @{
                       @"id" : @"6",
                       @"order" : @"5",
                       @"title" : @"Cycling",
                       @"unit" : @"mi",
                       @"type" : HKQuantityTypeIdentifierDistanceCycling,
                       @"sampleUnit" : @"mi",
                       @"enabled" : @"1"
                   },
                   @{
                       @"id" : @"7",
                       @"order" : @"6",
                       @"title" : @"Heart Rate",
                       @"unit" : @"BPM",
                       @"type" : HKQuantityTypeIdentifierHeartRate,
                       @"sampleUnit" : @"count/min",
                       @"enabled" : @"1"
                   },
                   @{
                       @"id" : @"8",
                       @"order" : @"7",
                       @"title" : @"BMI",
                       @"unit" : @"",
                       @"type" : HKQuantityTypeIdentifierBodyMassIndex,
                       @"sampleUnit" : @"count",
                       @"enabled" : @"1"
                   }
        ];

So the user can use a switch to change the enabled from a 1 to a 0 or vice-versa to turn on or off the item, with me so far?
When the user signs up the app saves the "default" settings to NSUserDefaults and also to the live server to back up in case the user ever deletes the app.
If the user logs out or deletes the app, on next login we check to see if they currently have and NSUserDefaults saved, if not we pull from the server.
Then I compare the 2 arrays to see if any items were changed or added to the "defaults", is this the best way to go about doing it?
//here we need to check if the user does not have any preferences saved, if not pull them from Parse.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSMutableArray *dashboardItems = [defaults objectForKey:@"dashboardItems"];

if (dashboardItems == nil) {

    //user has no preferences so load them in
    dashboardItems = [NSJSONSerialization JSONObjectWithData:[user[@"preferences"] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

    [defaults setObject:dashboardItems forKey:@"dashboardItems"];
    [defaults synchronize];

}

//compare current preferences against default to see if any new items were changed
NSArray *defaultPreferences = [[PreferencesManager sharedManager] dashboardItems];

for (NSDictionary *item in defaultPreferences) {

    for (NSDictionary *userItem in dashboardItems) {

        if ([item[@"id"] isEqualToString:userItem[@"id"]]) {

            //we have a match, compare name and change if necessary
            if (![item[@"title"] isEqualToString:userItem[@"title"]]) {

                //set user's item title to default title
                [userItem setValue:item[@"title"] forKey:@"title"];

            }

        } else {

            //we did not find this in user preferences, so add it
            [dashboardItems addObject:item];

        }

    }

}

//save defaults
[defaults setObject:dashboardItems forKey:@"dashboardItems"];
[defaults synchronize];

If I need to clarify anything further, please just let me know.
Thanks!

A: I would start by getting all default settings, then replace those that has a match in the stored user settings:
NSMutableArray *defaultSettings = [@[] mutableCopy];
NSArray *userSettings = @[];
for (NSInteger i = 0; i < defaultSettings.count; i++) {
    NSDictionary *setting = defaultSettings[i];
    NSInteger index = [userSettings indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        NSDictionary *userSetting = obj;
        *stop = [setting[@"title"] isEqualToString:userSetting[@"title"]];
        return *stop;
    }];
    if (index != NSNotFound) {
        // Found matching setting
        defaultSettings[i] = userSettings[index];
    }
}

[defaults setObject:defaultSettings forKey:@"defaultSettings"];
[defaults synchronize];

But if I were you, I'd use a NSDictionary of NSDictionary, and use the key as the ID.  It would made the same process a lot easier:
NSDictionary *defaultSettings = @{
                                  @"1": @{@"order": @"0", @"title": @"Steps traveled", @"enabled": @"0"},
                                  @"2": @{@"order": @"1", @"title": @"Flights Climbed", @"enabled": @"0"},
                                  @"3": @{@"order": @"2", @"title": @"Distance Traveled", @"enabled": @"0"}
                                  };
NSMutableDictionary *mutableDefaultSettings = [defaultSettings mutableCopy];
NSDictionary *userSettings = @{
                               @"2": @{@"order": @"1", @"title": @"Flights Climbed", @"enabled": @"1"}
                               };

for (NSString *id in userSettings.allKeys) {
    mutableDefaultSettings[id] = userSettings[id];
}

[defaults setObject:mutableDefaultSettings forKey:@"dashboardItems"];
[defaults synchronize];


text:
Q: Adding factors to an mle2 model As a reproducible example please see the following code:
set.seed(1)
TDT <- data.table(Country = c(rep("A",30),rep("B",50), rep("C",20)),
                      Id = c(rep(1,20),rep(2,20),rep(3,20),rep(4,20),rep(5,20)),
                      Time = rep(seq(as.Date("2010-01-03"), length=20, by="1 month") - 1,5),
                      Country = c(rep("Albania",30),rep("Belarus",50), rep("Chilipepper",20)),
                      norm = round(runif(100)/10,2),
                      Income = sample(100,100),
                      Happiness = sample(10,10),
                      Sex = round(rnorm(10,0.75,0.3),2),
                      Age = round(rnorm(10,0.75,0.3),2),
                      Educ = round(rnorm(10,0.75,0.3),2))
TDT [, ID := .I]
TDT$Country <- as.factor(TDT$Country)
#################################################################################################
start_rho <- c(1,1.2,1.4,1.6,1.8,2)
mu_Happiness <- mean(TDT$Happiness, na.rm=TRUE)
sd_Happiness <- sd(TDT$Happiness, na.rm=TRUE)

LL4 <- function(p, a, mu, sigma) {
  -sum(dnorm(TDT$Happiness - a*((TDT$Income^(1-p)-1)/(1-p)) + TDT$Sex + TDT$Age + TDT$Educ, mu, sigma, log=TRUE))
}

mle2(LL4, start = list(p = 0.2, sigma=sd_Happiness, mu=mu_Happiness, a=1) , fixed = NULL, method = "BFGS")

Now, a paper I am trying to reproduce tells me that a is allowed to differ per country, so I want to add a*Country to the model resulting in:
LL4 <- function(p, a, mu, sigma) {
    -sum(dnorm(TDT$Happiness - a*((TDT$Income^(1-p)-1)/(1-p)) + a*TDT$Country + TDT$Sex + TDT$Age + TDT$Educ, mu, sigma, log=TRUE))
}

mle2(LL4, start = list(p = 0.2, sigma=sd_Happiness, mu=mu_Happiness, a=1) , fixed = NULL, method = "BFGS")

I get:
Error in optim(par = c(p = 0.2, a = 1, mu = 5.5, sigma = 2.88675134594813 :
  initial value in 'vmmin' is not finite
In addition: Warning message:
In Ops.factor(a, TDT$Country) : '*' not meaningful for factors

How do I properly add a factor to this model?


text:
Q: Abrir txt via pyscript com pandas O que pode estar de errado neste código? Estou tentando abrir um txt no navegador usando as regras do pyscript
Quando não fica todo branco, fica com este erro

    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />

<py-env>
    - pandas
</py-env>

    <py-script>
        import pandas as pd
        df = pd.read_csv('C:/Users/ACER/Desktop/Teste.txt', delimiter = "\t")
        print(df)
    </py-script>

A: Tem algumas alterações que precisam ser efetuadas:

*

*Utilize a tag py-env dentro da tag head

*Adicione o caminho do arquivo dentro de paths na tag py-env e use esse arquivo apenas pelo nome no código.

*Adicione uma div com id para exibir o resultado da tag py-script

*Adicione o atributo output na tag py-script com o id da div que irá exibir o resultado

Exemplo:

  <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />

  <py-env>
    - pandas
    - paths:
      - https://gist.githubusercontent.com/Quijaua/d5f9fd7aba63d1701aafb2765776c008/raw/050c3efab8dea9ee9d94f2fd3a29ba2df33d3b62/uf.txt
  </py-env>

  <py-script output="teste">
    import pandas as pd
    df = pd.read_csv("uf.txt", delimiter = "\t")
    print(df)
  </py-script>


text:
Q: Flutter firebase recaptcha does not work due to restrictions on the app's api keys I'm using FlutterFire to authenticate my users, and the method verifyPhoneNumber is giving me problems on some devices (on both Android and iOS).
On the rare occasions in which the app cannot be verified via SafetyNet (Android) or APNs silent notifications (iOS), the firebase sdk triggers the reCaptcha flow and it fails. The reason of the failure is that my api keys are restricted to my Android and iOS apps on the Google Cloud Console, and even though is the app (using FlutterFire's sdk) who is opening the reCaptcha screen, it is doing it in an external browser that is blocked from using this keys.
If I remove the restrictions from my keys it works perfectly, but I'm afraid that if I do that someone else can freely use them.
Is this the intended behaviour of FlutterFire? I don't know if I'm doing something wrong, but I still haven't found what. I cannot find any way to configure this behaviour when calling verifyPhoneNumber, the browser with the reCaptcha request is opened automatically.
Would be perfect if the same api key could be restricted for both an app and a http referrer but this not possible, so I didn't find an answer there either.
Any suggestions? I have removed the restrictions for now, but I wouldn't like to keep it this way.
Thanks!


text:
Q: Use triplets of integers vs HashMap> let's asume that there is a class Pos, implementing Lombok's equals and hashcode and have only immutable 3 integers (int x,y,z)
what may be more effective
HashMap<Integer, HashMap<Integer, HashMap<Integer,T>>> or
HashMap<Pos, T> ?
considering that i register values only at creation, and after that i only read values lots of times from the map, and also very often loop trough that map for every x and z possible for a specific y value (so in first case i even don't need to filter the y value, i just get the map for it, and filter null z maps for that y value)

A: Records
Java 16+ offers a brief class definition now: records. So no need to resort to Lombok for that. See JEP 395: Records.
A record is appropriate when the main purpose of your class is to carry data transparently and immutably. The compiler implicitly creates the constructor, getters, equals and hashCode, and toString.
record Position ( int x , int y , int z ) {}

Collect your Position objects.
List< Position > positions = new ArrayList<>() ;
positions.add( new Person( 1 , 2 , 3 ) ) ;
…

From stream to map via Collectors.groupingBy
Group them by their y value.
Map< Integer, Set< Position > > positionsByY =
    positions
    .stream()
    .collect(
        Collectors.groupingBy( Position :: y )
    );

When you want all x and z values for a particular valid of y, retrieve a list.


text:
Q: Translating EventAggregators usage of SynchronizationContext to VB.Net Working with a fairly large VB.Net back office winforms application.  1 million+ LOC.
Big ball of mud, 90% of all code is in Forms & other UI controls.
Slowly introducing better architecture as time & recources allows, We've been using ideas from the EventAggrgator by Jeremy Miller.
http://codebetter.com/blogs/jeremy.miller/archive/2008/01/11/build-your-own-cab-extensible-pub-sub-event-aggregator-with-generics.aspx
Initially I stripped out the usage of SynchronizationContext.  Now I'm trying to introduce it back, and I'm struggling with the translation of the lamda stuff from c# to vb.net.
Specifically this line of c#
_context.Send(delegate { receiver.Handle(subject); }, null);

This is the vb.net I have so far:
_context.Send(New SendOrPostCallback(AddressOf listener.Handle(message)), Nothing)

The error I'm getting is
listener.Handle(message) <-- AddressOf operand must be the name of a method.
I'm sure I'm missing something simple, but after staring at this for 2 days, I'm lost.

A: Try the following
_context.Send(New SendOrPostCallback(AddressOf listener.Handle), message)

The problem is you're trying to translate C# delegates which aren't supported in VB until VB9.  This style of delegate, void returning, is not actually supported until VB10.
The best translation is to use straight delegates instead.  Depending on the signature the above should work.  if not, please post the signature for listener.Handle so we can give a better answer.


text:
Q: Is there a way to bypass key/token-authentication in ManagedOnlineEndpoint (SDK-v2)? According to SDK-v2's ManagedOnlineEndpoint documentation, auth_mode must be provided thru key or aml_token. This means, once the endpoint is deployed, we need to include the api key or token when we send POST requests to the API. I'm wondering if there's a way to bypass providing these authentication methods, e.g., thru Azure ManagedIdentity?
My motivation for bypassing the key/token authentication is that, I have an ML model (deployed via ManagedOnlineEndpoint) that needs to call multiple other secondary ManagedOnlineEndpoints and then use their outputs as input-features in the (main) model. It would be nice to not have to manage API-keys for those secondary model endpoints.
I have a solution that works, but I'm curious if there's an alternative or more elegant way of doing it.
The current solution is, I'm storing APIkeys of the secondary models in Azure KeyVault and then retrieve them when needed, i.e., defined in the scoring script of the (main) model.

A: Use managed identity for seamless access to your resources. Here is the Document to access Azure resources from an online endpoint with a managed identity.
The identity for an endpoint is immutable. During endpoint creation, you can associate it with a system-assigned identity (default) or a user-assigned identity. You can't change the identity after the endpoint has been created.


text:
Q: Outlook Undeliverable Bounce Report-Item Search Issues, VBA I have some undeliverable emails in a folder. I am trying to go through each email in the folder and pull out the intended recipients email address by searching the message.
I have some VBA code that works on regular emails, but since undeliverable's aren't Outlook "Mail Items", they are Outlook "Report Items", I am having issues searching the message. The search function is coming back empty and after a lot of research, it seems that maybe "Report Items" do not actually have a "body" that can be searched.
The email in all the error reports are in the following format in the report.
(xxxxxx@xxxxxx.com)

Here is the code I am using, which works on normal Mail Items.
Sub Undeliver()

On Error Resume Next
Set myOlApp = Outlook.Application
Set mynamespace = myOlApp.GetNamespace("MAPI")

'Selects the current active folder to use
Set myfolder = myOlApp.ActiveExplorer.CurrentFolder

'creates excel spreadsheet where data will go
Set xlobj = CreateObject("excel.application")
xlobj.Visible = True
xlobj.Workbooks.Add

'names column a row 1 "email" and column b row 1 "else"
xlobj.Range("a" & 1).Value = "Email"
xlobj.Range("b" & 1).Value = "Else"

'loops through all the items in the current folder selected
For I = 1 To myfolder.Items.Count
    Set myitem = myfolder.Items(I)

    'selects the body of the current email being searched
    msgtext = myitem.Body

    'searches the body for the first open parentheses and first close
    'parentheses and copies the value in between into an array
    delimtedMessage = Replace(msgtext, "(", "###")
    delimtedMessage = Replace(delimtedMessage, ")", "###")

    'splits the array up into two pieces
    messageArray = Split(delimitedMessage, "###")

    'this inputs the values of the array into my excel spreadsheet
    xlobj.Range("a" & I + 1).Value = messageArray(1)
    xlobj.Range("b" & I + 1).Value = messageArray(2)
Next I

End Sub

Does anyone know how I can access the message part of the report for searching purposes?

A: The solution I ended up going with involved converting the body of the message back to Unicode and then searching for what I needed. This ended up being very simple to implement.
Here is my finished, working code for future reference. I ended up adding a progress bar to monitor where it was in the code. It unfortunately runs fairly slow but it gets the job done.
Hopefully this helps someone in the future!
On Error Resume Next
Set myOlApp = Outlook.Application
Set mynamespace = myOlApp.GetNamespace("MAPI")

Set xlobj = CreateObject("excel.application")
xlobj.Visible = True
xlobj.Workbooks.Add

xlobj.Range("a" & 1).Value = "Email"
xlobj.Application.displayStatusBar = True

For I = 1 To myOlApp.ActiveExplorer.CurrentFolder.Items.Count
    Set myitem = myOlApp.ActiveExplorer.CurrentFolder.Items(I)
    msgtext = StrConv(myitem.Body, vbUnicode)

    delimtedMessage = Replace(msgtext, "mailto:", "###")
    delimtedMessage = Replace(delimtedMessage, "
", "###")
    messageArray = Split(delimtedMessage, "###")

    xlobj.Range("a" & I + 1).Value = Split(messageArray(1), """")(0)
    xlobj.Application.StatusBar = "Progress: " & I & " of " & myOlApp.ActiveExplorer.CurrentFolder.Items.Count & Format(I / myOlApp.ActiveExplorer.CurrentFolder.Items.Count, " 0%")
Next I

xlobj.Application.displayStatusBar = False

A: Well, there is always this solution.
The gist is that ReportItem.Body returns an unreadable string, so this solution saves the ReportItem as a text file, then parses the text file. Its not exactly elegant, but it should work.
Hope this helps!


text:
Q: Condition on whether filename belongs to a list of filenames From this site, I've learned how to condition on the name of my latex file.     This code below returns the first line of the conditional iff the file is called test.tex
\begin{document}
    \ifthenelse{\equal{\detokenize{test}}{\jobname}}
        { This is file test.tex }
        { This is NOT file test.tex  }
    \end{document}

Unfortunately, I need to condition on whether the filename belongs to a list of filenames, specified externally to this file.     Is there a way of getting latex to read an external file, obtain a list of file names, then condition on whether or not \jobname  belongs to that list?   I realize that this seems like a lot to ask for, but ...

A: You can do it in various ways with expl3. Since you want to use \jobname, we have to stringify everything and do full expansion.
If the check is to be done just a few times, we can read the file each time:
% this file is named leosimon.tex
\begin{filecontents*}{listoffiles.txt}
leosimon.tex
x-leosimon.tex
foobar.tex
\end{filecontents*}

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand {\checkfileinlistTF}{mmmm}
 { % #1 = name to test, #2 = file name, #3 = True case, #4 = False case
  \file_if_exist:nTF { #2 }
   {
    \leosimon_checkfileinlist:nnnn { #1 } { #2 } { #3 } { #4 }
   }
   {
    %error
    \msg_error:nnn { leosimon/checkfiles } { nofilelist } { #2 }
   }
 }

\tl_new:N \l_leosimon_checkfiles_list_tl
\tl_new:N \l_leosimon_checkfiles_name_tl
\msg_new:nnnn { leosimon/checkfiles } { nofilelist }
 {
  Missing~file~list~#1
 }
 {
  The~file~#1~does~not~exist,~aborting~command
 }

\cs_new_protected:Nn \leosimon_checkfileinlist:nnnn
 {
  % read the file list
  \tl_set_from_file:Nnn \l_leosimon_checkfiles_list_tl { } { #2 }
  % stringify the file list
  \tl_set:Nx \l_leosimon_checkfiles_list_tl { \tl_to_str:N \l_leosimon_checkfiles_list_tl }
  % fully expand the name
  \tl_set:Nx \l_leosimon_checkfiles_name_tl { #1 }
  % stringify the name
  \tl_set:Nx \l_leosimon_checkfiles_name_tl { \tl_to_str:N \l_leosimon_checkfiles_name_tl }
  % check
  \tl_if_in:NVTF \l_leosimon_checkfiles_list_tl \l_leosimon_checkfiles_name_tl
    {
     #3
    }
    {
     #4
    }
 }
\cs_generate_variant:Nn \tl_if_in:NnTF { NV }
\ExplSyntaxOff

\begin{document}

\checkfileinlistTF{\jobname.tex}{listoffiles.txt}
 {This is in the list}
 {This is NOT in the list}

\checkfileinlistTF{x-\jobname.tex}{listoffiles.txt}
 {This is in the list}
 {This is NOT in the list}

\checkfileinlistTF{foobar.tex}{listoffiles.txt}
 {This is in the list}
 {This is NOT in the list}

\checkfileinlistTF{hey.tex}{listoffiles.txt}
 {This is in the list}
 {This is NOT in the list}

\checkfileinlistTF{hey.tex}{wrongname}
 {This is in the list}
 {This is NOT in the list}

\end{document}

Output on the terminal:
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! leosimon/checkfiles error: "nofilelist"
!
! Missing file list wrongname
!
! See the leosimon/checkfiles documentation for further information.
!
! For immediate help type H <return>.
!...............................................

l.79  {This is NOT in the list}

? h
|'''''''''''''''''''''''''''''''''''''''''''''''
| The file wrongname does not exist, aborting command
|...............................................
?

PDF output

However, this would be too expensive if the check has to be performed several times.
Here is an indirect way. The file list is read in before using it, most conveniently in the preamble, but it's not mandatory. You can have more than one list. The command \readfilelist has an optional argument; if present it will create a new list which you can use in \checkfileinlistTF like
\readfilelist[newlist]{<filename>

\checkfileinlistTF[newlist]{x.tex}{True}{False}

Here's the full code.
% this file is named leosimon.tex
\begin{filecontents*}{listoffiles.txt}
leosimon.tex
x-leosimon.tex
foobar.tex
\end{filecontents*}

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\readfilelist}{O{default}m}
 {
  \leosimon_checkfiles_read:nn { #1 } { #2 }
 }

\NewDocumentCommand {\checkfileinlistTF}{O{default}mmm}
 { % #1 = list (optional), #2 = file name, #3 = True case, #4 = False case
   \leosimon_checkfileinlist:nnnn { #1 } { #2 } { #3 } { #4 }
 }

\tl_new:N \l_leosimon_checkfiles_name_tl

\msg_new:nnnn { leosimon/checkfiles } { nofilelist }
 {
  Missing~file~list~#1
 }
 {
  The~file~#1~does~not~exist,~aborting~command
 }

\cs_new_protected:Nn \leosimon_checkfiles_read:nn
 {
  \file_if_exist:nTF { #2 }
   {
    \tl_gclear_new:c { g_leosimon_checkfiles_#1_tl }
    % read the file list
    \tl_gset_from_file:cnn { g_leosimon_checkfiles_#1_tl } { } { #2 }
    % stringify the file list
    \tl_gset:cx { g_leosimon_checkfiles_#1_tl } { \tl_to_str:c { g_leosimon_checkfiles_#1_tl } }
   }
   {
    %error
    \msg_error:nnn { leosimon/checkfiles } { nofilelist } { #2 }
   }
 }

\cs_new_protected:Nn \leosimon_checkfileinlist:nnnn
 {
  % fully expand the name
  \tl_set:Nx \l_leosimon_checkfiles_name_tl { #2 }
  % stringify the name
  \tl_set:Nx \l_leosimon_checkfiles_name_tl { \tl_to_str:N \l_leosimon_checkfiles_name_tl }
  % check
  \tl_if_in:cVTF { g_leosimon_checkfiles_#1_tl } \l_leosimon_checkfiles_name_tl
    {
     #3
    }
    {
     #4
    }
 }
\cs_generate_variant:Nn \tl_if_in:NnTF { cV }
\ExplSyntaxOff

\readfilelist{listoffiles.txt}

\readfilelist[wrong]{wrong.txt} % a new list (but it will give error if the file is not there

\begin{document}

\checkfileinlistTF{\jobname.tex}
 {This is in the list}
 {This is NOT in the list}

\checkfileinlistTF{x-\jobname.tex}
 {This is in the list}
 {This is NOT in the list}

\checkfileinlistTF{foobar.tex}
 {This is in the list}
 {This is NOT in the list}

\checkfileinlistTF{hey.tex}
 {This is in the list}
 {This is NOT in the list}

\end{document}


text:
Q: html5 canvas or dom for online backgammon game I'm starting to develop an online backgammon game. I 'm not sure whether to use html5 canvas or use dom and css. could you tell me the pros and cons of each approach for moving and animating pieces?

A: Board games like backgammon require very little animation, and/or fancy animations. In other words, it's a relative "simple" 2d game (relative to what's possible with both DOM manipulation and Canvas 2d context). I assume you want to make it in 2d.
This means that you can use both methods to create the game; they will both do just fine. The real question becomes: which technique do you know more about, and do you prefer?
If you don't know the answer to that, start investigating in both techniques. Read simple tutorials, play with some code and get the gist of both techniques. Then make your decision.
Canvas

*

*pro: more advanced techniques available

*pro: easier to distribute to game portals

*con: a bit harder to master imo

*con: easy to fkcu it up (memory and performance wise)

DOM manipulation
See the canvas pros and cons, and revert them ;)
Here a nice guide to canvas 2d context methods.


text:
Q: Horovod torch estimator prepare_batch error I'm trying to make a horovod torch estimator for a spark pipeline, but I'm getting an error while trying to fit the data and I don't know/understand the cause.
I've left the full stack error here, but the final trace is as follows:
[1,0]<stderr>:Traceback (most recent call last):
[1,0]<stderr>:  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
[1,0]<stderr>:    return _run_code(code, main_globals, None,[1,0]<stderr>:
[1,0]<stderr>:  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
[1,0]<stderr>:    exec(code, run_globals)
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/task/mpirun_exec_fn.py", line 52, in <module>
[1,0]<stderr>:    main(codec.loads_base64(sys.argv[1]), codec.loads_base64(sys.argv[2]))
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/task/mpirun_exec_fn.py", line 45, in main
[1,0]<stderr>:    task_exec(driver_addresses, settings, 'OMPI_COMM_WORLD_RANK', 'OMPI_COMM_WORLD_LOCAL_RANK')
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/task/__init__.py", line 61, in task_exec
[1,0]<stderr>:    result = fn(*args, **kwargs)
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/torch/remote.py", line 432, in train
[1,0]<stderr>:    'train': _train(epoch)
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/torch/remote.py", line 373, in _train
[1,0]<stderr>:    inputs, labels, sample_weights = prepare_batch(row)
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/torch/remote.py", line 306, in prepare_batch
[1,0]<stderr>:    for col, shape in zip(feature_columns, input_shapes)]
[1,0]<stderr>:TypeError: 'NoneType' object is not iterable

Unfortunately, I don't really know how to give a minimal reproducible example, but I'll try to give the most relevant and minimal information possible to understand the context.
I'm working on a google colab notebook.
I created the estimator following the documentation, like so:
import horovod.spark.torch as hvd
from horovod.spark.common.store import DBFSLocalStore
import shutil
import uuid

uuid_str = str(uuid.uuid4())
work_dir = "/dbfs/horovod_spark_estimator/"+uuid_str

from torch import optim
# Setup store for intermediate data
store = DBFSLocalStore(work_dir)
optimizer = optim.Adam(model.parameters(), lr=1.0e-3)

torch_estimator = hvd.TorchEstimator(
  store=store,
  num_proc=1,
  model=model,
  optimizer=optimizer,
  feature_cols=['Windows'],
  label_cols=['Labels'],
  verbose=1)

And the model is from this repo, which is a basic LSTM in pytorch with some minor customizations. I also changed the requirements to use the most updated libraries.
The Dataframe fed to the fit function is like so:
+--------------------+------+---+
|             Windows|Labels| id|
+--------------------+------+---+
|[0, 0, 0, 0, 1, 2...|     1|  0|
|[0, 0, 0, 1, 2, 2...|     1|  1|
|[0, 0, 1, 2, 2, 2...|     1|  2|
|[0, 1, 2, 2, 2, 2...|     0|  3|
|[1, 2, 2, 2, 2, 2...|     0|  4|
|[2, 2, 2, 2, 2, 2...|     0|  5|
|[2, 2, 2, 2, 2, 2...|     0|  6|
|[2, 2, 2, 2, 2, 2...|     0|  7|
+--------------------+------+---+

Which is an array/vector of 10 ids and 1 label per window.
My attempts to solve this issue
My first hypothesis was that, by looking at the error log, it looks like there is a mismatch between the input data and the model definition. If so, i don't understand how the mismatch could be possible, since the model expects as features the list of ids and a label of 1 or 0 for the whole window (list).
Thinking that it might be caused by the column names, I also tried changing them to exactly the name expected when using the normal torch dataloader, but with no success.
The second thing that stood out was that NoneType object, as if horovod isn't taking or finding the correct data or structure to pass the model.
I tried looking on the web for similar situations, but it seems like horovod isn't widely used, so I found little to nothing useful in helping me.
Any help in finding a solution to this would be greatly appreciated, but I'm also open to any alternative to horovod that can integrate a torch model into a spark pipeline or just be fed a spark dataframe.
EDIT 1:
Thanks to @pSoLT I managed to get past the NoneType Error by setting the input shapes in the the constructor of hvd.TorchEstimator (in my case input_shapes=[[-1,10]]).
Unfortunately, I immediately stumbled upon another one:
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/task/__init__.py", line 61, in task_exec
[1,0]<stderr>:    [1,0]<stderr>:result = fn(*args, **kwargs)[1,0]<stderr>:
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/torch/remote.py", line 432, in train
[1,0]<stderr>:    [1,0]<stderr>:'train': _train(epoch)[1,0]<stderr>:
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/torch/remote.py", line 374, in _train
[1,0]<stderr>:    [1,0]<stderr>:outputs, loss = train_minibatch(model, optimizer, transform_outputs,[1,0]<stderr>:
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/torch/remote.py", line 468, in train_minibatch
[1,0]<stderr>:    [1,0]<stderr>:loss = loss_fn(outputs, labels, sample_weights)[1,0]<stderr>:
[1,0]<stderr>:  File "/usr/local/lib/python3.8/dist-packages/horovod/spark/torch/remote.py", line 351, in loss_fn
[1,0]<stderr>:    [1,0]<stderr>:loss = calculate_loss(outputs, labels, loss_weights, loss_fns, sample_weights)[1,0]<stderr>:
[1,0]<stderr>:NameError[1,0]<stderr>:: [1,0]<stderr>:free variable 'loss_fns' referenced before assignment in enclosing scope[1,0]<stderr>:

As I mentioned in the comments, I'll play around more if I have the chance, but I'll try switching to SparkTorch for the immediate future.


text:
Q: VBA Cubevalue referencing I am quite new to VBA and I have problem with inserting Cubevalue formula.
I can insert formula like this.
Formula = "=CUBEVALUE(""ThisWorkbookDataModel"",""[Measures].[MTD]"",""[DataAll_Qe].[Attribute].&[""&R19C&""]"",""[MaterialMatrix_Qe].[Material].&[""&RC3&""]"",""[CalendarMatrix_Qe].[TIP].&[""&R20C&""]"",Slicer_Month,Slicer_Subcategory)"

What I want is that instead of inserting member &[""&R19C&""]" it is dynamic and it inserts Frow(defined variable for first row)minus one. So if I change first row to 25 it inserts &[""&R24C&""]".
Hope you can help me. The whole purpose is to copy than this value formula from First row/First column to Last row/Last Column.
There are be many rows and 4 columns.
I have managed to make formula, only problem is that it is static with referenced member expressions.
Regards,
Eagle


text:
Q: Create regex from object keys How can I simplify the following better using Underscore? It feels like too much code for something very simple. It creates a regex from the object keys.
var obj = {
   'dog' : 1,
   'cat' : 1,
   'rat' : 1
};

var arr = [], regex;

_.each( obj, function( value, index ){
  arr.push( index );
});

regex = _.reduce( arr, function(){
  return new RegExp( arr.join('|'), 'i' );
});

// console.log( regex ) should output:
/dog|cat|rat/i

A: Simply use Object.keys and native Array.prototype.join like this
console.log(new RegExp(Object.keys(obj).join("|"), "i"));

With _, it will be _.keys
console.log(new RegExp(_.keys(obj).join("|"), "i"));

The result would be
/dog|cat|rat/i

A: I quickly figured that you don't need to use underscore for this.
 var regex = new RegExp( Object.keys( obj ).join('|'), 'i' );


text:
Q: The sum of a square and twice a square Consider the set $\{3,6,9,11,12,17,18,19,22\ldots\}$ (OEIS A154777) of positive integers that are expressible in the form $a^2 + 2b^2$.   Is there a theorem about the form of such numbers analogous to the one about integers representable in the form $a^2 + b^2$? Is there a way to relate this problem to that one?
Some numbers, such as $27, 33, 51, 54,\ldots$ are expressible in the form $a^2 + 2 b^2$ in more than one way.  Is the set of such numbers infinite? (OEIS search for this sequence finds nothing.)  It appears that all such numbers are divisible by 3; is there a proof of this?  What else is known about this?
(Mercio observes in a comment that $121 = 11^2 + 2\cdot0^2 = 7^2 + 2\cdot6^2$ is not divisible by 3; another example is $209 =3^2 + 2\cdot 10^2 = 9^2 + 2\cdot 8^2$.)

A: According to OEIS,

$n$ belongs to this sequence iff every prime $ p \equiv 5,7 \pmod 8$ dividing $n$ occurs to an even power.

So the answer to my question "Is there a theorem analogous to the one about $a^2+b^2$?" is "Yes".

A: $$ (a^2 + 2 b^2)(c^2 + 2 d^2) = (ac+2bd)^2 + 2 (ad-bc)^2 = (ac-2bd)^2 + 2 (ad+bc)^2  $$
so you get multiple representations as soon as you have the product of two distinct represented odd primes, that is $\equiv 1,3 \pmod 8.$ You kind of lose if 2 is involved because of the evident $0,$ also you get the analogue of Pythagorean triples for the square of any odd represented prime, as in mercio's comment.
The presence of such a simple formula for multiplication is just that this is the principal form (binary quadratic forms) of this discriminant. The fact that it is  simple to describe the represented primes is the fact that this is class number one. That is, there is only one genus, the principal one, and there is only one (equivalence class of) forms in that genus. It is still not too bad when you have one form per genus but more than one genus, as in $x^2 + 6 y^2$ and $2 x^2 + 3 y^2.$ But then the description of all numbers that are represented by the principal form includes an extra odd/even check about the sum of certain prime exponents.


text:
Q: manual random selection, how? Thas a question for my test in one hour...how do I do that? I have tried to find it online but no way...any help please?
Suppose that a simple random sample of 20 of the Aucklanders surveyed is to be
selected for further in-depth interviews about the new Auckland Council. Each
person surveyed is allocated an identification number from 1 to 300. Use the row
of random digits below to select the first 5 people. Start at the beginning of the
row and use consecutive groups of digits.
38905 93159 25252 29004 50592 73607
Here are the answer choices.
The first five Aucklanders sampled had identification numbers:
(1) 38, 90, 59, 31 and 25
(2) 389, 59, 315, 925 and 252
(3) 59, 252, 290, 45 and 273
(4) 389, 931, 252, 290 and 505
(5) 59, 252, 290, 45 and 59

A: You look at the row of random numbers and take three at a time. If the three-digit number you get isn't in the range 1-300, skip it. So, the first three digits are 389, which isn't an identification number in the appropriate range: skip it. Then the next three digits are 059, which give the ID number 59. Next, 315 and 925- skip them. Then 252, 290, 045, so our first four Aucklanders sampled are 59, 252, 290, 45. That narrows it down to choices 3, 5: do you see how to pick the last one?


text:
Q: How to subtract all elements in list against each other? I'm currently building a time calculator for running and one of my calculators is to subtract time.
Once the user enters all of their times they'd like to subtract, it would look like this:
TimesList = [60, 120, 240, 600]

My question is how could I creates some statement to subtract all the elements in the list to create some final time number? I would want some logic to do this: 600 - 240 - 120 - 60 = finaltime
Also keep in mind that the newest time is inserted at the front of the list, so subtraction would have to start at the back of the list and work to the front.

A: You can use functools.reduce:
import functools
TimesList = [60, 120, 240, 600]
final_result = functools.reduce(lambda x, y:x-y, TimesList[::-1])

Output:
180

A: You could go with the following :
(sum(TimesList[:-1]) * -1) + TimesList[-1]

A: You can try this if you want to create your own function :
TimesList = [60, 120, 240, 600]
def recursive(final_time,value):
    if not final_time:
        return value
    else:
        try:
            value -= final_time[1]

            return recursive(final_time[1:], value)
        except IndexError:
            return value

print(recursive(sorted(TimesList,reverse=True),sorted(TimesList,reverse=True)[0]))

output:
180


text:
Q: How to create a helper method that takes 2 double inputs into a class global array? I'm new to java and I have a question about an assignment I have. I've written a bunch of methods that are different formulas, like the duration of a storm. The assignment asks me to write two helper methods to get input from the user. One of them is called get_S_Input() and I was able to implement it correctly I think. But the one I'm stuck on is this other helper method called get_2_Invals(). It wants me to prompt the user with my parameter, and read in 2 double values. It wants me to record the values in a class global array of doubles and then exit the method, but I don't know how to do this. I want to put it in the else statement in the method below. Here is my code so far...
import java.lang.Math;
import java.util.Scanner;

public class FunFormulas {
    public void sd(){
        double durationOfStorm = Math.sqrt(((Math.pow(get_S_Input("Enter the diameter of storm in miles:"), 3) / 216)));
        if (durationOfStorm > 0)
            System.out.println("The storm will last: " + durationOfStorm);
    }

    public void sl(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of seconds since the lightning strike:");
        double secondsSinceLightning = Double.valueOf(scanner.nextLine());
        double distanceFromLightning = (1100 * secondsSinceLightning);
        System.out.println(distanceFromLightning);
    }

    public void si(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the edge of cube in inches:");
        double edgeOfCubeInInches = Double.valueOf(scanner.nextLine());
        if (edgeOfCubeInInches < 0){
            System.out.println("ERROR: please enter a non-negative number!!!");
        }
        double weightOfCube = (0.33 * (Math.pow(edgeOfCubeInInches, 3)));
        System.out.println(weightOfCube);
    }

    public void dt(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the time in hours:");
        double timeInHours = Double.valueOf(scanner.nextLine());
        if (timeInHours < 0){
            System.out.println("ERROR: please enter a non-negative number!!!");
        }
        System.out.println("Enter the rate of speed in mph:");
        double rateOfSpeed = Double.valueOf(scanner.nextLine());
        if (rateOfSpeed < 0){
            System.out.println("ERROR: please enter a non-negative number!!!");
        }
        double distanceTravelled = (rateOfSpeed * timeInHours);
        System.out.println(distanceTravelled);
    }

    public void sa(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your weight in pounds:");
        double weight = Double.valueOf(scanner.nextLine());
        weight = weight * 0.4536;
        System.out.println("Enter your height in inches:");
        double height = Double.valueOf(scanner.nextLine());
        height = height * 2.54;
        double BSA = ((Math.sqrt(weight * height)) / 60);
        System.out.println(BSA);
    }

    public double get_S_Input(String promptStr){
        //Scanner helper method
        System.out.println(promptStr);
        Scanner scanner = new Scanner(System.in);
        double value = Double.valueOf(scanner.nextLine());
        if (value < 0 ){
            System.out.println("ERROR: please enter a non-negative number!!!");
        }
        return value;
    }

    public void get_2_Invals(String promptStr){
        /*Prompt the user with the promptStr passed in as a parameter
        ii. Read in the first double precision value entered by the user with the Scanner
        iii. Read in the second double precision value entered by the user with the Scanner
        iv. Check to make sure the values entered by the user are non-negative
        a. If either number entered by the user is negative, the method should print out an
            error message, and return to step i. above.
        b. If the number is non-negative (that is greater than or equal to zero) the method
            should record the numbers obtained from the user in a class-global array of
            doubles and exit.*/
        System.out.println(promptStr);
        Scanner scanner = new Scanner(System.in);
        double firstValue = scanner.nextInt();
        double secondValue = scanner.nextInt();
        if (firstValue < 0 || secondValue < 0)
            System.out.println("ERROR: please enter non-negative number!");
        else

    }

    public static void main(String [] args){
        FunFormulas fun = new FunFormulas();
        fun.sd();
    }
}


text:
Q: Fetched data failed to reach the component I trying to fetch data from API with React+Redux, but for some reason, data fails to render, even though i see it comes in console (with redux-logger)
It looks like for some reason, reducer doesn't change areLoading value to false - and data doesn't reach page. But I can't figure our where is the mistake, everything is seems right.
Component:
class Posts extends Component {
    componentDidMount() {
        this.props.postsFetch();
    }
    render() {

        return (

                {this.props.data.map(function(post, i) {
                    return (

{post.title}

                    );
                })
                }

        );
    }
}

const mapStateToProps = (state) => {
    return {
        data: state.posts,
        gotError: state.postsError,
        areLoading: state.postsLoading
    };
};

export default connect(mapStateToProps, { postsFetch })(Posts);

Reducers:
const INITIAL_STATE = {
    areLoading: false,
    gotError: false,
    items: []
}
export function postsError(state = INITIAL_STATE, action) {
    switch (action.type) {
        case "POSTS_REQUEST_FAILURE":
            return {
                ...state,
                gotError: true
            }
        default:
            return state;
    }
}

export function postsLoading(state = INITIAL_STATE, action) {
    switch (action.type) {
        case "POSTS_REQUEST_LOADING":
            return {
                ...state,
                areLoading: true
            }
        default:
            return state;
    }
}

export function posts(state = INITIAL_STATE, action) {
    switch (action.type) {
        case "POSTS_REQUEST_SUCCESS":
            return {
                ...state,
                areLoading: false,
                items: action.data
            }
        default:
            return state;
    }
}

If I change my return statement to "return action.areLoading = false", and after that return action.data, everything works. But this solutions seems not right.
Actions:
export function postsError() {
    return {
        type: "POSTS_REQUEST_FAILURE",
    };
}

export function postsLoading() {
    return {
        type: "POSTS_REQUEST_LOADING",
        url: 'http://jsonplaceholder.typicode.com/posts/',
    };
}

export function posts(data) {
    return {
        type: "POSTS_REQUEST_SUCCESS",
        data
    };
}

export function postsFetch() {
    return function (dispatch) {
        dispatch(postsLoading());
    }
}

Middleware:
export const apiCallMiddleware = store => next => action => {
    const { url, ...rest } = action;

    if (!url) return next(action)

    next({ type: "POSTS_REQUEST_LOADING" })

    axios(url)
        .then(response => {
            const data = response.data
            next({ type: "POSTS_REQUEST_SUCCESS", data })
        })
        .catch(err => {
            next({ ...rest, type: "POSTS_REQUEST_FAILURE" })
        })
}

I searched for a solutions on forum, but none of them seems to help me. I also new to React+Redux, sorry for a newbie question.
Thanks in advance.

A: You're passing data into the posts action as an object and the reducer doesn't recognize a data key when you're doing action.data. I believe you have to change data to data: data in two places.
In the middleware:
next({ type: "POSTS_REQUEST_SUCCESS", data: data })

In the posts action:
export function posts(data) {
    return {
        type: "POSTS_REQUEST_SUCCESS",
        data: data                    //<---------
    };
}

and the reducer can now access the key data from action like so:
case "POSTS_REQUEST_SUCCESS":
  return {
    ...state,
    areLoading: false,
    items: action.data
  }

A: I figure out what was the problem.
Here
const mapStateToProps = (state) => {
    return {
        data: state.posts,
        gotError: state.postsError,
        areLoading: state.postsLoading
    };
};

i got links to state.post object.
Changing it to
const mapStateToProps = (state) => {
    return {
        data: state.posts.items,
        gotError: state.posts.gotError,
        areLoading: state.posts.areLoading
    };
};

make it to look on object properties, instead of the whole object
Thanks for the help!

A: Please try to log your state under mapStateToProps like console.log(state); and use the exact property into return statement. I believe there is some issue.
const mapStateToProps = (state) => {
    console.log(state);
    return {
        data: state.posts,
        gotError: state.postsError,
        areLoading: state.postsLoading
    };
};


text:
Q: How does one determine for which value of $z_0$ the equation $ax+by=z$ has positive integer solutions $(x,y)$ for all $z\geq z_0$? I just recently learned about "Frobenius Numbers" from watching Numberphile on youtube (http://www.youtube.com/watch?v=vNTSugyS038) and they look strikingly like Diophantine equations in some sense... But what seems off is that every Diophantine equation I've seen thus far doesn't have an integer solution for every value past some other value.. The example they use is using various discrete combinations of packages of chicken nuggets, it is impossible to order some combinations of nuggets less than some $x$ (of which I forget off the top of my head), and that every value greater than $x$ can be obtained through some linear combination of the available bunches.
For example, in another video from Arsdigita, it is argued that $7x+11y=z$ has positive integer solutions $(x,y)$ for every $z\geq 61$.
One thing I learned is that $ax+by=z$ has a solution if and only if $(a,b)\mid z$. So is the link here that $(a,b)=1$? How does one determine starting at which value of $z$ that positive solutions can always be found?

A: You are correct in thinking that the equation $ax + by = z$ can only have integer solutions for all sufficiently large $z$ if $(a,b) = 1$. However, if $(a,b) = 1$, You can in fact always find a $z_0$ such that, for all $z\ge z_0$, the equation has a solution. There is even a simple closed form for this: $z_0 = (a-1)(b-1)$.
This can be proved by noting that, if we allow $x$ and $y$ to be negative, than any $z$ may be written in the form $ax + by$, in many different ways. This is still possible, in fact, if we restrict $x$ to be in the range $0\le x < b$. In that case, there is always a unique choice of values for $x$ and $y$ (this can be shown using modular arithmetic). So, to find the largest number that we can't represent with $x$ and $y$ positive, we let $x = b-1$ (the largest possible value less than $b$)and $y = -1$ (the largest possible negative value), and get $z = a(b-1) + -b = ab - a - b$, so all integers greater than $z_0 = ab-a-b+1 = (a-1)(b-1)$ are representable as $ax + by$ with $x,y >0$.


text:
Q: Why are the Lonely Mountain and the dwarfs not shown in Lord of the Rings? This has really been bugging me after watching the three Hobbit films and then, even though I had already watched them thousands of times, the Lord of the Rings trilogy (only to get a real insight into what actually happened to Middle Earth as such).
When I watched the Lord of the Rings again, they don't really mention anything about the Lonely Mountain, or about the dwarves and why they didn't help in the battle in Return of the King. They only really spoke about Moria and Balin being killed.
Someone please put my mind at rest and explain why this is.

A: The Dwarves and Men of Dale did not assist Gondor because, like most other kingdoms in Middle Earth, they were facing danger and battles of their own.

At the same time as the great armies besieged Minas Tirith a host of the allies of Sauron that had long threatened the borders of King Brand crossed the River Carnen, and Brand was driven back to Dale. There he had the aid of the Dwarves of Erebor; and there was a great battle at the Mountain's feet. It lasted three days, but in the end both King Brand and King Dáin Ironfoot were slain, and the Easterlings had the victory. But they could not take the Gate, and many, both Dwarves and Men, took refuge in Erebor, and there withstood a siege.
When news came of the great victories in the South, then Sauron's northern army was filled with dismay; and the besieged came forth and routed them, and the remnant fled into the East and troubled Dale no more. Then Bard II, Brand's son, became King in Dale, and Thorin III Stonehelm, Dáin's son, became King under the Mountain. They sent their ambassadors to the crowning of King Elessar; and their realms remained ever after, as long as they lasted, in friendship with Gondor; and they were under the crown and protection of the King of the West.

From the Lord of the Rings appendices.
This attack was foreseen:

We discover that messengers have come also to King Brand in Dale, and that he is afraid. We fear that he may yield. Already war is gathering on his eastern borders. If we make no answer, the Enemy may move Men of his rule to assail King Brand, and Dáin also '

(Gloin, in Council of Elrond)
Aside from that, they are not mentioned because Dale and Erebor are not on the way to Mordor and are uninvolved in the Quest. In the book, Sauron does also send emissaries to Erebor to seek for Bilbo and the Ring.

'Then about a year ago a messenger came to Dáin, but not from Moria - from Mordor: a horseman in the night, who called Dáin to his gate. The Lord Sauron the Great, so he said, wished for our friendship. Rings he would give for it, such as he gave of old. And he asked urgently concerning hobbits, of what kind they were, and where they dwelt. "For Sauron knows," said he, "that one of these was known to you on a time."

A: The Lonely Mountain and the dwarfs are mentioned on the Lord of the Rings book but not shown in the movie.
Peter Jackson has altered the story quite a bit, but also the movies couldn't be 10 hours long each; he had to cut some stuff out. The Lonely Mountain is one of them.
It is mentioned that the Kingdom under the Mountain was restored with King Bard's help and the land prospered.
Some of the dwarfs,lead by Balin preferred to leave Erebor and go and live in Moria (but where killed by the orcs, as we see in the movies).