text:
Q: Android: back-up messages and files programmatically Is it possible to back-up messages (SMS, MMS, email) and files (both on internal and external memory) then restore it using the same application without having to root/jailbreak the device? Either possible or not, what approach will I consider? [Kindly support with SSCCE, Thanks]
I am consider Android 2.2 (Froyo) as my base platform.

UPDATE: Jan. 30, 2013
Update my question

A: Is it too much of a longshot just to quote this question for the bounty?
How to Read MMS Data in Android?
Be sure to request the READ_SMS permission in your manifest.

A:
Is it possible to back-up messages (SMS, MMS, email) and files (both on internal and external memory) then restore it using the same application without having to root/jailbreak the device?

Not for all of that. In fact, not even for most of that.
Some things have public, documented means of loading and saving data, such as content providers documented in the Android SDK. Many of those are not designed to be used for backup/restore purposes. For example, if you tried to back up and restore contacts, since many of those contacts are actually synchronized from other sources (e.g., Facebook), you could screw things up royally.
Some things have undocumented, unsupported means of loading and saving data, such as the SMS content provider. Since you have no way of accurately predicting the behavior across multiple devices, trying to implement a backup/restore regime using these sources is impractical IMHO.
Everything else on internal storage is inaccessible to you, for obvious privacy and security reasons.


text:
Q: How to open existing VMs in VirtualBox? I recently got a new workstation and I moved my VirtualBox and VMWare Player VMs from the old PC to the new.
The VMWare Player VMs are a snap: you go to "File -> Open a Virtual Machine…", find the .vmx files from the old PC, and voila! It's up and running. All the required files apparently are in the same folder.
With VirtualBox there just doesn't seem to be a way to do that. Looks like VMs are tied to the original host in some magical/invisible way like registry entries, etc.

A: In the machine folder there is a *.vbox file. Drag it into the VM list in VirtualBox.

A: Importing existing virtual machines from another host into VirtualBox 4 and above on Windows hosts:

*

*Importing the vdi virtual disk:

*

*Go to the menu: *File ⇨ Virtual media manager.

*Drag and drop the [vm_name].vdi into the list.

*Adding the imported machine to the vbox manager list:

*

*Double-click on the [vm_name].vbox file in the directory of the vm, to add this machine to the vbox manager list.

*Double-click on the [vm_name].vbox inside the vbox manager list to start the appliance.

*Sidenotes:

*

*If the VM comes from an older vbox release, you will have an [vm_name].xml inside a sub directory instead of a [vm_name].vbox in the same directory as [vm_name].vdi.

*Copy the [vm_name].xml into the same directory as the [vm_name].vdi and rename it to [vm_name].vbox.

*Proceed with step 1.1 or 2.1 depending on the actions you have already taken.

A: The previous answers appear obsolete.
As of version 4 of the Oracle VirtualBox Manager, the "Add" option is hidden in the "Machine" menu (which is an operating system menu).  Just select Add, and navigate to the .vbox file you want.  This works great even if the vbox file is on an external drive: if the drive is later removed, the missing boxes are simply marked as 'inaccessible'.

A: If you want to use an existing virtual hard disk and 'open' it into Virtual Box - you need to go to "File > Virtual Media Manager" and select 'Add.'
Browse to your existing disk and select ok. This registers a disk with Virtual Box.  Now you need to attach this disk to a new or existing VM to actually use it.

A: By default, VirtualBox loads its configuration data from the folloing paths:

*

*On Windows, this is %HOMEDRIVE%%HOMEPATH%\.VirtualBox; typically something like C:\Documents and Settings\Username\.VirtualBox.

*On Mac OS X, this is $HOME/Library/VirtualBox.

*On Unix-like systems (Linux, Solaris), this is $HOME/.VirtualBox.

This means that machines are specific to the logged in user.  If you need to set a common place to store machines between different users you can override the default locatiion by setting the VBOX_USER_HOME environment variable.  VirtualBox will use the path in this variable as its store for VM configuration data.
See the VirtualBox help topic on VirtualBox configuration data for more information.

A: I'm not sure I see a problem here. In VirtualBox if you are opening a new VM (one you might have created on a different computer) you use File/Import Appliance and then browse for the file to open. After importation it can be found in the main VM panel.
If you created the VM on the same computer then it's already in the left pane of the main program window.
It may be different from what you're used to but I don't see why it would be frustrating...

A: If you are on a Unix-like computer you can do this:
find /path/to/vms -name "*.vbox" -exec VBoxManage registervm {} \;

You just need to remember to provide the entire path to the .vbox file. If you specify a relative path it will foolishly assume that it is relative to your home folder.
For example, I did this after rebuilding my workstation:
$ find /store/vm -name "*.vbox" -exec VBoxManage registervm {} \;

It found and re-registered all of my virtual machines.

A: On Mac OS X, simply open the .vbox file (from the Finder) and it gets added to the list of virtual machines.

A: Regarding errors like this:

Failed to open the hard disk V:\ProgramData\VirtualPC\CleanTesting_XP sp1.vhd. Parent medium with UUID {199e419e-a076-d811-81ef-8eeb0865d5ed} of the medium 'V:\ProgramData\VirtualPC\CleanTesting_XP sp1.vhd' is not found in the media registry ('C:\Users\Clay/.VirtualBox\VirtualBox.xml').

VirtualBox seems to cache the UUID associated with a virtual disk filename. It's not in the file the message says; it must be stored elsewhere. Apparently VirtualBox 4 doesn't support unregister/register disk commands any more.
In the end, I found if I changed the name of the VDI file, then it no longer matches the cached entry and VirtualBox doesn't complain.

A: On Debian, I edited ~/.VirtualBox/VirtualBox.xml and also the machine.xml I want to import : ~/VirtualBox VMs/$machine/$machine.xml
Close VirtualBox, add in VirtualBox.xml :
<MachineRegistry>
  <MachineEntry uuid="{$find-in-machine.xml}" src="/$fullpath-to-machine.xml"/>
</MachineRegistry>

Relaunch VirtualBox, add host-only network if needed, import ext pack if needed (https://www.virtualbox.org/wiki/Downloads), install virtualbox additions if needed : sudo apt-get install virtualbox-guest-additions-iso.
Start your VM.

A: In VirtualBox 4.3.8 running on a Win 7 host the solution works very smoothly by doubleclicking on the .vbox file of the machine - it even found the respective disks and associated them. Earlier I tried the registervm command line option but that complained about the attached hard disk not being found, as the documentation predicts. I then associated the .vdi virtual harddisk filetype with Virtualbox.exe, not sure if that helped.

A: None of the solutions above worked for me because I was trying to import a VDI file created under VirtualBox 3.1.6 into VirtualBox 4.32 running on a different machine.  This is a self contained file and there is no linkage to another VDI.  I kept getting the error:
Parent medium with UUID {a9dccef3-45f8-45ff-835e-a2b6e7279bac} of the medium
'c:\Disks\Windows.2003.R2.Enterprise.SQL.Express.192.168.56.222.Trusted.vdi'
is not found in the media registry

I even imported the same vdi under VirtualBox 3.1.6 and then tried to use VBoxManage clonehd again to see if I can get rid of the error but that did not work either.
In the end I simply edited .VirtualBox/VirtualBox.xml manually by adding
<HardDisk uuid="{43ea34ba-6d72-413e-8b37-32f475927ace}" location="C:/Disks/Windows.2003.R2.Enterprise.SQL.Express.192.168.56.222.Trusted.vdi" format="VDI" type="Normal"/>

(The uuid was obtained using VBoxManage showvhinfo under VirtualBox 3.1.6.)
And that finally solved the problem, i.e., I was able to create a new VirtualBox session using the vdi.
Hope this note will help those who runs into the same problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does this code cause a segmentation fault in Node.js v0.10.31 on a Mac? var foo, bar;
foo = new Uint8Array(20000);
bar = new Uint8Array(20000);
for (i = 0, j = 0; i < foo.length; i += 2, j += 2) {
    bar[i + 0] = foo[j + 0];
    bar[i + 1] = foo[j + 1];
    bar[i + 1] = foo[j + 1];
}

I realise that this routine makes no sense, especially the duplicated line, but this is a vastly reduced version of a real routine that has an actual purpose and appears to cause the same issue.
What I'm looking for is an explanation, if possible, on why it consistently crashes node.js.
For the record, it fails when i and j hit 11780.

A: Known bug in node 0.10.31, stick with 0.10.30 until the fix has been released.


text:
Q: Toggling div visibility for a graph I'm creating a flow graph using HTML, CSS and JS.
This is the fiddle:
http://jsfiddle.net/Newtt/HRedA/3/
This is my JS:
var flag = false;
function showdiv(id) {
    var div = document.getElementById(id);
    div.style.display = flag ? 'none' : 'block';
    flag = !flag;
}

It shows the root node of the graph and has to be clicked on to increase the levels.
As you can see there are some issues regarding the number of clicks required to show the divs that are hidden. I would like some help to fix two things:

*

*Number of clicks required

*When I open stage two and stage three, clicking on stage one should collapse all the open stages. However, with the current code, that doesnt seems to be working.

A: By setting the display-flag on the actual element you will avoid toggling a global state:
function showdiv(id) {
    var div = document.getElementById(id);
    var divFlag = div.expandedFlag == true
    div.style.display = divFlag ? 'none' : 'block';
    div.expandedFlag = !divFlag;
}

Or even simpler by using the elements display-state to decide if show/hide:
function showdiv(id) {
    var div = document.getElementById(id);
    div.style.display = (div.style.display == 'block') ? 'none' : 'block';
}

Including Part 2:
For part two. Including a structure containing children nodes for recursive hiding:
function showdiv(id) {
    var div = document.getElementById(id);
    var hideFlag = (div.style.display == 'block');
    div.style.display = (hideFlag ? 'none' : 'block');
    if(hideFlag){hideChildren(id)}
}

var children = {
    'two' : ['three-one','three-two']
};

function hideChildren(parent) {
    if(children[parent] !== undefined){
        for(var i = 0; i<children[parent].length; i++){
            var id = children[parent][i]
            document.getElementById(id).style.display = 'none';
            hideChildren(id)
        }
    }
}

A: For part 2 I would again use the DOM to your advantage. I agree that if you intend to generate these dynamically it's going to take some rework of the DOM structure and code.
For this example however, I created the following JSFiddle
http://jsfiddle.net/HRedA/15/

So the html above is reduced so it's not cluttering the page, but you'll notice that instead of all the elements being at the same level the nodes are structured inside of one another just like the flow diagram is structured. This means that when you hide a parent it will also hide it's children. This has the side-effect/feature of also remembering what you had expanded. For example if you hide the root and then show it again all your previous expansions will remain.
The reason this won't work dynamically is that all the lines and boxes are positioned by hand. I even had to move some around when they became children of other nodes.
Hope this helps.


text:
Q: Ошибка в compass "cannot load such file -- compass-normalize" Plumber в консоли выдал ошибку такого рода:
LoadError on line ["55"] of /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb: cannot load such file -- compass-normalize
Run with --trace to see the full backtrace

Устанавливал,compass-normalize, разными способами с инета, не помогло.
Подскажите как правильно уставновить compass-normalize в ubuntu
$ ruby -v
ruby 2.3.3p222 (2016-11-21) [x86_64-linux-gnu]

$ compass -v
Compass 1.0.3 (Polaris)
Copyright (c) 2008-2018 Chris Eppstein
Released under the MIT License.
Compass is charityware.
Please make a tax deductable donation for a worthy cause: http://umdf.org/compass

A: Решило проблему команда sudo gem install compass-normalize


text:
Q: Receiving a shared URL from another app into my Android app not working I am new to Android app development. I am trying to make an app which does the following:

*

*I open my app

*I leave my app and keep it running in the background

*I share a link to my app from another app (I tried YouTube)

*My app displays the link on its TextView.

And I am following this guide: https://developer.android.com/training/sharing/receive#java
However, when I share the link to the app, the TextView is not getting updated. In fact, the link is not even being received by the intent in the first place.
Here is my MainActivity.java, no TextReceived log containing the shared link was being produced:
    import androidx.appcompat.app.AppCompatActivity;

    import android.util.Log;

    import android.content.Intent;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Intent intent = getIntent();
            String action = intent.getAction();
            String type = intent.getType();
            if (Intent.ACTION_SEND.equals(action) && type != null) {
                if ("text/plain".equals(type)) {
                    handleSendText(intent); // Handle text being sent
                } else {
                    Toast toast = Toast.makeText(getApplicationContext(), "Please share an url", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        }

        void handleSendText(Intent intent){
            String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
            Log.d("Textreceived", sharedText);
            if (sharedText != null) {
                TextView helloTextView = (TextView) findViewById(R.id.TextView1);
                helloTextView.setText(sharedText);
            }
        }
    }

Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/nothing"
        android:id="@+id/TextView1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

And here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SimpleVideoDownloader"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

And here is the debug panel logs:
Connected to the target VM, address: 'localhost:52211', transport: 'socket'
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/videodownloade: Late-enabling -Xcheck:jni
D/ProcessState: Binder ioctl to enable oneway spam detection failed: Invalid argument
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10291; state: ENABLED
D/AppScoutStateMachine: 32132-ScoutStateMachinecreated
W/ActivityThread: Application com.example.simplevideodownloader is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1391)
W/ziparchive: Unable to open '/data/app/~~_1ZXNj-gpkC0bM-o-_LQYg==/com.example.simplevideodownloader-4o9AfRTKkroRKixsJBmZrA==/base.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~_1ZXNj-gpkC0bM-o-_LQYg==/com.example.simplevideodownloader-4o9AfRTKkroRKixsJBmZrA==/base.dm': No such file or directory
I/Perf: Connecting to perf service.
V/GraphicsEnvironment: ANGLE Developer option for 'com.example.simplevideodownloader' set to: 'default'
V/GraphicsEnvironment: Updatable production driver is not supported on the device.
I/ForceDarkHelperStubImpl: initialize for com.example.simplevideodownloader , ForceDarkOrigin
D/OpenGLRenderer: JNI_OnLoad success
I/MiuiForceDarkConfig: setConfig density:2.750000, mainRule:0, secondaryRule:0, tertiaryRule:0
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/Looper: PerfMonitor longMsg : seq=3 plan=13:40:49.370 late=2ms wall=2457ms running=196ms runnable=29ms swapin=10ms binder=32ms h=android.app.ActivityThread$H w=110 procState=-1
D/ViewScrollStubImpl: the value of ScrollFrictionRes is: 0.019499999
D/IS_CTS_MODE: false
D/MULTI_WINDOW_SWITCH_ENABLED: false
D/IS_CTS_MODE: false
D/MULTI_WINDOW_SWITCH_ENABLED: false
D/IS_CTS_MODE: false
D/MULTI_WINDOW_SWITCH_ENABLED: false
D/DecorView[]: getWindowModeFromSystem  windowmode is 1
W/Looper: PerfMonitor looperActivity : package=com.example.simplevideodownloader/.MainActivity time=276ms latency=2464ms running=213ms  procState=-1  historyMsgCount=3 (msgIndex=1 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159) (msgIndex=2 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159) (msgIndex=3 wall=2457ms seq=3 running=196ms runnable=29ms swapin=10ms binder=32ms late=2ms h=android.app.ActivityThread$H w=110)
W/Looper: PerfMonitor looperActivity : package=com.example.simplevideodownloader/.MainActivity time=0ms latency=2740ms running=0ms  procState=-1  historyMsgCount=4 (msgIndex=1 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159) (msgIndex=2 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159) (msgIndex=3 wall=2457ms seq=3 running=196ms runnable=29ms swapin=10ms binder=32ms late=2ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159)
I/AdrenoGLES-0: QUALCOMM build                   : c5f0e23, I9972db7aac
    Build Date                       : 04/28/21
    OpenGL ES Shader Compiler Version: EV031.32.02.10
    Local Branch                     : mybrancheba83f1e-3815-f156-b760-08f1eafda2d8
    Remote Branch                    : quic/gfx-adreno.lnx.1.0.r99-rel
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
I/AdrenoGLES-0: Build Config                     : S P 10.0.7 AArch64
I/AdrenoGLES-0: Driver Path                      : /vendor/lib64/egl/libGLESv2_adreno.so
I/AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
D/hw-ProcessState: Binder ioctl to enable oneway spam detection failed: Invalid argument
E/videodownloade: open libmigui.so failed! dlopen - dlopen failed: library "libmigui.so" not found
D/DecorView[]: onWindowFocusChanged hasWindowFocus true
D/DecorView[]: onWindowFocusChanged hasWindowFocus false
D/AppScoutStateMachine: 32132-ScoutStateMachinecreated
I/OpenGLRenderer: Davey! duration=20858ms; Flags=1, FrameTimelineVsyncId=4974711, IntendedVsync=86204996072645, Vsync=86204996072645, InputEventId=0, HandleInputStart=86204997541436, AnimationStart=86204997554509, PerformTraversalsStart=86204997559040, DrawStart=86205055184092, FrameDeadline=86205029405977, FrameInterval=86204996896748, FrameStartTime=16666666, SyncQueued=86205057721227, SyncStart=86205057776748, IssueDrawCommandsStart=86205059246540, SwapBuffers=86205102629769, FrameCompleted=86225854180230, DequeueBufferDuration=8825157, QueueBufferDuration=1841250, GpuCompleted=86225854180230, SwapBuffersCompleted=86205106817061, DisplayPresentTime=227721,
D/DecorView[]: onWindowFocusChanged hasWindowFocus true

I tried bringing the intent-related functions and declarations in MainActivity.java under onResume and onPause lifecycles, but that didn't work either. I tried removing the handleSendText() function and doing everything on spot, which unsurprisingly didn't work out.
I would really like a solution which would work even if the app is closed, as I plan to prevent displaying an activity at all, and do everything in the background instead (and do something else with the shared link). Please help me out here, thanks in advance!

A: As per @CommonsWare 's comment, I tried finding out more, and this is what works:
public class MainActivity extends AppCompatActivity {

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

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();
        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if ("text/plain".equals(type)) {
                handleSendText(intent); // Handle text being sent
            } else {
                Toast toast = Toast.makeText(getApplicationContext(), "Please share an url", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    void handleSendText(Intent intent){
        String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
        Log.d("Textreceived", sharedText);
        if (sharedText != null) {
            //my work here
        }
    }

Basically put the getIntent() method inside onResume() and handle setIntent() from onNewIntent().
This answer was really helpful: https://stackoverflow.com/a/8896750/20059147


text:
Q: Difference between [BsonId] and BsonClassMap.MapIdField Using the C# MongoDB Driver, I'm trying to understand the main difference between the Attribute [BsonId] and the BsonClassMap.MapIdField method used in BsonClassMap.RegisterClassMap.
Less generally I'm trying to use a string field of a Model as my document's Id field. If I use the [BsonId] Attribute everything is working fine:
public class MyModel
{
    [BsonId]
    public string AStringId{ get; set; }
}

But if I try to instead register it as Id with MapIdField I then have a System.FormatException: Cannot deserialize a 'String' from BsonType 'ObjectId'.. whenever I'm querying that Collection
BsonClassMap.RegisterClassMap<MyModel>(cm =>
{
    cm.MapIdField(m => m.AStringId);
});

I'd like to know why this problem is happening and more generally what's the difference between those two ways to use a field as custom Id?
 : Don't RTFD me as the MongoDB C# driver documentation is awfully dry on that subject
Thanks


text:
Q: How do you turn a tuple with one integer inside it into a string or an integer I am trying to turn something like (600,) into 600, that is, take the integer out of a tuple. I get this when I define a function with an optional argument like def foo( arg1, arg2, *arg) If the argument which is passed as an integer to *arg, the result is like above, one integer inside a tuple inside the function.
def combine(city, country, *population):
    print(population)

string = combine('New York', 'United States', 50000000)

The rest of the combine function should give a string like New York United States, population = 10000000

A: If you are trying to get a value out of a tuple, use [0] as in (600,)[0]. That will return 600. If you have it inside a function or variable, do the same as in var[0] or func()[0]. If var and func() return something like (525,), it will return the first item, which in this case is 525.
For more info on indexes and slices, check here :D.
To check the length of a tuple, use len(var) where var is the tuple.
And to check if it IS a tuple, use isinstance(var, tuple) where var is the variable you want to check and tuple is the class that defines what a tuple is.
EDIT: For getting an optional argument, you need a default value for that optional argument. Say you had a function that printed your name, but you could also input your last name too. See the function below:
def greeting(name, last=None):
    if last is None:   # check if last was given an argument
        print(f'Ayy, {name}.')
    else:              # if last was given as an argument
        print(f'Hello there, {name} {last}.')


text:
Q: How to install python3.4 in home 'not root'? ensurepip failure I do not have root privileges on the Red Hat Linux machine I am installing python3.4 on.
Downloaded Python-3.4.1.tgz
tar -xzf Python-3.4.1.tgz
./configure
makealtinstall --with-ensurepip=install prefix=~ exec-prefix=~

Python3 does install, but I don't have pip.
I get the following error:

Ignoring ensurepip failure: pip 1.5.6 requires SSL/TLS

I don't have root access so I cannot install via:
sudo apt-get install libssl-dev openssl

I do have a working version of openssl.
Does anyone have suggestions I could try?

A: Since you are in RedHat, you have to install openssl-devel

yum install openssl-devel

Or you can install it later with get-pip.py

A: The complete procedure for installing Python 3.4 with pip3/pip3.4 on RHEL7 is below. For Ubuntu 12.04 LTS replace yum with apt-get, openssl-devel with libssl-dev and you are good to go:
sudo yum install -y gcc make openssl-devel openssl
wget https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tgz
tar -xf Python-3.4.3.tgz
cd Python-3.4.3/
./configure --with-ensurepip=install
make
make install

Alternatively, you can run make altinstall depending on whether you need create python link or not.


text:
Q: $(window).scroll(function) is not working I want to alert something whenever my window get scrolled but it's not working.
Here is my code
$(window).scroll(function(){
    var ws = $(window).scrollTop();
    if(ws)
    {
        alert('Scrolled');
    }
});

A: In my case, this rule was to blame:
html,
body { overflow-x: hidden; }

Hiding overflowing elements is fine as long as the rule is applied only to the body element.

A: Your code works fine if you add an HTML element having height

$(window).scroll(function(){
    var ws = $(window).scrollTop();
   if(ws)
  {
        console.log(ws);
  }
});

A: Try this,
CSS
body{
height:1200px;
}

Jquery
$(window).on('scroll',function(){
    alert('Hi');
});

(or)
  $(window).on('scroll',function(){
        var wstp = $(window).scrollTop();
       if(wstp)
      {
       alert('hi');
      }
    });

Just add height to your body tag and scroll.

A: If you want to execute or initialize function, you have to write below simple code.
$(window).on("scroll", function() {
   var scrollTop = $(window).scrollTop();
   if(scrollTop >= 10) {
     //here is your function name
   }
});


text:
Q: How can I turn a monadic function into a monadic state transformer? Basically, what I want is this:
stateIO :: (s -> IO (a, s)) -> StateT s IO a
stateIO f = do
    r <- get
    (a, r') <- liftIO $ f r
    put r'
    return a

I tried to use state, but the inner liftIO is problematic. Is there another way to be more clever, without that manual tuple unpacking?

A: Oh well. Thanks @bisserlis.
stateIO = StateT

(perhaps applied to avoid monomorphism restriction).


text:
Q: Is there a way to get user coordinates from telegram bot using Dialogflow? Currently im working on a telegram bot with Dialogflow. I want to get information about the user like current coordinates and user name but im not able to get them in the JSON coming from telegram. Is there a way to do such a thing without using any related google assistant events?

A: You can check the structure of updates received by bot on the documentation Telegram Bot API
update.message.from contains the User object.
update.message.location contains the Location object.
Be aware that the location will be present only if the user actually sent his position to the bot, it will not be a metadata coming along with every message.


text:
Q: Is it possible to create dynamic function in PHP5 I have a script i use to extend for my database object, what i went is build a little more complex class to save code over all so i will ask you guys here on this site about sombordy know a way to build it.
First i got this code
Abstract class
abstract class dbObjExtend {
// empty for now
}

Normal controller class
class obj extends dbObjExtend {
    public function setVar1($value) {
        $this->_var1 = $value;
    }

    public function setVar2($value) {
        $this->_var2 = $value;
    }

    public function setVar3($value) {
        $this->_var3 = $value;
    }

    public function setVar3($value) {
        $this->_var3 = $value;
    }
}

what i want now is move my setVar function inside the dbObjExtend dynamic so i can call and build new "set functions" when i need it, i hope you understand my question my abstract class will look like this if its possible.
Abstract class
abstract class dbObjExtend {
    public function setVar($key, $value) {
        $this->_{$key} = $value;
    }
}

if its possible to do this way i will make it easyer to call my functions on this way
Normal controller class - after
class obj extends dbObjExtend {
    public hello() {
        echo "Var1: ". $this->_var1 ."\n";
        echo "Var3: ". $this->_var2 ."\n";
        echo "Var3: ". $this->_var3 ."\n";
    }
}

Sample code
$obj = new obj;
$obj->setVar('var1', $value1);
$obj->setVar('var2', $value2);
$obj->setVar('var2', $value3);

Thanks for your time, and hope you understand what my point is :)


text:
Q: A canonical bijection from linear independent vectors to parking functions Call an $n$-vector $v$ in $\mathbb{Z}^n$ cool when it has only entries 0 or 1 and the ones appear in only one block. Thus there are $n(n+1)/2$ such vectors. For $n=3$ they are:
[ <[ 1, 0, 0 ]>, <[ 1, 1, 0 ]>, <[ 0, 1, 0 ]>, <[ 1, 1, 1 ]>, <[ 0, 1, 1 ]>, <[ 0, 0, 1 ]> ].
Let $X_n$ be the set of cool $n$-vectors. Call a subset $U \subset X_n$ cool when $U$ has $n$ elements that are linearly independent.
There should be $(n+1)^{n-1}$ cool subsets of $X_n$. For $n=3$ they are:
[ [ <[ 1, 0, 0 ]>, <[ 1, 1, 0 ]>, <[ 1, 1, 1 ]> ],
[ <[ 1, 0, 0 ]>, <[ 1, 1, 0 ]>, <[ 0, 1, 1 ]> ],
[ <[ 1, 0, 0 ]>, <[ 1, 1, 0 ]>, <[ 0, 0, 1 ]> ],
[ <[ 1, 0, 0 ]>, <[ 0, 1, 0 ]>, <[ 1, 1, 1 ]> ],
[ <[ 1, 0, 0 ]>, <[ 0, 1, 0 ]>, <[ 0, 1, 1 ]> ],
[ <[ 1, 0, 0 ]>, <[ 0, 1, 0 ]>, <[ 0, 0, 1 ]> ],
[ <[ 1, 0, 0 ]>, <[ 1, 1, 1 ]>, <[ 0, 0, 1 ]> ],
[ <[ 1, 0, 0 ]>, <[ 0, 1, 1 ]>, <[ 0, 0, 1 ]> ],
[ <[ 1, 1, 0 ]>, <[ 0, 1, 0 ]>, <[ 1, 1, 1 ]> ],
[ <[ 1, 1, 0 ]>, <[ 0, 1, 0 ]>, <[ 0, 1, 1 ]> ],
[ <[ 1, 1, 0 ]>, <[ 0, 1, 0 ]>, <[ 0, 0, 1 ]> ],
[ <[ 1, 1, 0 ]>, <[ 1, 1, 1 ]>, <[ 0, 1, 1 ]> ],
[ <[ 1, 1, 0 ]>, <[ 0, 1, 1 ]>, <[ 0, 0, 1 ]> ],
[ <[ 0, 1, 0 ]>, <[ 1, 1, 1 ]>, <[ 0, 1, 1 ]> ],
[ <[ 0, 1, 0 ]>, <[ 1, 1, 1 ]>, <[ 0, 0, 1 ]> ],
[ <[ 1, 1, 1 ]>, <[ 0, 1, 1 ]>, <[ 0, 0, 1 ]> ] ]

Question: Is there a canonical bijection from cool subsets of $X_n$ to parking functions (that are counted by the same number $(n+1)^{n-1}$)?

Background: The cool vectors correspond to the indecomposable representations of the $A_n$-quiver algebra $A$ and the cool subsets to the bases of the Grothendieck group $K_0(A)$ of $A$. I'm interested in a "canonical" bijection to parking functions to enter some statistics from homological algebra into findstat : findstat.org that has several statistics and maps for parking functions.
I can not really say what canonical means but it should behave nice under some standard statistics from homological algebra.
For example for such a canonical bijection, the number of simple vectors (those having only one non-zero entry) or the number of projective vectors (those having the last entry nonzero) in U should probably correspond to something nice for parking functions.

A: They are in canonical bijection with the spanning trees of the complete graph $K_{n+1}$ (for which the bijections with parking functions are well known).
Indeed, let $K_{n+1}$ be the complete graph on the ground set $\{0,1,\ldots,n\}$. Denote $f_0=0$ and consider $n$ linearly independent vectors $f_1,\ldots,f_n$. Denote further $e_j=f_j-f_{j-1}$ for $j=1,\ldots,n$. They form another basis of the same $n$-dimensional space $W$ as $f_j$'s. For an edge $\epsilon=ij$, $i<j$, of $K_{n+1}$ we consider the vector $w(\epsilon)=f_j-f_i=e_{i+1}+\ldots+e_j$. Note that $n$ edges $w(\epsilon_1),\ldots,w(\epsilon_k)$ are linearly independent if and only if the set of edges $\epsilon_i$'s does not contain cycles. Thus the bases of $W$ correspond to spanning trees of $K_{n+1}$.
The above construction is a standard vector representation of the circuit matroid.

A: See "A braid group action on parking functions" by Gorsky and Gorsky.


text:
Q: Logical to char I have a char array representing a binary number for example
bit <1x8 char> '00110001'

I want to replace the last char with a logical value. The following error is triggered: Conversion to char from logical is not possible.
This is my code:
bit(end:end) = hiddenImg(i,j);

I checked that hiddenImg(i,j) is in fact a logical value.

A: This may not be optimal but should do what you want (convert the logical to a char):
>> bit = '10010100'

bit =

10010100

>> bit(end)=num2str(true)

bit =

10010101


text:
Q: Fix Characters Wordpress Ionic App Special Characters in my ionic App are displayed weird. For example when I have a quote in my title (headline) it's displayed as follows: Ü for opening" and Ý for a closing"
I have changed already in my wordpress the following
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

to:
/** Database Charset to use in creating database tables. */
//define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
//define('DB_COLLATE', '');

Purged all Cache but the problem is the same.
Anybody an idea?

A: OK after doing excessive research I came to the conclusion that I have to add [innerHTML] into the span/title/h1


text:
Q: how to enable "Load data local infile " in mysql JDBC? i am trying to load data into a table through Java program using JDBC.
i have already done these steps :

sudo nano /etc/mysql/my.cnf

Then add:

[mysqld] local-infile = ON
[mysql] local-infile = ON

on running the this program:

Code:
Statement statement = con.createStatement();String sql="Create table tbl_user_analysis (Country varchar(10),State Varchar(20))";
statement.executeUpdate("drop table tbl_user_analysis");
statement.executeUpdate(sql);
statement.executeUpdate("load data local infile /home/Asus/workspace/example/xyz into table tbl_user_analysis fields terminated by '\\t' ");

But i am getting this exception:

Exception in thread "main"
  com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near
  '/home/Asus/workspace/example/xyz into table
  tbl_user_analysi' at line 1   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)     at
  com.mysql.jdbc.Util.getInstance(Util.java:386)    at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)    at
  com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)    at
  com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)    at
  com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)     at
  com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)  at
  com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2788)   at
  com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1816)
    at
  com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1730)
    at example1.example.main(example.java:281)


text:
Q: Define window title when using TitleAreaDialog I am working with an Eclipse RCP (e3) and I am using TitleAreaDialog. I succeeded to add the Title inside of it and the text as well as all the other components. However, what I was uncapable of doing is to add a title to my window. I tried everything that came to my mind and searched on the internet but with no luck. I wonder if it is even possible. Anyway, if you do have the solution, please let me know.
Thank you for your help

A: To set the text of the window title use the Shell.setText method. The cleanest way to do this is to override the configureShell method:
@Override
protected void configureShell(Shell newShell)
{
  super.configureShell(newShell);

  newShell.setText("Window title");
}

This applies to TitleAreaDialog, TrayDialog and Dialog (and others).


text:
Q: uWSGI process 1 got Segmentation Fault _ Fail to deploy Flask App on Pythonanywhere I'm trying to deploy my flask app on Pythonanywhere but am getting an error i have no idea what to do about. I've looked online and people haven't been getting similar errors like mine.
My app loads a bunch of pretrained ML models.
Would love some help!

2018-10-16 20:52:38 /home/drdesai/.virtualenvs/flask-app-env/lib/python3.6/site-packages/sklearn/base.py:251: UserWarning: Trying to unpickle estimator LinearRegression from version 0.19.1 when using version 0.20.0. This might lead to breaking code or invalid results. Use at your own risk.#012  UserWarning)
2018-10-16 20:52:38 !!! uWSGI process 1 got Segmentation Fault !!!
2018-10-16 20:52:38 * backtrace of 1 *#012/usr/local/bin/uwsgi(uwsgi_backtrace+0x2c) [0x46529c]#012/usr/local/bin/uwsgi(uwsgi_segfault+0x21) [0x465661]#012/lib/x86_64-linux-gnu/libc.so.6(+0x36cb0) [0x7f6ed211ccb0]#012/home/drdesai/.virtualenvs/flask-app-env/lib/python3.6/site-packages/sklearn/neighbors/kd_tree.cpython-36m-x86_64-linux-gnu.so(+0x404b6) [0x7f6ead1d54b6]#012/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyCFunction_FastCallDict+0x105) [0x7f6ed0e80005]#012/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x16b5fa) [0x7f6ed0f195fa]#012/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x2f3c) [0x7f6ed0f1ccfc]#012/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x16a890) [0x7f6ed0f18890]#012/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x16b7b4) [0x7f6ed0f197b4]#012/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x2f3c) [0x7f6ed0f1ccfc]#012/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x16a890) [0x7f6ed0f18890]#012/usr/lib/x86_
2018-10-16 20:52:38 chdir(): No such file or directory [core/uwsgi.c line 1610]
2018-10-16 20:52:38 VACUUM: unix socket /var/sockets/drdesai.pythonanywhere.com/socket removed.

A: Are you using Tensorflow?  It does some strange stuff with threads, which can make it crash in PythonAnywhere websites (which don't allow threading).   If you're using Keras with the Tensorflow backend, you should be able to get it to work by using Theano instead -- more information on this help page.

A: uWSGI is a C/C++ compiled app and segmentation fault is its internal error that means that there is some incorrect behavior in uWSGI logic: somewhere in its code it's trying to get access to area of memory it's not allowed to access to, so OS kills this process and returns "segfault" error. So make sure you have the latest stable version of uwsgi installed. Also make sure you installed it properly either using a package manager or via manual compiling. It's recommended to install it using a package manager since it's much more easy than via manual compiling. Also, make sure you use it properly.


text:
Q: Code to rearrange an html table in jQuery How could I go from this :

    A
    <input for A>

    B
    <input for B>

to this:

    A
    B

    <input for A>
    <input for B>

I need to move the rows into n (this changes based on the number of rows retrieved from a data set, in this case for 2 columns but it can be any number) number of columns. How could I achieve this?

A: You could read in the table data into a two-dimensional array and then just overwrite the table data with the transposed matrix.
function reArrange() {
    var table = $('table#theTable');
    // we will store all the table-data in a two-dim array:
    var data = new Array();
    // find all rows (row-index: i):
    $(table).find('tr').each(function(i, row) {
        // find all cells in this row (col-index: j):
        $(row).find('td').each(function(j, cell) {
            // make sure, we got the array right:
            if ( data[j] === undefined ) {
                data[j] = new Array();
            }
            // use col-index as first index in the array:
            data[j][i] = $(cell).html();
        });
    });
    // reset table:
    $(table).find('tr').remove();
    // re-fill table
    $(data).each(function(i, elem){
        var row = $('
');
        $(elem).each(function(j, col) {
            cell = $('').html(col);
            $(row).append(cell);
        });
        $(table).append(row);
    });

}
reArrange();

Have a look at this jsFiddle: http://jsfiddle.net/66YpC/2/
I hope, this is what you were looking for. If you need some more information on the code, let me know!


text:
Q: How to convert a time from GMT to EST I have a Date & time "20140508063630" in (yyyyMMddHHmmss) format. I want to convert this Time into EST time zone. How can I do it? If there is any API for this conversion please let me know. Thanks in advance.

A:     try {
          DateFormat gmtFormat = new SimpleDateFormat();
          TimeZone estTime = TimeZone.getTimeZone("EST");
          gmtFormat.setTimeZone(estTime);
          SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
          sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
          System.out.println("EST Time: " + gmtFormat.format(sdf.parse("20140508063630")));
        } catch (ParseException e) {
          e.printStackTrace();
        }

A: Since you have tagged your question java-time, you do deserve a java.time answer.
    String dateAndTime = "20140508063630";
    DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    ZonedDateTime coralHarbourDateTime = LocalDateTime.parse(dateAndTime, parseFormatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.of("America/Coral_Harbour"));
    System.out.println(coralHarbourDateTime);

This prints
2014-05-08T01:36:30-05:00[America/Coral_Harbour]

There are a number of things to note though:

*

*You also tagged your question android. java.time seems to be coming to Android, but as of writing it is not on the majority of Android phones. Don' t despair, though, get the ThreeTenABP and use the classes on Android.

*The SimpleDateFormat and TimeZone classes used in the other answers are long outdated, so if your Android app is doing any work with dates and/or times and/or time zones, I do recommend ThreeTenABP and the modern classes as the programmer friendly and the futureproof way to go.

*You asked for EST time zone and then gave us a date of May 8, which is in the summer time (DST) part of the year. First, three letter abbreviations are dangerous in being ambiguous and in this case not a full time zone, so avoid them where you can. I solved the problem by using America/Coral_Harbour since I read that this particular place uses EST all year round, no summer time. If this was not what you intended, please provide a different location. If instead I use America/Montreal, I get 2014-05-08T02:36:30-04:00[America/Montreal], for example, with time zone offset -4 instead of -5.

Furhter link: How to use ThreeTenABP in Android Project

A: Following code for convert date from one timezone to another timezone with any date format
{   String parsedDate = null;

    try {
        SimpleDateFormat dbDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    dbDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date date = dbUtcDateFormat.parse("20140508063630");

        SimpleDateFormat userDateFormat = new SimpleDateFormat(yyyyMMddHHmmss);
        userDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
        parsedDate = userDateFormat.format(date);
    } catch (Throwable t) {
        logger.warn("Date Parse Faied : ", t);
    }

    return parsedDate;
}


text:
Q: Use automapper to map entire object to an enum Is it possible to use automapper to determine an enum for the entire object?
Now I get this error:

Missing type map configuration or unsupported mapping.

When I try like
var orderType = _mapper.Map<OrderType>(orderData);

What I've been trying is:
public class Mapper : Profile
{
    public Mapper()
    {
        CreateMap<OrderData, OrderType>()
            .ConvertUsing(s => OrderType.Type1);
    }
    public enum OrderType { Type1, Type2, Type3 }
}

Of course there will be some more logic later to determine the correct enum :-)

A: I did a mistake at startup so it never added the profile to automapper


text:
Q: Can you include totals and detail rows in a single mySQL query? None of the questions on file seems to be about my precise problem.
Is it possible to sequence detail lines based on the number of detail lines for that order you have in a single query?
Consider the following simplified table:
Order number Article number
------------ --------------
123           1
123           2
123           3
234           1
234           2
345           1
456           1
456           2
456           3
456           4
456           5

The number of detail lines for each order would be
Order number Number of lines
------------ ---------------
123           3
234           2
345           1
456           5

Is it possible to select the order number, article number in descending order by total number of detail lines for each detail line?  In other words the desired results are
Order number Article number
------------ --------------
456          1
456          2
456          3
456          4
456          5
123          1
123          2
123          3
234          1
234          2
345          1

I can do it with multiple queries and temporary tables or extra columns.  Neither simple SELECTS, SELF JOINs nor UNIONs appear to give me the results I want.  Is it possible to do with a single query?

A: This query should work as it's getting the count from the join and then ordering it by the count.
select t1.orderNumber,  t1.articleNumber from myTable t1
inner join
(
  select orderNumber,  count(articleNumber) as count from myTable
   group by orderNumber

) t2
on t1.orderNumber = t2.orderNumber
order by t2.count desc, t1.orderNumber, t1.articleNumber

To better expain it:
We are first selecting all the data, then we are inner joining a table that has the count for each order number, once we have this we can then order it by count DESC so we get the order number with the highest count on top and we can then add additional sorting in the Order By

A: In the interests of future readers (when MySQL 8.x is production ready and it supports window functions) you can avoid the intermediate subquery and join by using COUNT() OVER(partition by ...) like this:

select t1.orderNumber,  t1.articleNumber f
from myTable t1
order by
    count(*) over(partition by t1.orderNumber) DESC
  , t1.orderNumber
  , t1.articleNumber
;

orderNumber |  f
----------: | -:
        456 |  1
        456 |  2
        456 |  3
        456 |  4
        456 |  5
        123 |  1
        123 |  2
        123 |  3
        234 |  1
        234 |  2
        345 |  1

ps: The example above done in MariaDB 10.2 to show MySQL(ish) syntax at work (& it's standards complaint SQL anyway).
dbfiddle here

A: If I understand the problem correctly, following query should work:
select t1.order_number, t1.Article_number
from t1
inner join (select order_number,count(*) as cnt from t1 group by order_number) as t2
on t1.order_number = t2.order_number
order by t2.cnt desc,t1.order_number,t1.Article_number;

Hope it helps!


text:
Q: Creating objects in Java I have the following class:
class Position {

        private double x,y;
        private int id;

        private static int count=0; //counts number of times a Position object has been created

        public Position (double initX, double initY) {
            x=initX;
            y=initY;
            id=count;
            count++;
        }

        public Position (Position a) {
            id=count;
            count++;
            x=a.x;
            y=a.y;
        }

I want to now create a Position object in another of my .java files. How would I do so? Wouldnt I just use Position x=new Position; ? Thats not working. Do I have to import the position class into the files? I tried that too, didnt work. Wouldnt let me import. My files are in the default folder.
Here's where I want to use it. Im not even sure Im reading the instructions correctly. Is this what they want from me? To initialize every element of the array to a new position object?
/**
     * Returns an array of num positions. Each position is initialized to a random
     * (x,y) position.
     * if num is less than zero, just return an empty array of length 0.
     *
     * @param num
     *            number of positions to create
     * @return array of newly minted Points
     */
 public int[] randomPos(int[] a) {
     int numPositions=Position.getNumPositionsCreated();
     int[] posArr=new int[numPositions];
     int x,y;
     for (int i=0; i<numPositions;i++)
         Position rand = new Position(x,y);
         //

A: You would need to invoke the constructor,
Position x = new Position(2.0,2.0);

Since one of your constructor takes two double's as arguments, I used those as an example.
Or, you could create a new Position object by passing in another Position object,
Position otherX = new Position(new Position(2.0,2.0));
// or combining our above example assuming that x is already instantiated
Position otherX = new Position(x);

Also, just in case you are unsure, there is a difference between instantiation and declaration!
Instantiation:
Position posX = new Position(1.0, 4.0);

Now, posX is an instance of a Position object, because we construct our object by invoking the constructor.
Declaration:
Position posX;

Note that the posX variable is declared to be a Position object, but has not yet been instantiated so posX would have a null reference.
Update:
Without actually do the homework for you, because you will not learn that way. I can tell you that what you have so far, and what is listed in the javadoc above do not agree. Also, given by the way the javadoc is written, it is tough to follow, therefore let me try to clean it up for you and leave you to do the rest,
/* Returns an array of n Positions. Each Position is initialized to a random
 * (x,y) position.
 * if n is less than zero, just return an empty array of length 0.
 *
 * @param n
 *     number of Positions to create
 * @return array of newly created Positions
 */

Now we can break down that javadoc, so lets pinpoint what we know.

*

*We are passing an argument, n which indicates how big the Positions array should be.

*We need to check to see if n is equal to 0, if so we return an empty Position array.

*Each Position object would be instantiated with random x and y values.

*We know that we need to return an Position array.

This should get you started, I am sure you can figure out the rest.

A: Position x = new Position(1.0, 2.0);

For example. The way you have it now is missing method arguments.

A: Position x = new Position(1d,2d);

You need to pass your constructor arguments.  Since you defined 2 constructors on your Position class, you must use one of them.  Usually not a bad idea to put a do nothing constructor on your class. like
Postion () {}

or in your case
Position () {
   Position.static++;
}

since you are counting.  Note you should reference static members statically.

A: Don't forget the parentheses and arguments to pass into the constructor when you call new, eg:
Position p = new Position(x, y);

Depending upon where the other class is, you may also need to make Position a public class (it appears you are using the default visibility of package-private).
Also note that x and y must be initialized first,

A: Your constructors take arguments, so you have to provide some.
Position p = new Position(1.0, -2.0);

If you want to create one without arguments, you need to a add a zero-argument constructor.
public Position() {
}

which would then be invoked by doing Position p = new Position() (the parenthesis are required when not passing in arguments)
If you don't define any constructors, java automatically creates an implied zero-arg constructor, but once you define a different constructor, you have to explicitly define a zero-arg constructor to have one.
If both of your classes are in the default package you shouldn't need to import anything.

A: Java already has a Point class.  It may be overkill for you but though I'd mention it.
http://download-llnw.oracle.com/javase/6/docs/api/java/awt/geom/Point2D.html


text:
Q: PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users? There is a known issue with opening a PDF in Internet Explorer (v 6, 7, 8, 9) with Adobe Reader X (version 10.0.*).  The browser window loads with an empty gray screen (and doesn't even have a Reader toolbar).  It works perfectly fine with Firefox, Chrome, or with Adobe Reader 10.1.*.
I have discovered several workarounds.  For example, hitting "Refresh" will load the document properly.  Upgrading to Adobe Reader 10.1.*, or downgrading to 9.*, fixes the issue too.
However, all of these solutions require the user to figure it out.  Most of my users get very confused at seeing this gray screen, and end up blaming the PDF file and blaming the website for being broken.  Honestly, until I researched the issue, I blamed the PDF too!
So, I am trying to figure out a way to fix this issue for my users.
I've considered providing a "Download PDF" link (that sets the Content-Disposition header to attachment instead of inline), but my company does not like that solution at all, because we really want these PDF files to display in the browser.
Has anyone else experienced this issue?
What are some possible solutions or workarounds?
I'm really hoping for a solution that is seamless to the end-user, because I can't rely on them to know how to change their Adobe Reader settings, or to automatically install updates.
Here's the dreaded Gray Screen:
Edit: screenshot was deleted from file server!  Sorry!
The image was a browser window, with the regular toolbar, but a solid gray background, no UI whatsoever.
Background info:
Although I don't think the following information is related to my issue, I'll include it for reference:
This is an ASP.NET MVC application, and has jQuery available.
The link to the PDF file has target=_blank so that it opens in a new window.
The PDF file is being generated on-the-fly, and all the content headers are being set appropriately.
 The URL does NOT include the .pdf extension, but we do set the content-disposition header with a valid .pdf filename and the inline setting.
Edit: Here is the source code that I'm using to serve up the PDF files.
First, the Controller Action:
public ActionResult ComplianceCertificate(int id){
    byte[] pdfBytes = ComplianceBusiness.GetCertificate(id);
    return new PdfResult(pdfBytes, false, "Compliance Certificate {0}.pdf", id);
}

And here is the ActionResult (PdfResult, inherits System.Web.Mvc.FileContentResult):
using System.Net.Mime;
using System.Web.Mvc;
///
/// Returns the proper Response Headers and "Content-Disposition" for a PDF file,
/// and allows you to specify the filename and whether it will be downloaded by the browser.
///
public class PdfResult : FileContentResult
{
    public ContentDisposition ContentDisposition { get; private set; }

    ///
    /// Returns a PDF FileResult.
    ///
    /// <param name="pdfFileContents">The data for the PDF file</param>
    /// <param name="download">Determines if the file should be shown in the browser or downloaded as a file</param>
    /// <param name="filename">The filename that will be shown if the file is downloaded or saved.</param>
    /// <param name="filenameArgs">A list of arguments to be formatted into the filename.</param>
    /// <returns></returns>
    [JetBrains.Annotations.StringFormatMethod("filename")]
    public PdfResult(byte[] pdfFileContents, bool download, string filename, params object[] filenameArgs)
        : base(pdfFileContents, "application/pdf")
    {
        // Format the filename:
        if (filenameArgs != null && filenameArgs.Length > 0)
        {
            filename = string.Format(filename, filenameArgs);
        }

        // Add the filename to the Content-Disposition
        ContentDisposition = new ContentDisposition
                                 {
                                     Inline = !download,
                                     FileName = filename,
                                     Size = pdfFileContents.Length,
                                 };
    }

    protected override void WriteFile(System.Web.HttpResponseBase response)
    {
        // Add the filename to the Content-Disposition
        response.AddHeader("Content-Disposition", ContentDisposition.ToString());
        base.WriteFile(response);
    }
}

A: It's been 4 months since asking this question, and I still haven't found a good solution.
However, I did find a decent workaround, which I will share in case others have the same issue.
I will try to update this answer, too, if I make further progress.
First of all, my research has shown that there are several possible combinations of user-settings and site settings that cause a variety of PDF display issues.  These include:

*

*Broken version of Adobe Reader (10.0.*)

*HTTPS site with Internet Explorer and the default setting "Don't save encrypted files to disk"

*Adobe Reader setting - disable "Display PDF files in my browser"

*Slow hardware (thanks @ahochhaus)

I spent some time researching PDF display options at pdfobject.com, which is an EXCELLENT resource and I learned a lot.
The workaround I came up with is to embed the PDF file inside an empty HTML page.  It is very simple:  See some similar examples at pdfobject.com.

    ...

        <object data="/pdf/sample.pdf" type="application/pdf" height="100%" width="100%"></object>

However, here's a list of caveats:

*

*This ignores all user-preferences for PDFs - for example, I personally like PDFs to open in a stand-alone Adobe Reader, but that is ignored

*This doesn't work if you don't have the Adobe Reader plugin installed/enabled, so I added a "Get Adobe Reader" section to the html, and a link to download the file, which usually gets completely hidden by the <object /> tag, ... but ...

*In Internet Explorer, if the plugin fails to load, the empty object will still hide the "Get Adobe Reader" section, so I had to set the z-index to show it ... but ...

*Google Chrome's built-in PDF viewer also displays the "Get Adobe Reader" section on top of the PDF, so I had to do browser detection to determine whether to show the "Get Reader".

This is a huge list of caveats. I believe it covers all the bases, but I am definitely not comfortable applying this to EVERY user (most of whom do not have an issue).
Therefore, we decided to ONLY do this embedded option if the user opts-in for it.  On our PDF page, we have a section that says "Having trouble viewing PDFs?", which lets you change your setting to "embedded", and we store that setting in a cookie.
In our GetPDF Action, we look for the embed=true cookie.  This determines whether we return the PDF file, or if we return a View of HTML with the embedded PDF.
Ugh.  This was even less fun than writing IE6-compatible JavaScript.
I hope that others with the same problem can find comfort knowing that they're not alone!

A: I don't have an exact solution, but I'll post my experiences with this in case they help anyone else.
From my testing, the gray screen is only triggered on slower machines [1]. To date, I have not been able to recreate it on newer hardware [2]. All of my tests have been in IE8 with Adobe Reader 10.1.2. For my tests I turned off SSL and removed all headers that could have disabled caching.
To recreate the gray screen, I followed the following steps:
1) Navigate to a page that links to a PDF
2) Open the PDF in a new window or tab (either via the context menu or target="_blank")
3) In my tests, this PDF will open without error (however I have received user reports indicating failure on the first PDF load)
4) Close the newly opened window or tab
5) Open the PDF (again) in a new window or tab
6) This PDF will not open, but instead only show the "gray screen" mentioned by the first user (all subsequent PDFs that are loaded will also not display -- until all browser windows are closed)
I performed the above test with several different PDF files (both static and dynamic) generated from different sources and the gray screen issue always occurs when following the above steps (on the "slow" computer).
To mitigate the problem in my application, I "tore down" the page that links to the PDF (removed parts piece by piece until the gray screen no longer occurred). In my particular application (built on closure-library) removing all references to goog.userAgent.adobeReader [3] appears to have fixed the issue. This exact solution won't work with jquery or .net MVC but maybe the process can help you isolate the source of the issue. I have not yet taken the time to isolate which particular portion of goog.userAgent.adobeReader triggers the bug in Adobe Reader, but it is likely that jquery might have similar plugin detection code to that used in closure-library.
[1] Machine experiencing gray screen:
Win Server '03 SP3
AMD Sempron 2400+ at 1.6GHz
256MB memory
[2] Machine not experiencing gray screen:
Win XP x64 SP2
AMD Athlon II X4 620 at 2.6 GHz
4GB memory
[3] http://closure-library.googlecode.com/svn/docs/closure_goog_useragent_adobereader.js.source.html

A: I ran into this issue around the time MVC1 was first released. See Generating PDF, error with IE and HTTPS regarding the Cache-Control header.

A: For Win7  Acrobat Pro X
Since I did all these without rechecking to see if the problem still existed afterwards, I am not sure which on of these actually fixed the problem, but one of them did. In fact, after doing the #3 and rebooting, it worked perfectly.
FYI: Below is the order in which I stepped through the repair.

*

*Go to Control Panel > folders options under each of the General, View and Search Tabs
click the Restore Defaults button and the Reset Folders button

*Go to Internet Explorer, Tools > Options > Advanced > Reset ( I did not need to delete personal settings)

*Open Acrobat Pro X, under Edit > Preferences > General.
At the bottom of page select Default PDF Handler. I chose Adobe Pro X, and click Apply.
You may be asked to reboot (I did).
Best Wishes

A: In my case the solution was quite simple.
I added this header and the browsers opened the file in every test.
header('Content-Disposition: attachment; filename="filename.pdf"');

A: I had this problem.  Reinstalling the latest version of Adobe Reader did nothing.  Adobe Reader worked in Chrome but not in IE.  This worked for me ...
1) Go to IE's Tools-->Compatibility View menu.
2) Enter a website that has the PDF you wish to see.  Click OK.
3) Restart IE
4) Go to the website you entered and select the PDF. It should come up.
5) Go back to Compatibility View and delete the entry you made.
6) Adobe Reader works OK now in IE on all websites.
It's a strange fix, but it worked for me.  I needed to go through an Adobe acceptance screen after reinstall that only appeared after I did the Compatibility View trick.  Once accepted, it seemed to work everywhere.   Pretty flaky stuff.   Hope this helps someone.

A: Hm, would it be possible to simply do this:
The first time your user opens a pdf, using Javascript you make a popout that basically says "If you cannot see your document, please click HERE". Make "HERE" a big button where it will explain to your user what's the problem. Also make another button "everything's fine". If the user clicks on this one, you remember it, so it isn't displayed in the future.
I'm trying to be practical. Going to great lengths trying to solve this kind of problem "properly" for a small subset of Adobe Reader versions doesn't sound very productive to me.

A: Experimenting more, the underlying cause in my app (calling goog.userAgent.adobeReader) was accessing Adobe Reader via an ActiveXObject on the page with the link to the PDF. This minimal test case causes the gray screen for me (however removing the ActiveXObject causes no gray screen).
<!DOCTYPE html>

    <title>hi</title>
    <meta charset="utf-8">

    link

I'm very interested if others are able to reproduce the problem with this test case and following the steps from my other post ("I don't have an exact solution...") on a "slow" computer.
Sorry for posting a new answer, but I couldn't figure out how to add a code block in a comment on my previous post.
For a video example of this minimal test case, see: http://youtu.be/IgEcxzM6Kck

A: I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online.  I could open everything in Firefox or Opera but not IE.  I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems.  I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches.  Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.

A: We were getting this issue even after updating to the latest Adobe Reader version.
Two different methods solved this issue for us:

*

*Using the free version of Foxit Reader application in place of Adobe Reader

*But, since most of our clients use Adobe Reader, so instead of requiring users to use Foxit Reader, we started using window.open(url) to open the pdf instead of window.location.href = url. Adobe was losing the file handle on for some reason in different iframes when the pdf was opened using the window.location.href method.


text:
Q: React-Redux firebase email address is badly formatted I'm getting the following error, when logging a user in.

The email address is badly formatted.

However, i can sign up fine.
working demo(that doesn't sign in)
https://stackblitz.com/edit/react-herqe7
Maybe its my firebase config file.
firebaseConfig.js
import React, { Component } from 'react';
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';

const config = {
    apiKey: "*******",
    authDomain: "*******",
    databaseURL: "*******",
    projectId: "*******",
    storageBucket: "",
    messagingSenderId: "*******"
};

firebase.initializeApp(config);

export const database = firebase.database()
export const auth = firebase.auth()
export const googleProvider = new firebase.auth.GoogleAuthProvider()

Actions.js
export const signIn = (user) => { return (dispatch) => {

    firebaseAuth.signInWithEmailAndPassword(user.email.trim(), user.password)
        .then(()=> {
            dispatch({type: 'SIGNIN_SUCCESS'})
        }).then((response) => {
            history.push('/dashboard');
        }).catch( (err) => {
            dispatch({ type: 'SIGNIN_ERROR', err});
        });
    }

}

A: I think the issue within SignIn.js is with the handle change and the inputs not having a name="email" name="password". You are setting state with e.target.name, but the input for email doesn't have a name. If you put a console log in your handleChange, you will see that e.target.name is "" not what you want it to be email, password etc
handleChange = e => {
    console.log(e.target.name);
    const { formData } = this.state
    this.setState({
      formData: {
        ...formData,
        [e.target.name]: e.target.value
      }
    });
  };

Add a name="email" to your email input so that e.target.name in handle change will have a key value to setState to.
   <input
      type="email"
      name="email"
      className="form-control"
      id="exampleInputEmail1"
      onChange={this.handleChange}
      aria-describedby="emailHelp"
      placeholder="Enter email"
    />

also will need one for password:
<input
   name="password"
   etc


text:
Q: overrideMaterial in CanvasRenderer I fall back to CanvasRenderer if user's browser does not support WebGL.  I would like to have wireframe only rendering when using CanvasRenderer for performance reasons. However I cannot get overrideMaterial to work with it. It's working with WebGLRendererer quite nicely like this:
scene.overrideMaterial =  new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true });

In CanvasRenderer this seems to have no effect, making FireFox unresponsive because the code is just too heavy for all but the simplest models.
Previously I had replaced all object materials directly with wireframe material by traversing the scene geometries and just overwriting the "real" materials. That kind of works, but  makes material and object management guite messy, as I would like to have the material information present in the models even if they are not rendered.
Is it possible use scene.overrideMaterial with CanvasRenderer? Or other way to force wireframe rendering? I'm using r54.

A: No, CanvasRenderer does not support scene.overrideMaterial. I think you have pretty much exhausted your options.
I would be careful about using MeshBasicMaterial as an override. Only do so if your scene contains meshes only -- no lines, for example.
three.js r.54


text:
Q: Cannot modify class property from shortcode handler function I'm trying to store data from a shortcode attribute in a class property, so I can use it later in other functions. But somehow I'm always ending up with the initial value of the property. Here's a reduced  example to showcase my problem:
class ScopeTestClass {
    public $my_var = null;

    function __construct() {
        // The calls to add_action() go here
        // I've omitted them for this example to avoid cluttering up the code
        add_shortcode( 'my_shortcode', array($this, 'my_shortcode_handler'));
    }

    function register_scripts() {
        wp_register_script('some_script', plugin_dir_url(__FILE__) .
            '/js/some_script.js', array('jquery'), '1.0', true);

    public function my_shortcode_handler() {
        $this->my_var = 'yeeha!';
        wp_enqueue_script('some_script');
        wp_localize_script( 'some_script', 'somescript', array(
            'ajax_url' => admin_url( 'admin-ajax.php' )));

    }

    public function ajax_handler() {
        // This function handles the ajax call from some_script.js.
        // When evaluating $this->my_var here, it is null.
    }
}

$test_obj = new ScopeTestClass();

While my_var is correctly set to "yeeha!" in the shortcode function, in the ajax_handler() function it shows as null. Is this an issue of scope? I thought it might be because both the shortcode and the ajax handler functions are called from outside the object context and thus $this doesn't point to test_obj, but other questions and articles I've read didn't seem to have this problem. So.. what is my issue here?

A: If you are posting from the script to the AJAX handler, that is an entirely different request, the script has no way of knowing the my_var value, so how can it be passed back to the AJAX.
But this is why you are using localize script isn't it? Why not simply pass the value in that array?
wp_localize_script( 'some_script', 'somescript', array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'my_var' => $this->my_var
    )
);


text:
Q: How to delete space of empty "section number" I have renewed the section number so that it doesn't display anything
\renewcommand{\thesection}{}

now the problem is that LaTeX is still reserving space for the section number although isn't displaying it, i.e., the section name is indented to the right and it doesn't cover up the space where the section number was supposed to be?

A: Don't do this.
Use \section* instead, or globally set \setcounter{secnumdepth}{0} to remove section numbering.


text:
Q: Does P(A|B) = P(A) really imply independence? I was going through KhanAcademy's practice questions and came across this question:

150 students in a tenth grade high school class take a survey about
which video game consoles they own. 60 students answer that one of
their consoles is a Playstation, 50 answer that one of their
consoles is an Xbox. Out of these, there are 20 who have both
systems.

Let A be the event that a randomly selected student in the
class has a Playstation and B be the event that the student has an
XBOX.

Is P(A|B) = P(A)? Are the events A and B independent?

Using the given values, P(A|B) = P(A) as P(A|B) = 20/50 = 2/5, and P(A) = 60/150 = 2/5, so they are equal.
Does this imply the events are independent though?
If I change the number of students that have Playstation to 50 (all else remaining the same), P(A|B) = 2/5 but P(A) = 1/3, they are not equal.
If these are truly independent events, shouldn't the original relationship hold up regardless of what the values are?

A: Statistical independence implies that knowing the value of one will not give you any more information about the other. If you change one of the numbers and leave the rest the same, you're creating a different situation - now the proportion of students who own neither system is lower. If you know a student does not have an xbox, it would be more likely that they own neither. If you know they have an xbox, they are more likely to be one of the students who has a playstation (because there are fewer students with just a playstation).
That said, the dependence in this case is not strong. Variables are independent if $$P(A,B) = P(A)P(B)$$
In this case that's $$\frac{20}{150} \ne (\frac{50}{150})^2$$
$$0.1333 \approx 0.1111 $$
which is pretty close.


text:
Q: How to use cast() method of Generics Vector How can I use the cast method of a generics vector. What I thought of, is patterns like (Vector<T>).class.cast(getDates()); or (Vector<a_typeClass>).class.cast(getDates()); but they are not working. A workarround is to cycle trough all elements. But there has to be a way to use cast for a generics Vector.
(Yes, I have to use Vector, because I'm extending an API)
Edit: This is only a small part of a much more complex code. The cast will never fail because of types checking: if (Date.class.isAssignableFrom(a_typeClass)). I also left out the null check in the sample. Eclipse is raising an error Type mismatch: cannot convert from Vector<Date> to Vector<T> because it is not recognizing the type check pattern.
Edit: In the samples I used isAssignableFrom the other way. Was before Date.class.isAssignableFrom(a_typeClass) is now a_typeClass.equals(Date.class). But still I have to use the (Vector<T>) cast, if I don't use it, compile error Type mismatch: cannot convert from Vector<Date> to Vector<T>will be raised. Thanks to davmac and JB Nizet.
Sample:
public class VectorCast {

    @SuppressWarnings("unchecked")
    public <T> Vector<T> getVector1(Class<T> a_typeClass) {
        Vector<T> returnValues = new Vector<>();
        if (a_typeClass.equals(Date.class)) {
            returnValues = (Vector<T>) getDates();

            // Not working
            // return (Vector<T>).class.cast(getDates());
            // return (Vector<a_typeClass>).class.cast(getDates());
        }

        return returnValues;
    }

    public Vector<Date> getDates() {
        // Just dummy Values
        return new Vector<Date>(Arrays.asList(new Date(0), new Date()));
    }

    public static void main(String[] args) {
        VectorCast vectorCast = new VectorCast();
        System.out.println(vectorCast.getVector1(Date.class));
    }
}

Work around Sample:
public <T> Vector<T> getVector2(Class<T> a_typeClass) {
    Vector<T> returnValues = new Vector<>();

    if (a_typeClass.equals(Date.class)) {
        for (Date date : getDates()) {
            returnValues.add(a_typeClass.cast(date));
        }
    }

    return returnValues;
}

A: So, if I understand correctly, you want your method to return an existing Vector<Date>, but as a Vector<T> if the class passed as argument is Date.class, or an empty vector if the class passed as argument is not Date.class. That's quite a strange requirement, but anyway.
You check, at runtime, that a_typeClass is assignable to Date. But the compiler has no clue about that. T is still another type than Date, and Vector<T> is still another type than Vector<Date>. So you need a cast to make it happy.
But even then, your check is incorrect. To be safe, a_typeClass should be equal to Date.class. I could call your method with java.sql.Timestamp.class as argument, and your method would happily return the Vector<Date> as a Vector<Timestamp>. So, callers would expect the Vector to contain Timestamp instances, and the first get() call they would make on the returned Vector would fail with a ClassCastException.
So, what you can do is check that a_typeClass is equal to Date.class, and leave the cast there, which is absolutely necessary for the code to compile, and will always be unchecked, and thus emit a warning.

A: You can't really, because class literals are for raw classes only. You would have to do something like:
        Class<Vector<T>> c = (Class<Vector<T>>)(Object) Vector.class;
        return c.cast(getDates());

This is no clearer or better in any way than the cast you have now.
The essence of the problem is that the compile-time type checking of Java does not take control flow into account. The code pattern you have is unusual in Java (perhaps for this reason). Consider refactoring to avoid behaving differently based on a manual type check.


text:
Q: C# BackgroundWorker_DoWork only does some of the work This one has me stumped.  I have a simple utility I made to help with an enterprise installation of software.  One component backs up AppData files the user currently has on their machine and saves them to a folder on the desktop:
private void backupButton_Click(object sender, EventArgs e)
{
    backgroundBackup.RunWorkerAsync();
}

private void backgroundBackup_DoWork(object sender, DoWorkEventArgs e)
{
    ...
}

private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
    ...
}

// I removed the message boxes from DoWork, and added a RunWorkerCompleted event,
// but neither the confirmation nor the error messgae box from RunWorkerCompleted are shown.

private void backgroundBackup_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    ...
}

This works, but does not produce the expected results.  I put this operation on a background thread because the total file size each user is backing up may approach a gb or two.  Each time this is run, some, but not all of the files and folders from the target are copied to the destination, and the folders that are copied varies each time.  Sometimes only a handful of files and folders are copied, sometimes almost all everything is copied, but never the entire target.  If this operation is placed in a simple console app, it works every time.  Is there anything I need to understand about the BackgroundWorker class that is causing it to not do all the work in the DoWork method?
Edit:
I think I may be over complicating the issue with the BackgroundWorker class.  I spoke to a coworker, and they suggested a simple way of creating a new thread to handle a potentially lengthy process:
    private void backupButton_Click(object sender, EventArgs e)
    {
        Thread backupThread = new Thread(backupThreadJob);
        backupThread.Start();
    }

    private void backupThreadJob()
    {
        try
        {
            //copy files and stuff
        }

        catch(Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
    }

This gets the job done for me; I was unsuccessful in my attempts to use BackgroundWorker and was never able to figure out why only some files were being copied.  Thanks for everyone's help!

A: This isn't a complete answer. But I could imagine that the following has something to do with the problem:
Remember that BackgroundWorker executes your DoWork method on another, non-UI thread, so it's not a good idea to call MessageBox.Show there. You should only do UI stuff if you're running on the UI ("foreground") thread:

You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.
   — MSDN reference page for the BackgroundWorker class

I could imagine that if an exception occurs somewhere in your method, and you want to show a message box in the catch block, this call triggers yet another exception, which doesn't get handled... and thus your method aborts prematurely.

A: Here is an example showing you can call message boxes from the back ground threads.  MessageBox.Show is a static method call and can be called from the back ground thread.  You should never attempt to access anything on your UI layer (including bound backing objects - think WPF here).
Here is an example of where this would be used for message boxes.
I want to copy 10 files and I start the copy process in the background.  An error occurs (file exists, etc) and you want to prompt the user to overwrite - you could show a message box requesting confirmation from the user.
private void button1_Click(object sender, EventArgs e)
{
    BackgroundWorker bw = new BackgroundWorker();
    bw.RunWorkerCompleted += BwOnRunWorkerCompleted;
    bw.DoWork += BwOnDoWork;
    bw.RunWorkerAsync();
}

private void BwOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
    MessageBox.Show("This is a message from a background thread");
}

private void BwOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
    MessageBox.Show("Your done");
}


text:
Q: Get array value by dynamic key in php maybe I am totally blind but i have an array:
Array ( [p541] => 1 [p747] => 1 [p792] => 1 [p968] => 1 [p2157] => 1 [clickeditem] => 0WCr9ParDzLD9wpctknt0XErhOZcX33wXfgGDNpSoIo= [actualtime] => 11832 [timekey] => 1406227645 [actualuser_id] => V58yD4MQ2ZwTumjivhhQL/BSFXsu0Dvoj0bxp7Tu8PM= [timeout] => 0 [report_misuse] => 0 [A1] => 5RC52CZHPV8f0Zw+FYGZel5Ay2YcLVjrY8MBplz1zJA= [B1] => 0WCr9ParDzLD9wpctknt0XErhOZcX33wXfgGDNpSoIo= [B2] => KnCK/vIcQ5PAwJxjUMh0w+NTM+TqdVG9+Tiyi0U9QWM= [B3] => DhT8qBQFQC+dE/Rku7wdMJ4bw6dtFp8hzfmxPMCrItQ= [B4] => ZE30ASB6IUQglpXNiOUxdmiYpJnEbuKKXIaUZO9w4mU= [B5] => IXyGTO6V/8uZOK5y81DnI58xumZ0CIkFsTQwUWJ2CyE= [pageloadtime] => 0.179646 [option] => com_findme [view] => pair )

but I want to get the value for "p541"
$name= "p541";
$value = $array [$name];

does not work ???

A: If your array variable is named $array, try this:
$value = $array['p541'];

What you're doing is creating a new array named $value containing the variable $name, which is not what we want.

A: Your array items need to be comma separated and not within [ ] if you're declaring associative arrays like that. You also need to save your array to a variable so you can access it.
$value = array('p541' => 1, 'p747' => 2, 'p792' => 3);

then this...
$value['p541']

will equal 1


text:
Q: transfer file and form data in post request using RestTemplate between two applications I have set up two application that is

*

*Document server (8000)

*App server (4000)

both are working fine individually (tested using Postman ).
a problem occurs when I am receiving a file and form data from UI / Postman to App server and transferring to Document and form data using Rest templet to the Document Server.
at same time App server is giving me an below error.
15:33:56.360 [http-nio-4206-exec-10] DEBUG o.s.web.client.RestTemplate - Created POST request for "http://localhost:8000/docserver/api/webservicegetway/savefile"
15:33:56.428 [http-nio-4206-exec-10] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [application/json, application/*+json]
15:33:56.909 [http-nio-4206-exec-10] DEBUG o.s.web.client.RestTemplate - POST request for "http://localhost:8000/docserver/api/webservicegetway/savefile" resulted in 406 (null); invoking error handler
15:33:56.916 [http-nio-4206-exec-10] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/appserver] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 406 null] with root cause
org.springframework.web.client.HttpClientErrorException: 406 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:766)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:724)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:680)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:600)
at com.org.appserver.main.services.DocServerService.transferFileToDocServer(DocServerService.java:101)

and getting following an issue at doc server
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:831) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:256) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:280) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.connector.Request.parseParts(Request.java:2868) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.connector.Request.parseParameters(Request.java:3216) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.connector.Request.getParameter(Request.java:1137) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:381) ~[tomcat-embed-core-8.5.29.jar:8.5.29]

My RestWebservice code is below one:-
App Server:-
@RequestMapping(value = "/uploadTest", method = RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
private WebserviceResultSet fileUpload_Test( @RequestParam( "file" ) MultipartFile file,@RequestParam( "filename" ) String filesource,@RequestParam( "filepassword" ) String filepassword, Model p_model ) throws IOException, URISyntaxException {

    WebserviceResultSet result=new WebserviceResultSet();
    if ( file.isEmpty() ) {
        result.addErrormessage("Empty or Corrupted file upload");
        return result;
    }

            byte[] l_bytes = file.getBytes();
            Path l_path = Paths.get("C:\\Eclipse_workspace\\"+ file.getOriginalFilename() );
            Path p=Files.write( l_path, l_bytes );

            DocServerService docServerService=new DocServerService();
            docServerService.transferFileToDocServer(file, filesource, filepassword);

    return result;

}

Doc Server:-
@RequestMapping(value = "savefile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
private WebserviceResultSet saveFile(@RequestParam("file") MultipartFile p_file,
        @RequestParam("filename") String filename,
        @RequestParam("filepassword") String filepassword, Model p_model,
        HttpServletRequest request) {

    WebserviceResultSet savefile = new WebserviceResultSet();

    String applicationctxpath = request.getRealPath(request.getContextPath());

    String directoryName = applicationctxpath + File.separator +ROOT_PATH + File.separator +filename;

    File directory = new File(directoryName);
    if (!directory.exists()) {
        directory.mkdirs();

    }

    try {

        byte[] l_bytes = p_file.getBytes();
        Path l_path = Paths
                .get(directoryName + File.separator +  p_file.getOriginalFilename());
        Files.write(l_path, l_bytes);

        savefile.setStatus(com.main.general.ResultConstent.STATUS_OK);

    } catch (IOException e) {

        savefile.addErrormessage("Exception occured while saving file in Doc Server");

    }

    return savefile;
}


text:
Q: If $\omega$ is a differential $4$-form on a $10$-manifold $M$ then $\omega \wedge d\omega$ is exact Let $\omega$ be a differential $4$-form on a $10$-manifold $M$. I am trying to show that $\omega \wedge d\omega $, which is  a $9$-form, is exact.
Clearly $\omega \wedge d\omega$ is closed, because $d\omega \wedge d\omega =0$ ($|d\omega|=5$ is odd). But how can we show that $\omega \wedge d\omega $ is exact?

A: HINT: What is $d(\omega\wedge\omega)$?

A: Hint: What is $d(\omega \wedge \omega)$?


text:
Q: Different results of 'ps aux | grep x' if entered manually and done via script It was probably a bad method, but I was running ps aux | grep x | wc -l as part of the if statement in a script. When I ran this from the command line as a regular user, the result would be 1 if the process wasn't running, because of that annoying quirk whereby the grep process turns up.
That's fine and well, but I logged the results, and most of the time ps aux | grep x | wc -l run as an /etc/init.d script would return 0 lines. Why would that be?


text:
Q: How to get rows with distinct first attribute and max second attribute I have a table like this
CREATE TABLE table_name
(
id int,
date datetime
)

And in this table are many rows with duplicated id and different data.
How can I get rows with distinct id and max value of date for each id?
P.s. I'm not a badass in an SQL, so sorry for a stupid question, maybe

A: Group by the id. Aggregate functions like max() apply to each group.
select id, max(date)
from table_name
group by id


text:
Q: Comments Listview in Android I have an Activity which contains different items, one of those item is ListView.
I created a custom list adapter and sending to it a json array.
The data for the list arrives from the server.
The list purpose is to make comments list. I allowed the user to insert
a comment and then I show it in the ListView.
When I have some items in the list it works, and the items are shown.
The problem is when listview is empty and the user post a comment.
I see that that data is changed but I don't see the item, means the list is not refreshed..
So I tried to add to the listview an empty view but it doesn't work.
Here is an updated code: (UPDATE)
       if (!s.isEmpty() && !s.equals("{}")) {

            try {
                if (commentsListAdapter == null) {
                    commentsList.setEmptyView(findViewById(R.id.dummy));
                    commentsListAdapter = new CommentsListAdapter(PostView.this);
                }
                JSONObject resObj = new JSONObject(s);
                list.add(resObj);

                commentsListAdapter.setDataSet(list);

                cmntTxt.setText("");
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);

                commentCounter.setText(Integer.toString(list.size()));

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

And inside the Adapter I have this function:
public void setDataSet(List<JSONObject> list){
    commentsList = list;
    notifyDataSetChanged();
}

But the problem is not fixed..

A: I notice the code list.add(resObj) appears after new CommentsListAdapter when the list is empty and appears before new CommentsListAdapter when the list is NOT empty.
I suspect the Adapter CommentsListAdapter is not using the object list for the data storage. In that case, you need to make a public method in the adapter to make updates. Another words, the adapter is using another object for data storage.
It may help to post the code for CommentsListAdapter also. But I hope I am correct about my statements.
I hope that is clear...

A: Please change the following code:
public void setDataSet(List<JSONObject> list){
    commentsList = list;
    notifyDataSetChanged();
}

to :
private List<JSONObject> commentsList = new ArrayList<>();

public void setDataSet(List<JSONObject> list){
    commentsList.clear();
    commentsList.addAll(list);
    notifyDataSetChanged();
}

And use commentsList for all other methods in your adapter. This is a better way for notifyDataSetChanged() to work.
Hope it helps! :)

A: if you are adding your comment from the outside i.e from activity and not from adapter than whenever you set the adapter do this.
youradapterobject.notifyDataSetChanged();
and dont do commentsListAdapter == null than setemptyview
it automatically sets the emptyview if its null
correct usage
 list.setEmptyView(findViewById(R.id.erromsg));


text:
Q: How to locate the checkboxes with the attribute checked I have a list of checkboxes and I need to find the checkboxes that have the attribute "checked". Below is how my check box element looks,
<input type="checkbox" class="u-display--inline-block u-margin-right--small" checked="">

How can I find this with xpath? I cannot use //input[@type='checkbox' and @checked='true')] because i don't have a checked value true attribute. Any advice would be much appreciated.

A: You can just mention the attribute checked to test if it exists:
//input[@type='checkbox' and @checked]

A: Kindly use below xpath for the same:
//input[@type='checkbox'  and @checked]

A: To find the checkboxes that have the attribute checked you can use either of the following solutions:

*

*cssSelector:
"input.u-display--inline-block.u-margin-right--small[type='checkbox'][checked]"

*xpath:
"//input[@class='u-display--inline-block u-margin-right--small' and @type='checkbox'][@checked]"


text:
Q: Python Script runs on terminal/shell but not when executed from a function I have a Python script that takes a JSON argument.
When I run this script from the terminal/shell it runs. Here is the exact code that I execute on the terminal
python  bot.py dca strin '{\"marketplace\":\"USDT\",\"tokenlist\":[{\"token\":\"C98\",\"min\":0,\"max\":500},{\"token\":\"CHESS\",\"min\":1,\"max\":5}],\"compression\":1,\"buyamount\":20,\"tp\":3,\"sl\":10,\"continueflag\":0,\"rsi_level\":0,\"trstart\":1.5,\"trstop\":0.1,\"dca\":[[2,100],[4,100],[6,100],[8,100],[10,100],[15,100]],\"host\":\"localhost\",\"user\":\"root\",\"password\":\"root\",\"database\":\"trading\"}'

My error comes when I create another Python script/function to execute my bot.py.
In my function, I execute the bot.py using the subprocess.call as shown below.
args = '{\"marketplace\":\"USDT\",\"tokenlist\":[{\"token\":\"C98\",\"min\":0,\"max\":500},{\"token\":\"CHESS\",\"min\":1,\"max\":5}],\"compression\":1,\"buyamount\":20,\"tp\":3,\"sl\":10,\"continueflag\":0,\"rsi_level\":0,\"trstart\":1.5,\"trstop\":0.1,\"dca\":[[2,100],[4,100],[6,100],[8,100],[10,100],[15,100]],\"host\":\"localhost\",\"user\":\"root\",\"password\":\"root\",\"database\":\"trading\"}'
subprocess.call(["python", "\\bot_5_12/runner_single.py dca strin", args])

However, when I execute my function I get the error

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Kindly advise because I do not know how to debug this from my end.

A: You should try to replace quotes ( ' to " ), like this :
args = "{\"marketplace\":\"USDT\",\"tokenlist\":[{\"token\":\"C98\",\"min\":0,\"max\":500},{\"token\":\"CHESS\",\"min\":1,\"max\":5}],\"compression\":1,\"buyamount\":20,\"tp\":3,\"sl\":10,\"continueflag\":0,\"rsi_level\":0,\"trstart\":1.5,\"trstop\":0.1,\"dca\":[[2,100],[4,100],[6,100],[8,100],[10,100],[15,100]],\"host\":\"localhost\",\"user\":\"root\",\"password\":\"root\",\"database\":\"trading\"}"

args = str(args).replace(" ","")

subprocess.call(["python", "\\bot_5_12/runner_single.py dca strin", args])

Test your JSON right here.