text:
Q: Elasticsearch: Unable to save text with length over 800k I am trying to migrate from MySQL to Elasticsearch. One of field has Text length more than 800k in MySQL.
My properties:
curl -XPUT 'http://localhost:9200/book' -d '
{
  "mappings": {
    "case": {
      "properties": {
        "lesson_id": {
          "type": "integer"
        },
        "lesson_date": {
          "type": "date",
          "format": "yyyy-MM-dd HH:mm:ss"
        },
        "lesson": {
          "type": "text"
        }
      }
    }
  }
}'

I am getting blank response when I run migrate script for the record.


text:
Q: This computer doesn't have VT-x/AMD-v enabled. Enabling it in the BIOS is mandatory I have a Windows 8.1 Dell laptop with virtualization enabled. Below is the picture of intel processor identification utility.
I have Fedora 24 installed in my virtual box. It also has virtualization enabled.

When I run the cat /proc/cpuinfo | grep 'vmx\|svm' and minikube start command, it display below error message and I am not able to proceed.
Any suggestion on this how to resolve this error?

A: VirtualBox does not support nested virtualization, so the guest VM will not support VMX or SVM even though the host machine does.  You can't run a VM inside a VM.
From your screenshot, it looks like you're trying to run Kubernetes in your VirtualBox VM.  I'm not a Kubernetes expert, but my understanding is that it's meant to manage a cluster of virtual machines.  The lack of nested virtualization means you can't run the cluster within a VM; you have to install it on real hardware.  Basically, Kubernetes is something you'd use instead of VirtualBox, as a different way of creating and managing your VMs.
If you really need to run Kubernetes in a VM, VMware Workstation and Player seem to support nested virtualization.

A: enter image description here
Try this one in Bios settings and re-run minikube start

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where is the second parameter coming from in arrow function returning another arrow function in react with redux I don't understand where the (val) is coming from in the returned arrow function.  I get that the max/minLength is an arrow function taking in a argument set on the input field(3 and 25) and it's returning an arrow function with a parameter called val but where is the argument for this.  I don't see where it is passed or coming from?  I'm new to redux and redux-from so I'm not sure if it has something to do with this or just plain es6 JS.  Thanks
import React, {Component} from 'react';
import {Breadcrumb, BreadcrumbItem, Button, Form, Row, Label, Col, FormFeedback} from 'reactstrap'
import {Link} from 'react-router-dom'
import {Control, LocalForm, Errors} from 'react-redux-form';

const required = (val) => val && val.length;
const maxLength = (len) => (val) => !(val) || (val.length <= len);
const minLength = (len) => (val) => (val) && (val.length >= len);
const isNumber = (val) => !isNaN(Number(val));
const validEmail = (val) => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(val);

class Contact extends Component {
    handleSubmit = (values) => {
        console.log("Current state is:" + JSON.stringify(values));
        alert("Current state is:" + JSON.stringify(values));
    }

    render() {
        <LocalForm onSubmit={(values) => this.handleSubmit(values)}>
            <Row className="form-group">
                <Label htmlFor="firstname" md={2}>First Name</Label>
                <Col md={10}>
                    <Control.text model=".firstname" className="form-control" id="firstname" name="firstname"
                                  placeholder="First Name"
                                  validators={{required, minLength: minLength(3), maxLength: maxLength(25)}}/>
                    <Errors className="text-danger" model=".firstname" show="touched" messages={{
                        required: 'Required',
                        minLength: 'Must be greater than 2 Characters',
                        maxLength: 'Must be 25 Characters or less'
                    }}/>
                </Col>
            </Row>

A: A function returning another function is used to generate different variations of that particular function to be applied to different scenarios.
It's almost like a function factory.
It might be easier to digest what's going on if you expand the arrow functions into the standard function syntax that they represent.
function maxLength(len) {
  return function(val) {
    return !(val) || (val.length <= len);
  }
}

You can see that both arguments len and val are available on the third line for the conditional check. As far as the code in the innermost function is concerned, all the arguments taken before it are always fully available.
Below you can see how this maxLength function can be used in practice to perform different checks based on what the first argument means to you.
If your script has a concept of what a "long" array is and what a "short" array is, this is how it would work:
const isShortArray = maxLength(2); // `isShortArray(val)` is now a new function
const isLongArray = maxLength(4); // same core function, different context

isShortArray(['foo']); // true, array `val` has fewer elements than number `len` which was set to 2
isShortArray(['foo', 'bar', 'baz']); // false, `len` of maxLength exceeded

isLongArray(['foo', 'bar', 'baz']); // true, this time `len` is different
isLongArray(['foo', 'bar', 'baz', 'qux', 'foo']); // false, val.length > 4 again

This is very similar to the technique called currying in functional programming languages. You can read more about that in JavaScript here.


text:
Q: Download/save viewing picture from application resource How do I set my application to download/save to phone the image I am previewing?
I Tried with the code below but it's not working, it gives me error and I can't figure out where is that error. So what am I supposed to replace and with what?
public class FullImageActivity extends Activity {

Bitmap bm;

boolean isSDAvail=false, isSDWriteable = false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.full_image);

    //AdView ad = (AdView) findViewById(R.id.adView);
    //ad.loadAd(new AdRequest());

    // get intent data
    Intent i = getIntent();

    // Selected image id
    final int position = i.getExtras().getInt("id");
    final ImageAdapter imageAdapter = new ImageAdapter(this);
    final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
    imageView.setImageResource(imageAdapter.mThumbIds[position]);

       checkSDstuff();

}

private void checkSDstuff() {
    // TODO Auto-generated method stub
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)){
    //write
        isSDAvail = true;
        isSDWriteable =true;

    }else if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
    //read only
        isSDAvail =true;
        isSDWriteable = false;
    }else{
        //uh oh
        isSDAvail = false;
        isSDWriteable =false;
}
    Button buttonSave = (Button)findViewById(R.id.download);
    buttonSave.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(isSDAvail && isSDWriteable){

                File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                String name = filename.getText().toString(); //how to set name from postion
                File file = new File(path, name + ".jpeg");

                path.mkdirs();
                InputStream is = getResources().openRawResource(R.drawable.pic); //here to set (imageAdapter.mThumbIds[position]) from position of ImageView
                OutputStream os = new FileOutputStream(file);
                byte[] data = new byte[is.available()];
                is.read(data);
                os.write(data);
                is.close();
                os.close();
            }
        }
    });

}

A: Here is code to create a bitmap from an ImageView:
public Bitmap getBitmapFromImageView(ImageView imageView) {
    int viewWidth = imageView.getWidth();
    int viewHeight = imageView.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    imageView.layout(0, 0, viewWidth, viewHeight);
    imageView.draw(canvas);
    return bitmap;
}

Then to save the Bitmap:
try {
   Bitmap bmp = getBitmapFromImageView(imageView);
   FileOutputStream out = new FileOutputStream(filename);
   bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
   out.close();
} catch (Exception e) {
   e.printStackTrace();
}


text:
Q: Can tar -xvf be used in a If statement to return true or false I know I might sound weird but I was wondering if I could do a if [ tar -xvf ] on some file and that will return me true or false .
I need to write something to a file if the tarring was successful and if not then something else is written on the same file.
something like
if[ find . -maxdepth 1 -name "*.tar" -exec tar -xvf {} ] ; then
echo " Untar Successful"> test.txt
else
echo "Untar Not Successful"> test.txt

Please let me know if there is something I can do to implement this

A: EXIT STATUS
     The tar utility exits 0 on success, and >0 if an error occurs.

You can check error like
if [ $? -ne 0 ]; then

Where $? is the most recent foreground pipeline exit status.

A: You cannot reliably use the status of find to determine whether the commands it executes executed successfully.  The POSIX definition of find says:
find

EXIT STATUS
The following exit values shall be returned:
0   All path operands were traversed successfully.
>0  An error occurred.

This is different from saying anything about the exit statuses of any executed commands.
The xargs utility does provide the information you need.  POSIX says:
xargs

EXIT STATUS
The following exit values shall be returned:
0   All invocations of utility returned exit status zero.
1-125  A command line meeting the specified requirements could not be assembled, one or more of the invocations of utility returned a non-zero exit status, or some other error occurred.
126 The utility specified by utility was found but could not be invoked.
127 The utility specified by utility could not be found.

So, you could use:
if find . -maxdepth 1 -name "*.tar" -print0 | xargs -0-L 1 tar -xf
then echo "Untar Successful"
else echo "Untar Not Successful"
fi > test.txt

Note that this only uses one redirection. It tests the exit status of the pipeline, which is the exit status of the last command in the pipeline, which is the exit status of xargs, which tells you whether it worked or not.
The -print0 and -0 options are GNU extensions to the POSIX standard.  As long as your filenames do not contain spaces or newlines or tabs, you can safely use -print (and no corresponding argument to xargs) instead.

A: You can do:

find ... -exec sh -c 'tar ... && echo success || echo failure'

or

find ... -exec sh -c 'if tar ...; then echo success; else echo failure; fi'

(This emits a message for every file, and you can include the path of the tar
file by putting {} in the echoed message.  If you want to make one report at
the end stating that all of the tars were successful, you could do something like:

if find ... -exec sh -c 'tar ... && echo success || echo failure' |
  grep failure > /dev/null; then
    echo "untar failed"
else
    echo "untar successful"
fi

but that seems less useful to me.

A: You can definitely do "tar -tf" on tar files. Options may very according to the extensions you have. You can also add options "v" for verbose.
tar -Jtf "ABC.tar.xz"
tar -jtf "ABC.tar.bzip2"
tar -tf "ABC.tar"

You can even find list of files.
tar -tf "ABC.tar" "./ABC/hello.c" >/dev/null 2>&1

If file hello.c is present in zip file, it will return success(0) otherwise it will return error code.


text:
Q: tsql - using internal stored procedure as parameter is where clause I'm trying to build a stored procedure that makes use of another stored procedure. Taking its result and using it as part of its where clause, from some reason I receive an error:
Invalid object name 'dbo.GetSuitableCategories'.
Here is a copy of the code:
select distinct top 6 * from
 (
  SELECT TOP  100 *
  FROM [dbo].[products] products
  where products.categoryId in
  (select top 10 categories.categoryid from
    [dbo].[GetSuitableCategories]
      (
      -- @Age
      -- ,@Sex
      -- ,@Event
      1,
      1,
      1
     ) categories
    ORDER BY NEWID()
  )
  --and products.Price <=@priceRange
  ORDER BY NEWID()
 )as d

 union

 select * from
 (
   select  TOP 1 * FROM [dbo].[products] competingproducts
   where competingproducts.categoryId =-2
   --and competingproducts.Price <=@priceRange
   ORDER BY NEWID()
 ) as d

and here is  [dbo].[GetSuitableCategories] :
if (@gender =0)
   begin
    select * from categoryTable categories
    where categories.gender =3
   end
  else
   begin
    select * from categoryTable categories
    where categories.gender = @gender
    or categories.gender =3
   end

A: You can't use the results of a stored procedure directly in a select statement
You'll either have to output the results into a temp table, or make the sproc into a table valued function to do what you doing.
I think this is valid, but I'm doing this from memory
create table #tmp (blah, blah)

Insert into #tmp
exec dbo.sprocName

A: I would use an inline table valued user defined function. Or simply code it inline is no re-use is required
CREATE dbo.GetSuitableCategories
           (
--parameters
          )
RETURNS TABLE
AS
RETURN (
    select * from categoryTable categories
    where categories.gender IN (3, @gender)
)

Some points though:

*

*I assume categoryTable has no gender = 0

*Do you have 3 genders in your categoryTable? :-)

*Why do pass in 3 parameters but only use 1? See below please

*Does @sex map to @gender?

If you have extra processing on the 3 parameters, then you'll need a multi statement table valued functions but beware these can be slow


text:
Q: Anyone Using the Abyss Web Server Just curious to see if anyone is using the Abyss Web Server for any projects.
http://www.aprelium.com/
I've checked it out a few times, had it running a few ASP.Net demo sites, but haven't gotten to far with it. I like the ease of use, but I'm thinking both IIS and Apache out class Abyss for the most part.
Has anyone used it?
If so, what is your experience?
I ask because I'm tempted to use if for some projects, but if it isn't worth the investment I probably won't.
Thanks for your time.

A: I know this is many years later, but Abyss is still around, and we are using it for some of our customers who must install our apps on desktops where their IT does not allow IIS to run.  It works well with MVC and .NET 4.5.2.

A: No more than about 0.3% of public hosts, for sure:
http://news.netcraft.com/archives/2009/12/24/december_2009_web_server_survey.html


text:
Q: Reinstalling Windows 7 with Bootcamp on a Mac I have already installed Windows 7 on my Mac per the installation instructions but didn't use Bootcamp because it didn't specify to do so. I am now wondering if I made a mistake.
Do I need to uninstall Windows 7 and reload using Bootcamp? If so, how do I go about it and get Windows 7 installed correctly?

A: *

*Your Windows is correctly installed. You are not forced to use the Boot Camp Assistant (available under OS X) to install it -- in fact, with some configurations (for example, if you have multiple partitions) Boot Camp Assistant refuse to "assist" you but you can install Windows by partitioning the disk with Disk Utility and booting manually from the Windows CD at Mac startup;

*the only thing you need to do now is to install the Bootcamp drivers, so all your hardware is properly recognized. Just start Boot Camp Assistant and at the second step select "Download the latest Windows support software from Apple"; the drivers will be downloaded and will be saved on a USB key or CD. You can then boot into Windows and follow the procedure to install them.
For further information be sure to check out http://www.apple.com/support/bootcamp/ or print the installation guide at the first step of Boot Camp Assistant.

A: I haven't personally used Bootcamp, but I have used other boot loaders before. If you can boot into your Mac OS still, then you should be able to configure BootCamp to present you with the options.
I am not familiar with how this is done, but knowing Apple, I am sure it is in their options to detect an existing Windows installation. You should not need to "Uninstall" Windows, you should be able to just adjust configurations for BootCamp to deal with your current Windows installation.


text:
Q: Adding a 0 in the beginning of a 2D numpy array import numpy as np
import math as m
from matplotlib import pyplot as plt

#Q1
def bm(s,n):
    np.random.seed(222)
    dw = np.random.normal(0,1,size=(s,n))*m.sqrt(1/n)
    w = np.cumsum(dw, axis=1)
    a = np.mean(w, axis=0)
    b = np.std(w, axis=0)
    plt.plot(np.arange(n),w[:10:,:].T)
    plt.plot(np.arange(n),a.T)
    plt.plot(np.arange(n),b.T)
    plt.show()

bm(1000,600)

This code creates Brownian Motions generated from random standard normal distributions.
Every graph needs to start at 0, so I need to append 0 to the beginning of each graph.
How can I do this?

A: You can always subtract off the first delta:
w = np.cumsum(dw, axis=1) - dw[:, :1]

The elements of w are normally given by
 dw[:, :1]
 dw[:, :1] + dw[:, 1:2]
 dw[:, :1] + dw[:, 1:2] + dw[:, 2:3]
 ...

Clearly removing dw[:, :1] offsets the sum by the first element. The difference between dw[:, 0] and dw[:, :1] is that the latter preserves the shape for proper broadcasting, as if you did dw[:, 0][:, None]. If you insist on removing the last element rather than the first, you can do
 w = np.empty_like(dw)
 np.cumsum(dw[:, :-1], axis=1, out=w[:, 1:])
 w[:, 0] = 0

You can actually prepend a zero in a couple of different ways. A concatenation is one way:
np.concatenate((np.zeros((dw.shape[0], 1)), np.cumsum(dw, axis=1)), axis=1)

A potentially better way, hinted above, might be to pre-allocate the output buffer:
w = np.empty((dw.shape[0], dw.shape[1] + 1))
np.cumsum(dw, axis=1, out=w[:, 1:])
w[:, 0] = 0

A: In general, you can use numpy.concatenate to append arrays.
But in this specific case, I'd just do
dw[:, 0] = 0.0

after you create dw.


text:
Q: Merge/Zip/Copy two dynamic frame together in Glue I am working on a simple ETL process that shall extract certain columns out of am AWS RDS (postgres). The main challenge is, that most of the information is in one "json-column" just as a simple string.
My Approach so far:
# Setup Glue and get RDS
glueContext = GlueContext(SparkContext.getOrCreate())
df = glueContext.create_dynamic_frame.from_catalog(database="db", table_name="table")

# Get the fields
sel_df = df.select_fields(["regular", "bigjson"])

# Unpack the json
json_df = sel_df.unbox("bigjson", "json")

# Get the fields we need from the json
json_fields = json_df.select_fields(["A", "B", "C"])

# Want to do something like this
final_df = sel_df.select_fields(["regular"])
final_df = final_df.merge(json_fields, vertical=true) # copies the columns

This works so far. Now i want to create a new Dynamic frame using the columns from the DF json_fields and sel_df. This should be possible because non of my transformations so far changed the number of rows.
Question:

*

*Is there a way to copy them together?


text:
Q: finding out HTML equivalents of latex math symbols Unlike the other unresolved questions about painless latex to HTML conversion,
I just want to know the conversions for math symbols.
For example, when I give
\Leftrightarrow

as input to that program, I should get back
⇔

Alternatively, is there an equivalent of :
detexify.kirelabs.org/classify.html
for HTML symbols?

A: In HTML, references like ⇔ are nothing but notations indicating specific characters, and as soon as you know the identity of a symbol as a character, by its Unicode number or Unicode name, you can check the HTML 4 list of named references or the much larger HTML5 CR list of named references (the added references have much more limited browser support, and using them is almost always a bad idea). On the other hand, you don't achieve anything except perhaps some source code readability by using the named references instead of numeric references like ⇔. The numeric references are more reliable, since there have been some silent changes in the meanings of named references, between HTML versions. – Besides, when generating HTML, you can use the character themselves, if you are generating a UTF-8 encoded file, as you should.
Thus, the key question would be how to find the identity of a character. This needs to be resolved case by case, since LaTeX is about producing graphic presentations of symbols, not characters as defined in character code standards. For example, The Comprehensive LATEX Symbol List does not identify characters by code number or Unicode name, it just shows glyphs produced. In many cases, there is no real ambiguity, but often there is.
The Shapecatcher page lets you draw a symbol and then it tries to recognize it as a Unicode character. But recognizing a character from a graphic is complicated and risky. When I tested by drawing a symbol that looks like the one \Leftrightarrow produces, I got several suggestions, including U+27FA LONG LEFT RIGHT DOUBLE ARROW, but not U+21D4 LEFT RIGHT DOUBLE ARROW. These are encoded as separate characters in Unicode, and they can apparently be regarded as corresponding to \Leftrightarrow and \Longleftrightarrow, but distinguishing the two can be difficult or impossible when considering just one graphic, one glyph (since the length of the arrow naturally depends on font design, too).


text:
Q: Purpose of serial number in DNS zone files So a DNS zone file contains an SOA record specifying the authoritative name server, along with some other information such as a "serial number".
I'm trying to understand the purpose of the serial number.  Googling around for answers, I found the following explanation:

Serial numbers in DNS zone files provide a way for the server to
  verify that the contents of a particular zone file are up-to-date. If
  the serial number in a zone file hasn't changed since that zone was
  last loaded, named figures that it can ignore the file. This means
  that sysadmins have to remember to update the serial number every time
  they make a change to a zone file -- otherwise, their changes won't be
  picked up and published.

Source: http://www.itworld.com/article/2767441/it-management/serial-numbers-in-zone-files--yours-and-named-s.html
I don't understand this explanation, and the fact that this requires sysadmins to remember to manually update the serial number seems insane.
So, what's the purpose of the serial number?  It can't be for other DNS servers to verify if a particular record is out-of-date, because that's what the TTL is for.
So, why is it important to have a serial-number?  Why not just have the DNS server re-read the zone file when a change is made?

A: It's so that other servers doing zone transfers can verify if they need to do a zone transfer. Old serial number, no transfer. TTL not involved on this one.
The DNS server knows that it needs to re-read the zone file when the serial number changes as just making a change does not trigger anything, there's no timestamp within the zone file generated by changing anything to note that there has been an update on most DNS software. Most Zone files are just text files in the *nix world.
Normal convention is that the Serial number is the timestamp in date ISO date format followed by a two number increment
2014101501
Microsoft products are set up to autoincrement the Serial Number when changes are made.


text:
Q: Xcode workspace with Unity3D as a sub-project? Let's say we're developing a 2D game with Cocos2d-iPhone and UIKit and CoreAnimation. But we're also considering leveraging the 3D capabilities of Unity 3D.
Is it possible that we add the Unity3D-generated Xcode project as a sub-project into the workspace and expose the 3D UI element as some kind of UIView subclass so that the native UIKit and CoreAnimation code could use them without the need to mess up with their underlying Unity3D implementation?

A: Yes, it's possible.
The guys from Blurst have made some games using Cocoa as frontend and Unity to 3D stuffs. Take a look on links below, there are very good informations on them:

*

*A Cocoa-Based Frontend For Unity iPhone Applications

*Building a iOS Unity + UIView / UIViewController / Interface Builder
App

*An Experiment with iPhone Native UI and Unity 3 Pro

*Unity Iphone App Embebed in objectiveC app


text:
Q: Getting value of Response object in activiti bpnm xml I am totally new to Activiti. There are very few resources available for Activiti.
What I want is: A process should go back to previous step if rejected. Now, this rejection comes in the form of a value to an attribute in the JSON object (Using Spring Boot).
How can I use this value in the activiti xml file.
More:
    @RequestMapping(path = "/update", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    public void updateMessage(@RequestBody WorkflowUpdateRequest request) {
    //Use request object
}

Incoming json:
{
    "landId":"1001",
    "userName":"Admin",
    "requestApproved":"false"
}
How do I use this "requestApproved" value here??
<sequenceFlow id="flow3" sourceRef="usertask2" targetRef="endevent1">

 <conditionExpression xsi:type="tFormalExpression">
      <![CDATA[${requestApproved== 'true'}]]>
    </conditionExpression>
        </sequenceFlow>


text:
Q: ANT release errors I'm trying to compile my app to a release build using ant release
I followed the procedure and generated build.xml using
$ANDROID_HOME/tools/android update project --name MyProject -p .
Both $ANDROID_HOME and $JAVA_HOME are exported correctly.
I saved ant.propertieswith a valid keystore file and alias
Following this, I tried to execute the command ant clean, which runs fine and exits with BUILD SUCCESSFUL message.
When I try to do an ant release, that's when the problem happens. I get a bunch of javac compile errors
-compile:
    [javac] Compiling 89 source files /Users/kishu27/Developer/projects/MyProject/bin/classes
    [javac] /Users/kishu27/Developer/projects/MyProject/src/com/myproject/android/fragments/SettingsDetailFragment.java:20: cyclic inheritance involving com.myproject.android.fragments.SettingsDetailFragment
    [javac] public class SettingsDetailFragment extends SettingsFragment implements OnScrollListener {
    [javac]        ^
    [javac] /Users/kishu27/Developer/projects/MyProject/src/com/myproject/android/fragments/SettingsDetailFragment.java:22: modifier private not allowed here
    [javac]     private String cat;
    [javac]                    ^
    [javac] /Users/kishu27/Developer/projects/MyProject/src/com/myproject/android/fragments/SettingsFragment.java:28: modifier private static not allowed here
    [javac]     private static final String LOG_TAG = SettingsFragment.class.getSimpleName();
    [javac]                                 ^
    [javac] /Users/kishu27/Developer/projects/MyProject/src/com/myproject/android/fragments/SettingsFragment.java:29: modifier public static not allowed here
    [javac]     public static final String KEY_OPTIONS = LOG_TAG + ".Options";
    [javac]                                ^
    [javac] /Users/kishu27/Developer/projects/MyProject/src/com/myproject/android/fragments/SettingsFragment.java:30: modifier public static not allowed here
    [javac]     public static final String KEY_CAT = LOG_TAG + ".Cat";
    [javac]                                ^

Does anyone have any idea what might be wrong?


text:
Q: IE 6 is crashing when printing from my web application When clicking on print button the second time from my app, IE 6.0 is crashing.
Steps to reproduce: 1) Click on print Button and cancel the print dialog. 2) Click on print again. IE 6.0 crashes.
It works fine in IE 7 & 8.
Below is the stack trace i got from WinDbg.
0:000> g
(730.9e0): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000058 ebx=00000000 ecx=0160de40 edx=00000016 esi=0103f154 edi=00000000
eip=013556cd esp=001360a8 ebp=001360c0 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00250246
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\Program Files\Google\Google Toolbar\Component\GoogleToolbarDynamic_32_78F32466E61F1EEC.dll -
GoogleToolbarDynamic_32_78F32466E61F1EEC!DllCanUnloadNow+0x37501:
013556cd 3b30            cmp     esi,dword ptr [eax]  ds:0023:00000058=????????

0:000> kp
ChildEBP RetAddr
WARNING: Stack unwind information not available. Following frames may be wrong.
001360c0 01355830 GoogleToolbarDynamic_32_78F32466E61F1EEC!DllCanUnloadNow+0x37501
001360d4 01355851 GoogleToolbarDynamic_32_78F32466E61F1EEC!DllCanUnloadNow+0x37664
00136130 013dc77e GoogleToolbarDynamic_32_78F32466E61F1EEC!DllCanUnloadNow+0x37685
001361c0 01386059 GoogleToolbarDynamic_32_78F32466E61F1EEC!DllCanUnloadNow+0xbe5b2
001361e8 0137d30a GoogleToolbarDynamic_32_78F32466E61F1EEC!DllCanUnloadNow+0x67e8d
00136228 0137d374 GoogleToolbarDynamic_32_78F32466E61F1EEC!DllCanUnloadNow+0x5f13e
00136250 7c923ada GoogleToolbarDynamic_32_78F32466E61F1EEC!DllCanUnloadNow+0x5f1a8
001362d4 7c81caae ntdll!LdrShutdownProcess+0x14f
001363c8 7c81cb26 kernel32!_ExitProcess+0x42
001363dc 79fdc424 kernel32!ExitProcess+0x14
00136604 7a096786 mscorwks!SafeExitProcess+0x157
00136610 7a0979b9 mscorwks!EEPolicy::HandleFatalError+0x55
00136634 79f8e993 mscorwks!CLRVectoredExceptionHandlerPhase3+0xbc
00136668 79f8e835 mscorwks!CLRVectoredExceptionHandlerPhase2+0x20
0013669c 79ef4558 mscorwks!CLRVectoredExceptionHandler+0x10a
001366c8 79ef4755 mscorwks!CPFH_RealFirstPassHandler+0x607
001366ec 7c9032a8 mscorwks!COMPlusFrameHandler+0x15a
00136710 7c90327a ntdll!ExecuteHandler2+0x26
001367c0 7c90e48a ntdll!ExecuteHandler+0x24
001367c0 79fc0a7d ntdll!KiUserExceptionDispatcher+0xe
00136ad4 79fc0ab0 mscorwks!WKS::gc_heap::sweep_large_objects+0x114
00136af8 79f7640f mscorwks!WKS::gc_heap::mark_phase+0x1eb
00136b1c 79f76995 mscorwks!WKS::gc_heap::gc1+0x62
00136b30 79f766aa mscorwks!WKS::gc_heap::garbage_collect+0x253
00136b5c 79f78576 mscorwks!WKS::GCHeap::GarbageCollectGeneration+0x1a9
00136be8 79f75e1e mscorwks!WKS::gc_heap::try_allocate_more_space+0x15b
00136bfc 79f75eb9 mscorwks!WKS::gc_heap::allocate_more_space+0x11
00136c1c 79e732c1 mscorwks!WKS::GCHeap::Alloc+0x3b
00136c38 79e7d904 mscorwks!Alloc+0x60
00136c74 79e990c6 mscorwks!SlowAllocateString+0x29
*** WARNING: Unable to verify checksum for C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\7bffd7ff2009f421fe5d229927588496\mscorlib.ni.dll
00136d18 792e18ce mscorwks!FramedAllocateString+0xa1
00136d38 792e1a26 mscorlib_ni+0x2218ce
00136d50 792e1992 mscorlib_ni+0x221a26
00136d70 7974c62f mscorlib_ni+0x221992
00136d80 7974c73b mscorlib_ni+0x68c62f
00136da4 7974ba37 mscorlib_ni+0x68c73b
00136dc0 7974bf34 mscorlib_ni+0x68ba37
00136e24 7978c030 mscorlib_ni+0x68bf34
00136e58 7978bf91 mscorlib_ni+0x6cc030
00136e80 7978b972 mscorlib_ni+0x6cbf91
00136ed0 797d8ac6 mscorlib_ni+0x6cb972
00136ef8 797d8973 mscorlib_ni+0x718ac6
00136f1c 797d87ef mscorlib_ni+0x718973
00136f2c 797d7a9d mscorlib_ni+0x7187ef
00136f40 7978c168 mscorlib_ni+0x717a9d
00136f58 7978c08f mscorlib_ni+0x6cc168
00136f70 79e71b4c mscorlib_ni+0x6cc08f
00136f80 79e821f9 mscorwks!CallDescrWorker+0x33
00137000 79e96571 mscorwks!CallDescrWorkerWithHandler+0xa3
00137144 79e965a4 mscorwks!MethodDesc::CallDescr+0x19c
00137160 79e965c2 mscorwks!MethodDesc::CallTargetWorker+0x1f
00137178 7a136258 mscorwks!MethodDescCallSite::Call+0x1a
001373b0 79eab8e5 mscorwks!SecurityStackWalk::ReflectionTargetDemand+0x1ea
0013743c 79e905b5 mscorwks!AccessCheckOptions::DemandMemberAccess+0xb0
00137454 79e90544 mscorwks!ClassLoader::CheckAccess+0x8b
00137484 79eab960 mscorwks!ClassLoader::CanAccess+0x26
001374c4 79eab146 mscorwks!InvokeUtil::CheckAccess+0xa9
00137500 79eab2de mscorwks!InvokeUtil::CheckAccess+0x3a
00137558 79eac262 mscorwks!CanAccess+0xb3
001375c4 79eac328 mscorwks!PerformSecurityCheckHelper+0xb5
00137678 792d5281 mscorwks!ReflectionInvocation::PerformSecurityCheck+0xb8
001376a8 792d50be mscorlib_ni+0x215281
00137780 79f9816e mscorlib_ni+0x2150be
0013787c 79f9827b mscorwks!COMToCLRWorkerBody+0x1de
001378d8 79f986e1 mscorwks!COMToCLRWorkerDebuggerWrapper+0x37
00137abc 055ba5a1 mscorwks!COMToCLRWorker+0x52f
00137ae4 77553359 0x55ba5a1
00137b34 7deae63e ole32!OleSaveToStream+0x63
00137ba8 7deb0a75 mshtml!CObjectElement::SaveToDataStream+0x6a
00137dd0 7dd87e73 mshtml!CObjectElement::Save+0x6f
00137dec 7dd888f3 mshtml!CTreeSaver::SaveElement+0xd4
00137e8c 7dd9d1bc mshtml!CTreeSaver::Save+0x3a7
00138464 7dd9d7c7 mshtml!CMarkup::SaveToStream+0x104
00138488 7dd9df2f mshtml!CMarkup::SaveToStream+0x13f
00138ad8 7deacff1 mshtml!CMarkup::Save+0x278
0013cb0c 7deb29e3 mshtml!CFrameSite::Save+0x197
0013cb24 7dd87e73 mshtml!CIFrameElement::Save+0x15
0013cb40 7dd888f3 mshtml!CTreeSaver::SaveElement+0xd4
0013cbe0 7dd9d1bc mshtml!CTreeSaver::Save+0x3a7
0013d1b8 7dd9d7c7 mshtml!CMarkup::SaveToStream+0x104
0013d1dc 7dd9df2f mshtml!CMarkup::SaveToStream+0x13f
0013d82c 7dd759db mshtml!CMarkup::Save+0x278
0013d84c 7dd75f32 mshtml!CDoc::SaveToTempFile+0xe4
0013dd30 7dd361cd mshtml!CDoc::PrintHandler+0x2dc
0013e0e0 7dda1f06 mshtml!CDoc::ExecHelper+0x3f2
0013e10c 7dd81a78 mshtml!CWindow::print+0xa8
0013e124 7dcf0e19 mshtml!COmWindowProxy::print+0x3e
0013e130 7dcbeb03 mshtml!Method_void_void+0x17
0013e1b0 7dcbe99f mshtml!CBase::ContextInvokeEx+0x462
0013e1dc 7dcbe966 mshtml!CBase::InvokeEx+0x25
0013e244 7dcbddb2 mshtml!COmWindowProxy::InvokeEx+0x248
0013e26c 75c729d7 mshtml!COmWindowProxy::subInvokeEx+0x26
0013e2a4 75c72947 jscript!IDispatchExInvokeEx2+0xac
0013e2dc 75c731e5 jscript!IDispatchExInvokeEx+0x56
0013e34c 75c71c0a jscript!InvokeDispatchEx+0x78
0013e394 75c71211 jscript!VAR::InvokeByName+0xba
0013e3d4 75c711c6 jscript!VAR::InvokeDispName+0x43
0013e3f8 75c7311d jscript!VAR::InvokeByDispID+0xfd
0013e4b0 75c71123 jscript!CScriptRuntime::Run+0x176c
0013e4c8 75c72f89 jscript!ScrFncObj::Call+0x8d
0013e554 75c71b32 jscript!NameTbl::InvokeInternal+0xe0
0013e580 75c7311d jscript!VAR::InvokeByDispID+0xd4
0013e638 75c71123 jscript!CScriptRuntime::Run+0x176c
0013e650 75c70f8a jscript!ScrFncObj::Call+0x8d
0013e6c0 75c72642 jscript!CSession::Execute+0xa7
0013e7b0 75c724fe jscript!NameTbl::InvokeDef+0x179
0013e830 75c72e10 jscript!NameTbl::InvokeEx+0xcb
0013e860 7dcc41dd jscript!NameTbl::Invoke+0x55
0013e8f4 7dcc40e5 mshtml!CWindow::ExecuteTimeoutScript+0x85
0013e914 7dcc2562 mshtml!CWindow::FireTimeOut+0x40
0013e924 7dcc2529 mshtml!GWMouseProc+0x127
0013ea5c 7e418734 mshtml!GlobalWndProc+0x1e2
0013ea88 7e418816 USER32!InternalCallWinProc+0x28
0013eaf0 7e4189cd USER32!UserCallWinProcCheckWow+0x150
0013eb50 7e418a10 USER32!DispatchMessageWorker+0x306
0013eb60 75f9d875 USER32!DispatchMessageW+0xf
0013eb78 75fa5218 BROWSEUI!TimedDispatchMessage+0x33
0013edd8 75fa5389 BROWSEUI!BrowserThreadProc+0x336
0013ee6c 75fa5655 BROWSEUI!BrowserProtectedThreadProc+0x50
0013fef0 7e319834 BROWSEUI!SHOpenFolderWindow+0x22c
0013ff10 00402372 SHDOCVW!IEWinMain+0x133
0013ff60 00402444 iexplore!WinMainT+0x2de
0013ffc0 7c817077 iexplore!_ModuleEntry+0x99
0013fff0 00000000 kernel32!BaseProcessStart+0x23


text:
Q: Most concise way to get highest n numbers out of a map? I have the following already:
public enum InvoiceCurrency {
    EUR(
            s -> (s.contains("€") || s.contains("EUR"))
    ),
    USD(
            s -> (s.contains("$") || s.contains("USD"))
    );

    private final Predicate<String> predicate;

    InvoiceCurrency(final Predicate<String> predicate) {
        this.predicate = predicate;
    }

    public boolean matchesString(final String value) {
        return predicate.test(value);
    }

    public static EnumMap<InvoiceCurrency, Integer> createMapping(final Stream<String> valuesStream) {
        EnumMap<InvoiceCurrency, Integer> mapping = new EnumMap<>(InvoiceCurrency.class);
        mapping.replaceAll((k, v) -> 0);
        Stream<InvoiceCurrency> enums = Arrays.stream(InvoiceCurrency.values());
        valuesStream.forEach(
            s -> enums.forEach(
                e -> {
                    if (e.matchesString(s)) {
                        mapping.compute(e, (k, v) -> v++);
                    }
                }
            )
        );
        return mapping;
    }
}

private InvoiceCurrency calculateCurrency() {
    EnumMap<InvoiceCurrency, Integer> map = InvoiceCurrency.createMapping(data.words.stream().map(w -> w.content));
    InvoiceCurrency maximum = map.entrySet().parallelStream().  //how to continue?
}

This results in a mapping from the enum to the 'number of occurences', so EUR can be mapped to 10 and USD to 1. Possibly, the count may be the same.
Now have do I, as concise as possibly and with the ability to use java-8, get the InvoiceCurrency that belongs to the highest number? And is there a concise way to see that the top 2 of the sorted integer count actually has the same value?
I know I can program it with loops, etc., but I wish to rely on the java-8 spirit for the most maintainable code.

A: Simple example with a Map<String, Integer> but the same will work with your example. Prints the top 2 entries (b and c or d).
import static java.util.Collections.reverseOrder;
import static java.util.Comparator.comparingInt;
//...

Map<String, Integer> map = new HashMap<>();
map.put("a", 2);
map.put("b", 10);
map.put("c", 5);
map.put("d", 5);
map.put("e", 1);

map.entrySet().parallelStream()
        .sorted(reverseOrder(comparingInt(Map.Entry::getValue)))
        .limit(2)
        .forEach(System.out::println);

//or:   .forEachOrdered(System.out::println);
//to print in descending order

NOTE: from b129 on, you can also use sorted(comparingInt(Map.Entry::getValue).reversed()) instead of sorted(reverseOrder(comparingInt(Map.Entry::getValue))).


text:
Q: Auto restart node.js socket.io I am now experimenting on node.js socket.io and trying to restart the socket.io server once it reach a specific number of connection. Below is my code so far but, really don't know how to execute the restart command.
var connectionsLimit = 100

io.on('connection', function (socket) {

  if (io.engine.clientsCount > connectionsLimit) {
    socket.emit('restart', { message: 'server will restart' })

    return
  }

 io.on('restart', function(data) {

    //how to restart?
 });

})


text:
Q: Can I use same suricata instance for both IDS (for L3,4) and IPS (for L3,L4,L7)? I have a interface where traffic is flowing from internet to NGINX server to application server. I want to monitor (IDS) the traffic flowing between Internet and NGINX at L3,4 and IPS the traffic flowing out from NGINX to application server at L3,4,7.
Will it be possible to use same suricata instance to do the both?

A: Not at this time. There is work being done to support this use case using NFQUEUE (IPS) and NFLOG (IDS).
Ticket: https://redmine.openinfosecfoundation.org/issues/1604
But for now you will have to run 2 instances.


text:
Q: Ionic header hide content despite class "has-header" On an app with Ionic and AngularJs, I try to create a new template with a header. Unfortunately some content is hidden by the header.
Here is my code:

<link href="http://code.ionicframework.com/1.0.0/css/ionic.min.css" rel="stylesheet"/>

XXX

<ion-content class="has-header">

Sign in

    <button class="button button-block button-positive">Sign In</button>

Don't have an account?

    <button class="button button-block button-positive">Sign Up</button>

</ion-content>

Or JsFiddle: http://jsfiddle.net/cyef9sxs/1/
Thank you!

A: Well you need to specify the position absolute and width for the ionic element.
.has-header {
  top: 44px;
  position:absolute;
  width: 100%;
}


text:
Q: HTTP Status 500 - Internal Server Error in enterprise java beans deployment HTTP Status 500 - Internal Server Error when trying to deploy a web application using enterprise java beans in netbeans running glassfish server

HTTP Status 500 - Internal Server Error

Type: Exception report
Message: Internal Server Error
Description: The server encountered an internal error that prevented it from fulfilling this request.
Exception
javax.servlet.ServletException: Error instantiating servlet class com.registaration.registrationcontroller
root cause

com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class com.registaration.registrationcontroller
root cause

com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Remote ejb-ref name=com.registaration.registrationcontroller/registrationservice,Remote 3.x interface =com.registration.registrationserviceRemote,ejb-link=null,lookup=,mappedName=,jndi-name=com.registration.registrationserviceRemote,refType=Session into class com.registaration.registrationcontroller: Lookup failed for 'java:comp/env/com.registaration.registrationcontroller/registrationservice' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming}
root cause

javax.naming.NamingException: Lookup failed for 'java:comp/env/com.registaration.registrationcontroller/registrationservice' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.registaration.registrationcontroller/registrationservice,Remote 3.x interface =com.registration.registrationserviceRemote,ejb-link=null,lookup=,mappedName=,jndi-name=com.registration.registrationserviceRemote,refType=Session' .  Actual (possibly internal) Remote JNDI name used for lookup is 'com.registration.registrationserviceRemote#com.registration.registrationserviceRemote' [Root exception is javax.naming.NamingException: Lookup failed for 'com.registration.registrationserviceRemote#com.registration.registrationserviceRemote' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.registration.registrationserviceRemote#com.registration.registrationserviceRemote not found]]]
root cause

javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.registaration.registrationcontroller/registrationservice,Remote 3.x interface =com.registration.registrationserviceRemote,ejb-link=null,lookup=,mappedName=,jndi-name=com.registration.registrationserviceRemote,refType=Session' .  Actual (possibly internal) Remote JNDI name used for lookup is 'com.registration.registrationserviceRemote#com.registration.registrationserviceRemote' [Root exception is javax.naming.NamingException: Lookup failed for 'com.registration.registrationserviceRemote#com.registration.registrationserviceRemote' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.registration.registrationserviceRemote#com.registration.registrationserviceRemote not found]]
root cause

javax.naming.NamingException: Lookup failed for 'com.registration.registrationserviceRemote#com.registration.registrationserviceRemote' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.registration.registrationserviceRemote#com.registration.registrationserviceRemote not found]
root cause

javax.naming.NameNotFoundException: com.registration.registrationserviceRemote#com.registration.registrationserviceRemote not found
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.1 logs.

GlassFish Server Open Source Edition 4.1


text:
Q: How to create a floor function with a "step" argument I would like to create a function floor(number, step), which acts like :
floor(0, 1) = 0
floor(1, 1) = 1
floor(1, 2) = 0
floor(5, 2) = 4
floor(.8, .25) = .75

What is the better way to do something like that ?
Thanks.

A: You could do something like floor( val / step ) * step

A: what you want is basically the same as
step * (x // step)
isn't ?

A: Something along the lines of the code below ought to do the job.
def stepped_floor (n, step=1):
    return n - (n % step)


text:
Q: AWS AppFlow CloudFormation Template Size Limit - Mapping 500+ fields I am trying to create an AWS::AppFlow::Flow that can map a large number (500+) of fields from a Salesforce source object into an S3 object. The list of fields must be specified (rather than simply slurping all fields).
Please correct me if I'm wrong here, but it seems that my template MUST have a TaskType: Filter with a ConnectorOperator: PROJECTION and the full list of SourceFields I wish to copy.
Further, for each field, I seem to need a separate TaskType: Map defined for that field...
I used this example template to get started, with the relevant bits:
      Tasks:
        - TaskType: Filter
          SourceFields:
            - FieldA
            - FieldB
            - FieldN
          ConnectorOperator:
            Salesforce: PROJECTION
        - TaskType: Map
          SourceFields:
            - FieldA
          TaskProperties:
            - Key: SOURCE_DATA_TYPE
              Value: string
        - TaskType: Map
          SourceFields:
            - FieldB
          TaskProperties:
            - Key: SOURCE_DATA_TYPE
              Value: datetime
        - TaskType: Map
          SourceFields:
            - FieldN
          TaskProperties:
            - Key: SOURCE_DATA_TYPE
              Value: integer

Unfortunately, the list of fields I need to map is very large, and the template exceeds the maximum size allowed for CloudFormation templates (51200 bytes). I imagine most of the space is used by the repetitive Map task blocks for each field.
I am aware that you can upload the template file to S3, allowing a larger file size quota; however, even if I could pursue this option (I can't), the file size would also exceed the CloudFormation limit!
Is there another way to do this that would save template space?
I've found one or two mentions of a Map_all TaskType, which sounds promising on the surface; however, I can't find any concrete documentation on how to use it.
PS: For what it's worth, just the list of field names, comma-separated, is ~14KB.
PPS: I didn't design this schema, and I have no ability to change it.

A: i would recommend on excluding the columns thats not required , in the exclude column list , which will reduce the template size


text:
Q: Distribution of $\frac{\overline X - \overline Y - (\mu_1 -\mu_2)}{\sqrt{\frac1{m+n-2} [(m-1)*s_1^2+(n-1)*s_2^2](\frac1{m}+\frac1{n})}}$ I need to prove the following r.v has $t_{m+n-2}$ distribution
$$\frac{\overline X - \overline Y - (\mu_1 -\mu_2)}{\sqrt{\frac1{m+n-2} [(m-1)*s_1^2+(n-1)*s_2^2](\frac1{m}+\frac1{n})}}$$
where $\overline X$ and $s_1^2$ are the mean sample and the quasivariance  of a s.r.s from a population $N(\mu_1,\sigma)$ and $\overline Y$ and $s_2^2$ are the  mean sample and the quasivariance of a s.r.s from a population $N(\mu_2,\sigma)$ ( the samples are independent).
It's easy to see most of it. I can prove the numerator divided by $\sigma$ has distribution $N(0,1)$ and the denominator divided by $\sigma$ has distribution $\chi^2_{m+n-2}$. However, I need to prove numerator and denominator are independent, and I don't know how to. Of course, $\overline X, \overline Y, s_1^2, s_2^2$ are pairwise independent but that doesn't guarantee anything , does it?

A: We end up with  some $$U=\frac{\overline X-\overline Y-(\mu_1-\mu_2)}{\sigma\sqrt{\frac{1}{m}+\frac{1}{n}}}\sim N(0,1)$$
And some $$V=\frac{(m+n-2)s^2}{\sigma^2}\sim \chi^2_{m+n-2}$$
, where we have the pooled variance $$s^2=\frac{(m-1)s_1^2+(n-1)s_2^2}{m+n-2}$$
Now $U$ is a function of $\overline X$ and $\overline Y$, and $V$ is a function of $s_1^2$ and $s_2^2$. Moreover, $(\overline X,\overline Y)$ is independent of $(s_1^2,s_2^2)$ (this can be verified using MGFs since in fact $\overline X,\overline Y,s_1^2$ and $s_2^2$ are all mutually independent of each other). Since (measurable) functions of independent random variables/vectors are also independent of each other, it follows that $U$ and $V$ are independent.
The required statistic is of course $T=\frac{U}{\sqrt{V/(m+n-2)}}$.


text:
Q: "Zone in" on the coordinate with the lowest generated value? I have a function that generates a value for a coordinate (latitude, longitude). I want to find the coordinate on the world map that has the lowest value.
What's the best way to do this?
I don't think typical search algorithms (such as binary sort) would work considering that there are two planes to deal with and the accuracy can be improved each time (by adding more decimal places to the coordinates).
I've tried to obtain the lowest value through randomly generating coordinates but as you can guess it's too inefficient:
import random
shortest = [500, 0, 0]
while True:
    lat = (random.random()*180)-90
    lon = (random.random()*360)-180
    value = compute(lat, lon) #function which obtains the value
    if value < shortest[0]:
        shortest = [value, lat, lon]
        print(shortest)


text:
Q: Solving $x^2 (x-y)^2 = x^2 - y^2$ using implicit differentiation I have a test tomorrow and I am doing homework to review and study. The problem is to differentiate
$$
x^2 (x-y)^2 = x^2 - y^2.
$$
I tried multiple times; however, every time I try I get the incorrect answer. It would be greatly appreciated if somebody could show me the steps on how to get the answer. (No full answer please; I still want to learn).
The answer according to the book is
$$
\frac{-2x^3 + 3x^2y - xy^2 + x}{x^y - x^3 + y}.
$$

A: $\frac{d}{dx}[x^2(x-y)^2 = x^2 - y^2]$
$\Rightarrow 2x(x-y)^2 + x^2\cdot 2(x-y) \cdot (1-\frac{dy}{dx}) = 2x - 2y\cdot\frac{dy}{dx}$
$\Rightarrow 2x^3-4x^2y + 2xy^2 +2x -2x\frac{dy}{dx}-2y + 2y\frac{dy}{dx}= 2x -2y\frac{dy}{dx}$
$\Rightarrow 2x^3 - 4x^2y + 2xy^2 - 2y = (2x-4y)\frac{dy}{dx}$
$\frac{dy}{dx}=\frac{x^3 - 2x^2y+xy^2 -y}{x-2y}$


text:
Q: "Property description must be an object error" in non debug mode while executing command react-native run-android I have this react-native project and its been running fine for the past 2 months but now I am getting an error "Property description should be and object" while running the build on android in a non-debug mode. It works very well in debug-mode and on IOS. Can somebody please guide? here is my package.json
Tried downgrading redux to 4.0.0 and put resolutions for babel in package.json. But nothing works and the error persists.
  "react-native": "0.58.4",
  "react-native-action-picker": "^1.0.2",
  "react-native-base64": "0.0.2",
  "react-native-cli": "^2.0.1",
  "react-native-color-palette": "^2.0.2",
  "react-native-confirmation-code-input": "^1.0.4",
  "react-native-customized-image-picker": "^0.1.5",
 "react-native-vector-icons": "^6.6.0",
  "react-navigation": "^2.14.2",
  "react-redux": "^6.0.1",
  "redux": "^4.0.1",
  "redux-logger": "^3.0.6",
  "redux-persist": "^5.10.0",
  "redux-promise": "^0.6.0",
  "redux-thunk": "^2.3.0",

A: update npm. redux 4.0.4 work for me

A: [Just a workaround in case you can't afford to update dependency]
I got the same error in redux, I solved it.
Simply go to: node_modules/redux/lib/redux.js
and replace the line:
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(arguments[i], key));

to this:
var descriptor = Object.getOwnPropertyDescriptor(arguments[i], key);
    if (descriptor) {
      Object.defineProperty(target, key, descriptor);
    }


text:
Q: CocoaPods already installed but display error message not installed once more I'm a new in flutter, I bought a new MacBook Pro BigSur and I try to install flutter.
I have a problem with CocoaPods, I did evrything and finally I successfully installed as you can see in my flutter doctor. But the problem now, when I running the simulator, I get the same message error, CocoaPods not installed or invalid state.... I don't understand this situation and how must I do now ?
please help me ....
here my flutter doctor ..
[✓] Flutter (Channel stable, 2.8.1, on macOS 11.6.2 20G314 darwin-x64, locale
    en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✗] Chrome - develop for the web (Cannot find Chrome executable at
    /Applications/Google Chrome.app/Contents/MacOS/Google Chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[✓] Android Studio (version 2021.1)
[!] Android Studio
    ✗ Android Studio not found at
      /Applications/android-studio-2021.1.1.20-mac.dmg/Contents
[✓] VS Code (version 1.63.2)
[✓] VS Code (version 1.63.2)
[✓] Connected device (1 available)

! Doctor found issues in 2 categories. ```

Error message :

``` Warning: CocoaPods not installed. Skipping pod install.
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
  For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

CocoaPods not installed or not in valid state.```

successfully installation message :

``` Fetching cocoapods-1.11.2.gem
Successfully installed cocoapods-1.11.2
Parsing documentation for cocoapods-1.11.2
Installing ri documentation for cocoapods-1.11.2
Done installing documentation for cocoapods after 2 seconds
1 gem installed. ```

A: Try: sudo arch -x86_64 gem install ffi
And then run: arch -x86_64 pod install
You would also need to update your podfile in the iOS folder, uncomment the second line and replace '9.0' with '10.0'
It should work.

A: If you're using Android Studio, this is an issue that users have been getting with the new "Bumblebee" release 2021.1.1 that just came out.
https://github.com/flutter/flutter/issues/97251
Workaround for now is to launch Android Studio using the command line like this:
open /Applications/Android\ Studio.app

A: export PATH="/usr/local/lib/ruby/gems/3.0.0/bin:$PATH"
Setting the path to the latest version of Ruby & then opening the Application directly from cmd line/terminal fixed it for me.
open /Applications/Android\ Studio.app


text:
Q: How can high energy, cosmic gamma photons reach the earth, when they are capable of creating (lepton) particle anti-particle pairs? In this article we can read that energy of high energy gamma rays which have an astronomical source (for example gamma ray bursts) is about $10(TeV)$. This is more than enough for the creation of an electron anti-electron pair because the electron has a tiny rest energy [of about ${0,511}(MeV)$]. Also, the rest energies of the muon and the tau are small compared with the high energy of the photon. Then why aren't all the gamma photons (by means of the Feynman diagram, depicted below, where two real gamma photons go in and a real electron and a real anti-electron go out) converted to pairs of particle anti-particle pairs, so we can't receive the gamma photons on earth?
Are the electrons and anti- electron recombining again to produce a gamma ray?

A: The two gammas in your diagram have to interact, i.e. coincide at  a volume within the heisenberg uncertainty  so as to have a measurable probability of interaction.

gamma rays which have an astronomical source (for example gamma ray bursts) is about 10(TeV).

The crux here is the word "source". If it is a point source , or an approximately point source, the paths of the rays will diverge due to the geometrical nature of a point source:

Thus those ten GeV gammas will not cross each other's path so as to interact.
It is true that astronomical sources will not be point sources, except approximately, but the arguments hold, maybe gammas from an extended source might cross paths, but the ones at the edges will follow the law above, and those will be the gammas that survive and reach us.


text:
Q: Pass Inputs to Function to get Predictions I am trying to deploy a model via a REST API function (new to it) to apply predictions to unlabeled data on the fly.
I do not understand how to map my input features to the args (or maybe it should be kwargs) function
Using this simple example as a guide
# Read the fitted model from the file model.pkl
# and define a function that uses the model to
# predict petal width from petal length

import pickle
import numpy as np

model = pickle.load(open('model.pkl', 'rb'))

def predict(args):
  iris_x = np.reshape(float(args.get('petal_length')), (-1,1))
  result = model.predict(iris_x)
  return result[0][0]

predict({'petal_length': 3})
0.88346654397265678

# doing it manually via dataframe

row = {'petal_length': 3}
df = pd.DataFrame([row])
result = model.predict(df)
result[0][0]
0.88346654397265678

I have a dataframe as input with 13 features with mixed data types that are plugged into a sklearn classification pipeline performing FE techniques like scaling, ohe, and tfidf ... the api function does not work and looks like something to do with the shape based on the error ... it seems the input format has to be a dataframe because of the sklearn pipeline
model = joblib.load(persisted_model)

def preds(args):
  unlabeled_X = np.reshape(args\
                 .get('c1',\
                     'c2',\
                     'c3',\
                     'c4',\
                     'c5',\
                     'c6',\
                     'c7',\
                     'c8',\
                     'c9',\
                     'c10',\
                     'c11',\
                     'c12',\
                     'c13'), (-1,13))
  result = model.predict(unlabeled_X)
  return result[0][0]

# using dummy data as example
preds({
  "c1": "some text",
  "c2": "more text",
  "c3": 0,
  "c4": 0,
  "c5": 0,
  "c6": "cat var",
  "c7": "cat var",
  "c8": "cat var",
  "c9": "flag",
  "c10": 0,
  "c11": 0,
  "c12": 0,
  "c13": 0
})

TypeError: get expected at most 2 arguments, got 13

If I try the manual approach via dict to df it works
# using dummy data as example
row = {
  "c1": "some text",
  "c2": "more text",
  "c3": 0,
  "c4": 0,
  "c5": 0,
  "c6": "cat var",
  "c7": "cat var",
  "c8": "cat var",
  "c9": "flag",
  "c10": 0,
  "c11": 0,
  "c12": 0,
  "c13": 0
}

df = pd.DataFrame([row])
model.predict(df)[0]
'CLASS1'

My main question is how do I get the api function to work so it can accept new data to make predictions?
Perhaps the function can be modified to transform the dictionary input to a dataframe so the API can be called?
Thanks!


text:
Q: Threading cleanup (disposing) I am referring to this Simple threading event example .
More specifically, this piece of code:
for i in range(4):
     t = threading.Thread(target=worker)
     t.daemon = True  # thread dies when main thread (only non-daemon thread) exits.
     t.start()

From what I understand this created 4 threads that will be used. As I am more familiar with C++ and C# I am wondering about cleanup. Can I just leave these threads open or is there a proper way of 'closing'/disposing them? Please do not misread this as wanting to kill the thread. I am just wondering that when all work is completed is there a proper way of cleaning up.


text:
Q: Data parsed from an XML file renders %22% for " and %27% for '...how do I fix this? I am parsing data from an XML file and the XML has the character ' encoded as %27% and the character " as %22%. Those characters render in my HTML, so I end up with data like this:

Pike%27%s Peak

or

this is my %22%Quote%22%

I attempted to perform a string.replace(), but to no avail. I am such a newbie when it comes to parsing XML with javascript. I'm sure my code is way off, but that's why I'm posting this quest...can anyone help me out? Here's the code for my attempted string.replace():
function xmlencode(string) {
return string.replace(/'%27'/g,'\'').replace(/'%22'/g,'\"');

}
Your feedback is much appreciated.
Thanks,
Carlos

A: That's some proprietary encoding, that's nothing that is usually used in an XML file. Because of that, there is no standard way of decoding it.
You have some extra apostrophes in your function that keeps it from working:
function decode(string) {
  return string.replace(/%27%/g,"'").replace(/%22%/g,'"');
}

You can parse the hex code between the percent signs to get a function that works for any such entity:
function decode(string) {
  return string.replace(/%[\da-f]{2}%/gi,function(m) {
    return String.fromCharCode(parseInt(m.substr(1,2), 16));
  });
}

Example:
alert(decode("%49%%74%%20%%77%%6f%%72%%6b%%73%%21%"));


text:
Q: Corona SDK Random Spawn multiple objects and keep track of each object to remove on collision I am working on a small zombie game, I would like to spawn zombies randomly and keep track of them so if they collide with a bullet object then they are removed however if they collide with the hero then they attack.
I get the logic to remove them or make them attack on collision, however I am not sure how to randomly spawn multiple objects on screen and keep track of them.
I am not asking for anyone to write code for me, just need guidance on the task.
Thanks in advance.

A: What you can do is get the display.viewableContentWidth and display.contentHeight (varies depending on your config.lua, you can view more here).
First set math.randomSeed(os.time) on the main.lua file REASON is we want to a different random everytime we open the app. you can view more here.
Second Store the values of display.viewableContentWidth and display.contentHeight on a variable lets say x and y and create a table namely zombies and a counter
Third Create a function that will be called everytime you want to spawn the zombies like:
local x = display.contentWidth
local y = display.contentHeight
local zombies = {}
local zombieCounter = 0

showZombies = function()

    --Gives a value from 1 to x
    local xVal = math.random(x)

    --Gives a value from 1 to y
    local yVal = math.random(y)

    --spawn your zombie
    zombies[zombieCounter] = display.newImageRect ("yourZombie.png", 70,90)
    zombies[zombieCounter].x = xVal
    zombies[zombieCounter].y = yVal
    --set a tag for this zombie namely "myName"
    zombies[zombieCounter].myName = zombieCounter
    zombieCounter = zombieCounter + 1
end

fourth on your collision function (assuming you have all the listeners in)
zombieCollision = function(event)

    --DO WHAT YOU NEED TO DO WITH YOUR ZOMBIE
    --CALL THE COLLIDED ZOMBIE
    local zombieNUmber = event.other.myName
    print("The number of the zombie is "..zombies[zombieNumber].myName)

end

The trick here to track the zombies is the zombies[zombieNumber].myName inside your collision function.


text:
Q: JUnit-Test started with Ant gives a "ClassNotFoundException" This Ant-Target works:
<target name="run">
    <java jar="dist/FBChatSoft.jar" fork="true"/>
</target>

so "dist/FBChatSoft.jar" is the correct path to the jar.
But the following target doesn't work. The Path to the *Test.java is also correct.,
<target name="junit" depends="jar">
    <mkdir dir="junitreport"/>
    <junit printsummary="yes">
        <classpath>
            <path location="dist/FBChatSoft.jar"/>
        </classpath>

        <formatter type="xml"/>

        <batchtest fork="yes" todir="junitreport">
            <fileset dir="src/fbchatsoft/client/" includes="*Test.java"/>
        </batchtest>
    </junit>
</target>

<target name="junitreport">
    <junitreport todir="junitreport">
        <fileset dir="junitreport" includes="TEST-*.xml"/>
        <report todir="junitreport"/>
    </junitreport>
</target>

In the JUnitReport I can read:

PropertiesHelperTest
java.lang.ClassNotFoundException:
  PropertiesHelperTest
  at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
  at java.lang.Class.forName0(Native Method)
  at java.lang.Class.forName(Class.java:186)

You can find the whole code at: https://bitbucket.org/michaelkohler/fbchatsoft/src

A: You need to use **/*Test.java in order to include files recursively.
See the fileset and directory-based tasks documentation.

A: I edited my build.xml and now it looks like this:
    <?xml version="1.0" encoding="UTF-8"?>
<project name="FBChatSoft" default="default" basedir=".">
    <description>Builds, tests, and runs the project FBChatSoft.</description>

    <import file="nbproject/build-impl.xml"/>

    <import file="nbproject/profiler-build-impl.xml"/>

    <target name="clean">
        <delete dir="dist"/>
    </target>

    <target name="compile">
        <mkdir dir="build/classes"/>
        <javac srcdir="src" destdir="build/classes"/>
    </target>

    <target name="jar">
        <mkdir dir="dist"/>
        <jar destfile="dist/FBChatSoft.jar" basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="fbchatsoft.client.FBChatSoft"/>
        <attribute name="Class-Path" value="lib/smack.jar lib/junit-4.5.jar"/>
            </manifest>
        </jar>
    </target>

    <target name="run">
        <java jar="dist/FBChatSoft.jar" fork="true"/>
    </target>

    <target name="junit" depends="jar">
        <mkdir dir="junitreport"/>
        <junit printsummary="yes">
            <classpath>
                <pathelement location="build/classes/"/>
            </classpath>

            <formatter type="xml"/>

            <batchtest todir="junitreport">
                <fileset dir="src/" includes="**/*Test.java"/>
            </batchtest>
        </junit>
    </target>

    <target name="junitreport">
        <junitreport todir="junitreport">
            <fileset dir="junitreport" includes="TEST-*.xml"/>
            <report todir="junitreport"/>
        </junitreport>
    </target>
</project>

Then I added the newest junit package to /usr/share/ant/lib and now it works!


text:
Q: Read analog input from Arduino Uno Wifi Wire/TWI/I2C pins (A4 & A5) I recently got an Arduino Uno Wifi (flashed it with the Wifilink firmware to support UDP) and I have created a simple sketch to read analog values from a flex sensor.
I am using the code below (copy paste from the official website)
const int FLEX_PIN = A4; // Pin connected to voltage divider output

// Measure the voltage at 5V and the actual resistance of your
// 47k resistor, and enter them below:
const float VCC = 4.98; // Measured voltage of Ardunio 5V line
const float R_DIV = 47500.0; // Measured resistance of 3.3k resistor

// Upload the code, then try to adjust these values to more
// accurately calculate bend degree.
const float STRAIGHT_RESISTANCE = 37300.0; // resistance when straight
const float BEND_RESISTANCE = 90000.0; // resistance at 90 deg

void setup() {
  Serial.begin(9600);
  pinMode(FLEX_PIN, INPUT);
}

void loop() {
  // Read the ADC, and calculate voltage and resistance from it
  int flexADC = analogRead(FLEX_PIN);
  float flexV = flexADC * VCC / 1023.0;
  float flexR = R_DIV * (VCC / flexV - 1.0);
  Serial.println("Resistance: " + String(flexR) + " ohms");
  // Use the calculated resistance to estimate the sensor's
  // bend angle:
  float angle = map(flexR, STRAIGHT_RESISTANCE, BEND_RESISTANCE, 0, 90.0);
  Serial.println("Bend: " + String(angle) + " degrees");
  Serial.println();
  delay(500);
}

The code does not work in the Arduino Uno Wifi: it does not show any change in the bend degrees. However, it works in another Arduino Uno I have for testing.
Also I made a test and I found out that pins 4 and 5 in Arduino Uno Wifi produce current for some reason even with an empty script, capable of lighting a LED (while pins 0,1,2,3 do not light it up).
The same applies for the values for the sensors. For example if I put the flex sensor in analog pin 0 then the values change when I bend it (e.g. 362 read not bend and 600 bend, which is fine).
On the other hand when I put the pin of the sensor in A4 or A5 there is a change from 1023 (starting value) to 982 and it won't change no matter if I bend the sensor.
I was recently informed that those pins are Wire/TWI/I2C pins. Is there any way i can read analog input from those pins?
Also posted in Arduino forums link

A: 'WiFi' is connected to those pins.
pins A4 and A5 are Wire/TWI/I2C pins and there is the additional UART SC16IS750 connected to which the esp8266 is connected on Uno WiFi


text:
Q: I am trying to make a main class in processing (java) using IntelliJ I am currently using processing in IntelliJ. Usually when i use processing when i create a file it starts off as a sort of "main project" then i can create new classes.
However in intelliJ, I am starting off with a class, and making more classes. So then the global variables i use in main part of the program won't pass to the classes.
for example in processing i do this
global variables
classes
void setup()
{
   code....
}
void draw()
{
   code...
   calling classes

}

then in the class
class example
{
   void example2()
   {
     code using global variable
   }
}

however in intellij i start off with
import processing.core.PApplet;

    public class program
    {
  global variables
    classes
    void setup()
    {
       code....
    }
    void draw()
    {
       code...
       calling classes

    }

Then when i go to make class it doesnt get the global variables.
Anyone know?

A: Assuming you have the processing core.jar file somewhere on your classpath, a basic processing sketch would look like this:
import processing.core.PApplet;

public class MySketch extends PApplet {

    @Override
    public void setup() {
    }

    @Override
    public void draw() {
    }

    public static void main(String[] args) {
        PApplet.main(new String[] { MySketch.class.getName() });
    }

Getting it set up to work in intellij can be difficult due to the fact that you need the gluegen-rt and jogl libraries on the classpath as well.  Processing uses those libraries to do the actual rendering.
If you're familiar with maven, I've created a tool to let you install the processing dependencies and all the contributed libraries into your local maven repo. It's called processing-deps
Instructions for gettting that set up are in the README of that project.
But basically you'll end up with pom.xml file that has at bare-minimum this in it to get the the dependencies pulled in:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>my-group-id</groupId>
<artifactId>my-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.processing</groupId>
        <artifactId>processing-core</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.jogamp.gluegen</groupId>
        <artifactId>gluegen-rt-main</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.jogamp.jogl</groupId>
        <artifactId>jogl-all-main</artifactId>
        <version>2.2.4</version>
    </dependency>
</dependencies>


text:
Q: Composer: multiple vendor directories (zend seperate dir than doctrine,...) I've new to composer and I searched a few hours on the internet to find a solution for my problem, I've found one but can't get it to work so it's probably me.
I'm starting a new project with zend framework 1.12.3 and some extra vendors like doctrine. I don't mind that doctrine, phpunit, ... are installed in the default /vendor (or if I set another) but I rather have Zend on library/Zend instead of vendor/zendframework/....
I'm new to composer so I could've missed something.
Original:
{
    "name": "Awesome",
    "require": {
        "zendframework/zendframework1": "1.12.3",
        "doctrine/orm": "2.3.4",
        "doctrine/dbal": "2.3.4"
    },
    "require-dev": {
        "phpunit/phpunit": "3.7.21",
        "mockery/mockery": "dev-master@dev"
    }
}

I also tried it with https://github.com/composer/installers
{
    "name": "Awesome",
    "require": {
        "composer/installers": "~1.0"
        "zendframework/zendframework1": "1.12.3",
        "doctrine/orm": "2.3.4",
        "doctrine/dbal": "2.3.4"
    },
    "require-dev": {
        "phpunit/phpunit": "3.7.21",
        "mockery/mockery": "dev-master@dev"
    },
    "extra": {
        "installer-paths": {
            "library/Zend": ["zendframework/zendframework1"]
        }
    }
}

If it's a too big hastle to do it I can install zend locally so that's not a problem but it would be nice to do it with composer at once.

A: As explained in the comments, its not possible to install different packages in different(custom) locations.
the installer-paths does not work, as the zend package is not of a supported type (I think this works only for wordpress packages)
For your problem this is not a real problem. Zend Server sure does nothing special, only because the libraries are placed in this specific place. Also they had enough time to fix things for composer, if they really had some.
But, even if its not a solution for placing the Zend framework in this specific place, its possible to have multiple composer.json in different directories. You only need to add both autoload.php files. Thats no problem, as composer supports autoloading for multiple usage as this.


text:
Q: Numerically solving the Schrodinger equation via finite difference This is not strictly a question about physics but about the numerical solution to
a physics problem. I am solving the Schrodinger equation via finite difference, via the substitution

I solved this using Mathematica for the case that $V(x) = 0$ and get the correct eigenvalues. I find the eigenvectors and plot them via
d2dx[n_] :=
  SparseArray[{Band[{1, 1}] -> -2, Band[{1, 2}] -> 1,
     Band[{2, 1}] -> 1}, {n, n}]/(1/n^2);
evecs[n_, m_] := Last@Eigenvectors[N[-d2dx[n]], m]
ListPlot[evecs[100, 1], Joined -> True]
ListPlot[evecs[100, 2], Joined -> True]
ListPlot[evecs[100, 3], Joined -> True]

But the results look like this:

The profiles are correct but of course it shouldn't be oscillating in this way. Why am I seeing these oscillations and how do I get the correct eigenvectors?

A: The problem is in the Mathematica code, the answer can be found here: https://mathematica.stackexchange.com/questions/173669/solving-the-schrodinger-equation-by-exact-diagonalization/173672#173672.
The eigenvectors are organized from greatest eigenvalue to least. The solution is to reverse the list of eigenvectors then take the m'th vector from the list. It can be fixed by replacing with
evecs[n_, m_] := Reverse[Eigenvectors[N[-d2dx[n]]]][[m]]


text:
Q: Why doesn't my backend update the keywordData column in database My idea is to have the ability to add multiple strings at keyword, I've been told to use foreign keys and so am I. But I can't figure out why it's not working properly. Any ideas?
My code is as follows
user.js
var User = sequelize.define('user', {
  username: Sequelize.STRING,
  myhash: Sequelize.TEXT,
  mysalt: Sequelize.STRING,
  keyword: Sequelize.STRING
});

var keywordData = sequelize.define('keywordData', {
  keywords: Sequelize.STRING
})

User.hasMany(keywordData)
keywordData.belongsTo(User)

User.js
router.post("/newkeyword", function(req, res) {
  keywordData.update(
    {keywordData: req.body.newkeyword},
    {where: {id: req.user['id']}}
  )
})

A: You forgot to indicate a foreignKey option in the second association definition as well as create an auto-increment id for keywordData model.
var keywordData = sequelize.define('keywordData', {
  id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true, },
  keywords: { Sequelize.STRING }
})

Hence, your association should be like this:
User.hasMany(keywordData)
keywordData.belongsTo(User, {foreignKey: 'keyword', targetKey: 'keywords' })

Also you an refer this document for more details.


text:
Q: Spring - @Cacheable annotation not working on java method When adding @Cacheable annotation on a method performing a simple Java code, on application execution, breakpoint inside the method is triggered. Does this mean that the result was not cached?
Configuration used:
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=[port]
spring.cache.redis.time-to-live=[some value]

Note that the @Cacheable is working fine in the same project when put before a database method

A: Yes, this means that the result was not cached.

In this case, if any of the caches contains the required result, the result is returned and the method is not invoked.

Source
In order to make use of a cache, the method must be invoked with the same parameters again. However, there are limitations, as this answer points out.

A: To make it work, we need to call the method annotated with @Cacheable from a different Java class. Otherwise it doesnt work.


text:
Q: How can I use .NOTPARALLEL in makefile only on specific targets? I have 5 labels in Makefile:
all: label1 label2 label3 label4 last_label

I want last_label to be done last, and I want to use make -j. If I use .NOTPARALLEL, it will make all of them NOTPARALLEL, any suggestion on how to do that?

A: If the reason last_label needs to run last is that it needs data from the other labels, the best approach would be to tell make about that dependency:
all: last_label

last_label: label1 label2 label3 label4

If there's not a true dependency (i.e., if you don't want last_label to be rebuilt if one of the others changes), and if you're using GNU Make, you can specify these as "order-only" dependencies--make will just make sure they exist before last_label is built:
all: last_label

last_label: | label1 label2 label3 label4

A: Create a target specifying the four targets that can be executed in parallel & include this and last_label in the all target:
intermediate: label1 label2 label3 label4

all:
        $(MAKE) intermediate
        $(MAKE) last_label

This would execute the targets specified within intermediate in parallel, but intermediate and last_label would be forced consecutively.
(Note that the leading space before $(MAKE) is a TAB character.)


text:
Q: get JOIN table as array of results with PostgreSQL/NodeJS I'm creating an app where users are able to create questions, and others can upvote/downvote them.
The following is a part of my sql schema:
CREATE TABLE "questions" (
  id            SERIAL,
  content       VARCHAR(511) NOT NULL,
  created_at    TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
  CONSTRAINT    pk_question PRIMARY KEY (id)
);

CREATE TABLE "votes" (
  id            SERIAL,
  value         INT,
  question_id   INT NOT NULL,
  CONSTRAINT    pk_vote PRIMARY KEY (id),
  CONSTRAINT    fk_question_votes FOREIGN KEY (question_id) REFERENCES questions (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE
);

What I would like to have is Postgres giving me each question with an array of votes, like that:
[{ // a question
  id: 1,
  content: 'huh?',
  votes: [{ // a vote
    id: 1,
    value: 1
  }, { // another vote
    id: 2,
    value: -1
  }]
}, { /*another question with votes*/ }]

I looked at aggregate functions (like array_agg()) but it gave me only the values. A JOIN gave me a question joined with a vote, and would force me to do server side operations, which I would prefer not to.
Is there any way to do that? Is my reasoning regarding what I want to obtain wrong?
Thanks for your time.

A: Please think simple way, May be I am right, I use knex js
 let allpost = knex
        .select([
            'questions.id',
            'question.content',
            knex.raw('json_agg(v.*) as votes')
        ])
        .from('questions')
        .leftJoin('votes as v', 'questions.id', 'v.question_id')
        .groupBy('questions.id');

A: This is easy to do with pg-promise:
function buildTree(t) {
    const v = q => t.any('SELECT id, value FROM votes WHERE question_id = $1', q.id)
        .then(votes => {
            q.votes = votes;
            return q;
        });

    return t.map('SELECT * FROM questions', undefined, v).then(a => t.batch(a));
}

db.task(buildTree)
    .then(data => {
        console.log(data); // your data tree
    })
    .catch(error => {
        console.log(error);
    });

The same as above, but using ES7 async/await syntax:
await db.task(async t => {
    const questions = await t.any('SELECT * FROM questions');
    for(const q of questions) {
        q.votes = await t.any('SELECT id, value FROM votes WHERE question_id = $1', [q.id]);
    }
    return questions;
});
// method "task" resolves with the correct data tree

API: map, any, task, batch

Related questions:

*

*Get a parents + children tree with pg-promise

*Conditional task with pg-promise

And if you want to use just a single query, then using PostgreSQL 9.4 and later syntax you can do the following:
SELECT json_build_object('id', q.id, 'content', q.content, 'votes',
    (SELECT json_agg(json_build_object('id', v.id, 'value', v.value))
     FROM votes v WHERE q.id = v.question_id))
FROM questions q

And then your pg-promise example would be:
const query =
    `SELECT json_build_object('id', q.id, 'content', q.content, 'votes',
        (SELECT json_agg(json_build_object('id', v.id, 'value', v.value))
         FROM votes v WHERE q.id = v.question_id)) json
    FROM questions q`;

const data = await db.map(query, [], a => a.json);

And you definitely will want to keep such complex queries in external SQL files. See Query Files.
Conclusion
The choice between the two approaches presented above should be based on the performance requirements of your application:

*

*The single-query approach is faster, but is somewhat difficult to read or extend, being fairly verbose

*The multi-query approach is easier to understand and to extend, but it is not great for performance, due to dynamic number of queries executed.

UPDATE-1
The following related answer offers more options, by concatenating child queries, which will give a much improved performance: Combine nested loop queries to parent result pg-promise.
UPDATE-2
Another example added, using ES7 async/await approach.

A: sql-toolkit does exactly this. It's a node library built for pg-promise which allows you to write regular native SQL and receive back properly structured (nested) pure business objects, without either having to split up the query or rewrite it with json_build_object.
For example:
class Article extends BaseDAO {
  getBySlug(slug) {
    const query = `
      SELECT
        ${Article.getSQLSelectClause()},
        ${Person.getSQLSelectClause()},
        ${ArticleTag.getSQLSelectClause()},
        ${Tag.getSQLSelectClause()}
      FROM article
      JOIN person
        ON article.author_id = person.id
      LEFT JOIN article_tags
        ON article.id = article_tags.article_id
      LEFT JOIN tag
        ON article_tags.tag_id = tag.id
      WHERE article.slug = $(slug);
  `;
  return this.one(query, { slug });
  // OUTPUT: Article {person: Person, tags: Tags[Tag, Tag, Tag]}
}

The select clause uses the business object "getSQLSelectClause" methods to save tedium in typing the columns, as well as ensure no collisions of names (nothing magical going on, and could just be written out instead).
The this.one is a call into sql-toolkits base DAO class. It is responsible for structuring the flat result records into a nice nested structure.
(Also notice that it is "one" which matches our mental model for the SQL. The DAO methods for one, oneOrNone, many, and any ensure their count against the number of generated top level business objects - not the number of rows the sql expression returns!)
Check out the repository for details on how to set it up on top of pg-promise. It's strictly an enhancement, and does not seek to abstract out pg-promise (you still set up pg-promise and can use it directly). (Disclamer, I am the author of sql-toolkit.)


text:
Q: Spark collect() result has incorrect length under standalone mode I run PySpark job in two way:

*

*Local mode through IPython

*Standalone mode through spark-submit

There is a RDD like:
training_vector = training.map(lambda x : ... ).filter(lambda x : ...).map(lambda x : ...)
Then I collect the different column,
sparseData = training_vector.map(lambda x : x[1]).collect()
targetData = training_vector.map(lambda x : x[2]).collect()
In IPython local mode, two printed values are the same, it's looks good.
print len(sparseData)
print len(targetData)
But, after I write the same code to a *.py file, and call spark-submit --master spark://ip:7077 *.py, the length of sparseData and targetData are slightly different. (ex. 165655 and 165662)
I've been tried several different datasets which ended with similar situation. The standalone cluster has two workers. Does anyone has the same problem?
Thanks.


text:
Q: Android: Action Bar being covered up by scrolling SurfaceView In my Android project, I have a SurfaceView nested inside a scrollview. If I scroll the scrollview down (such that part of it is obscured by the action bar), then select the action bar, then the SurfaceView will be brought to the front of the z-ordering, in front of the action bar as well.
Is there a way to bring the action bar to the front, or the SurfaceView to the back, in terms of z-ordering?

A: surfaceview.setZOrderOnTop(false)


text:
Q: Accessing tips for a venue using the FourSquare API with javascript I'm trying to get a list of tips for each venue when performing a search using the explore endpoint of the FourSquare API to see popular venues nearby.
I'm getting a JSON response with venues in it and can access most of its properties. However, I don't know how to access the tips object that is returned and is part of the venue object.
This is the page on FourSquare describing the response:
https://developer.foursquare.com/docs/responses/venue
This is what I'm using to access the venue object:
var venues = data['response']['groups'][0]['items'];

How do I access the tips object that is inside this?

A: Try this ;)
var items = data['response']['groups'][0]['items'];

var itemVenue = {}; /* It is an object item venue */
var itemTips = []; /* It is an array of item tips */

for(var item in items){
    itemVenue = items[item]['venue'];
    itemTips = items[item]['tips'];

    console.log('Venue Name: ', itemVenue.name);
    console.log('Item tips count: ', itemTips.length);

    /* Here we can loop all tips of  this item */
    var itemTip = {}; /* tip is an object */
    for(var tip in itemTips){
        itemTip = itemTips[tip];
        console.log('Tip text: ', itemTip.text);
    }
}


text:
Q: MySQL: how to find tables with column(s) that has Extra on update current_timestamp()? I am working on MariaDB V10.6, and just realized the following extra feature has been automatically added to a timestamp column in a table that I am working on.
on update current_timestamp()

With some help from Google, I was able to remove this unwanted extra from this table.
My question is, is there a way I can find all the table in the database that has this extra and remove them if they are not desired? Some sort of query that I can run against schema?
Thanks.

A: This is documented behaviour https://mariadb.com/kb/en/timestamp/ ,to find
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'YOURSCHEMA' AND EXTRA ='on update current_timestamp()';

To modify
alter table T modify column yourcolumn timestamp default 0;

But do you really want such a default? And is timestamp a suitable datatype for your purposes?
https://dbfiddle.uk/lnPEBnXq


text:
Q: Terminating app due to uncaught exception 'NSInvalidArgumentException', Thread 1: signal SIGABRT
Thread 1: signal SIGABRT
Terminating app due to uncaught exception 'NSInvalidArgumentException'

What does this error indicate?

A: This kind of error usually occurs when you try to pass an invalid argument as a parameter of the function. For example: if function requires non-nil value, but your variable is nil. See Apple documentation: https://developer.apple.com/documentation/foundation/nsinvalidargumentexception


text:
Q: Modify Settings system app More specifically I want to edit the Settings.apk and add more options. I'm unsure what the best approach to this is. I know how to convert the classes.dex to a .jar, but this doesn't seem like the way to go about accomplishing anything. At any rate, I'm really looking for some insight into this and advanced editing such as this. Someone knows how to, care to share?

A: Good thing the source to the stock Settings.apk is available:
https://android.googlesource.com/platform/packages/apps/Settings