Programs & Examples On #Rup

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

I get the same error when using Gulp. The solution is to switch to Gulp version 3.9.1, both for the local version and the CLI version.

sudo npm install -g [email protected]

Run in the project's folder

npm install [email protected]

phpMyAdmin - Error > Incorrect format parameter?

Compress your .sql file, and make sure to name it .[format].[compression], i.e. database.sql.zip.

As noted above, PhpMyAdmin throws this error if your .sql file is larger than the Maximum allowed upload size -- but, in my case the maximum was 50MiB despite that I had set all options noted in previous answers (look for the "Max: 50MiB" next to the upload button in PhpMyAdmin).

On npm install: Unhandled rejection Error: EACCES: permission denied

sudo npm install -g @angular/cli

use this. it worked for me

Getting error "The package appears to be corrupt" while installing apk file

In my case, the target phone had the app already installed, but in a "disabled" state. So the user thought it was already uninstalled, but it wasn't. I went to the main app list, clicked on the "disabled" app, uninstalled it, and then the APK would go on.

Build fails with "Command failed with a nonzero exit code"

For me this was to do with a constraint that I was removing at build time. Unticking Remove at build time fixed the issue, and I suspect the compiler had an issue determining the layout without it.

The error code will mention which Storyboard is causing the issue.

Vue js error: Component template should contain exactly one root element

Just make sure that you have one root div and put everything inside this root

  <div class="root">
    <!--and put all child here --!>
   <div class='child1'></div>
   <div class='child2'></div>
  </div>

and so on

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

WebDriverException: Element is not clickable at point (x, y)

This is a typical org.openqa.selenium.WebDriverException which extends java.lang.RuntimeException.

The fields of this exception are :

  • BASE_SUPPORT_URL : protected static final java.lang.String BASE_SUPPORT_URL
  • DRIVER_INFO : public static final java.lang.String DRIVER_INFO
  • SESSION_ID : public static final java.lang.String SESSION_ID

About your individual usecase, the error tells it all :

WebDriverException: Element is not clickable at point (x, y). Other element would receive the click 

It is clear from your code block that you have defined the wait as WebDriverWait wait = new WebDriverWait(driver, 10); but you are calling the click() method on the element before the ExplicitWait comes into play as in until(ExpectedConditions.elementToBeClickable).

Solution

The error Element is not clickable at point (x, y) can arise from different factors. You can address them by either of the following procedures:

1. Element not getting clicked due to JavaScript or AJAX calls present

Try to use Actions Class:

WebElement element = driver.findElement(By.id("navigationPageButton"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

2. Element not getting clicked as it is not within Viewport

Try to use JavascriptExecutor to bring the element within the Viewport:

WebElement myelement = driver.findElement(By.id("navigationPageButton"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement); 

3. The page is getting refreshed before the element gets clickable.

In this case induce ExplicitWait i.e WebDriverWait as mentioned in point 4.

4. Element is present in the DOM but not clickable.

In this case induce ExplicitWait with ExpectedConditions set to elementToBeClickable for the element to be clickable:

WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("navigationPageButton")));

5. Element is present but having temporary Overlay.

In this case, induce ExplicitWait with ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.

WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));

6. Element is present but having permanent Overlay.

Use JavascriptExecutor to send the click directly on the element.

WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I ran in this problem with OpenVPN working as well and I've found a solution where you should NOT stop/start OpenVPN server.

Idea that You should specify what exactly subnet you want to use. In docker-compose.yml write:

networks:
  default:
    driver: bridge
    ipam:
      config:
        - subnet: 172.16.57.0/24

That's it. Now, default network will be used and if your VPN did not assign you something from 172.16.57.* subnet, you're fine.

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

I was upgrading gradle from 4.1 to 4.10 and my internet connection timed out.

So I fixed this issue by deleting "gradle-4.10-all" folder in .gradle/wrapper/dists

pytest cannot import module while python can

I had the same problem but for another reason than the ones mentioned:

I had py.test installed globally, while the packages were installed in a virtual environment.

The solution was to install pytest in the virtual environment. (In case your shell hashes executables, as Bash does, use hash -r, or use the full path to py.test)

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

Try using a callback like this with the catch block.

document.getElementById("audio").play().catch(function() {
    // do something
});

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

I had the same error because I have mapped the HTTP response like this:

this.http.get(url).map(res => res.json);

Note how I accidentally called .json like a variable and not like a method.

Changing it to:

this.http.get(url).map(res => res.json());

did the trick.

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

If it has happened after upgrading Android Studio, It can be caused by an out of date buildtool, Update Android SDK BuildTools

Error: EACCES: permission denied

From what i can see in your logs you posted:

npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: '/home/rupesh/node_modules/lodash',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/home/rupesh/node_modules/lodash',
npm ERR!   fstream_class: 'DirWriter',

directory /home/rupesh/node_modules/ doesn't have necessary permissions to create directory so run chown -r rupesh:rupesh /home/rupesh/node_modules/ this should solve it.

Compiling an application for use in highly radioactive environments

It may be possible to use C to write programs that behave robustly in such environments, but only if most forms of compiler optimization are disabled. Optimizing compilers are designed to replace many seemingly-redundant coding patterns with "more efficient" ones, and may have no clue that the reason the programmer is testing x==42 when the compiler knows there's no way x could possibly hold anything else is because the programmer wants to prevent the execution of certain code with x holding some other value--even in cases where the only way it could hold that value would be if the system received some kind of electrical glitch.

Declaring variables as volatile is often helpful, but may not be a panacea. Of particular importance, note that safe coding often requires that dangerous operations have hardware interlocks that require multiple steps to activate, and that code be written using the pattern:

... code that checks system state
if (system_state_favors_activation)
{
  prepare_for_activation();
  ... code that checks system state again
  if (system_state_is_valid)
  {
    if (system_state_favors_activation)
      trigger_activation();
  }
  else
    perform_safety_shutdown_and_restart();
}
cancel_preparations();

If a compiler translates the code in relatively literal fashion, and if all the checks for system state are repeated after the prepare_for_activation(), the system may be robust against almost any plausible single glitch event, even those which would arbitrarily corrupt the program counter and stack. If a glitch occurs just after a call to prepare_for_activation(), that would imply that activation would have been appropriate (since there's no other reason prepare_for_activation() would have been called before the glitch). If the glitch causes code to reach prepare_for_activation() inappropriately, but there are no subsequent glitch events, there would be no way for code to subsequently reach trigger_activation() without having passed through the validation check or calling cancel_preparations first [if the stack glitches, execution might proceed to a spot just before trigger_activation() after the context that called prepare_for_activation() returns, but the call to cancel_preparations() would have occurred between the calls to prepare_for_activation() and trigger_activation(), thus rendering the latter call harmless.

Such code may be safe in traditional C, but not with modern C compilers. Such compilers can be very dangerous in that sort of environment because aggressive they strive to only include code which will be relevant in situations that could come about via some well-defined mechanism and whose resulting consequences would also be well defined. Code whose purpose would be to detect and clean up after failures may, in some cases, end up making things worse. If the compiler determines that the attempted recovery would in some cases invoke undefined behavior, it may infer that the conditions that would necessitate such recovery in such cases cannot possibly occur, thus eliminating the code that would have checked for them.

How to prevent "The play() request was interrupted by a call to pause()" error?

I have the same issue, finally i solve by:

video.src = 'xxxxx';
video.load();
setTimeout(function() {
  video.play();
}, 0);

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Google Maps JavaScript API RefererNotAllowedMapError

This is another sh1tty Google product with a terrible implemenation.

The problem I have found with this is that if you restrict an API key by IP address, it wont work... BUT far be it from Google to make this point clear... It wasn't until troubleshooting and researching I found:

API keys with an IP addresses restriction can only be used with web services that are intended for use from the server side (such as the Geocoding API and other Web Service APIs). Most of these web services have equivalent services within the Maps JavaScript API (for example, see the Geocoding Service). To use the Maps JavaScript API client side services, you will need to create a separate API key which can be secured with an HTTP referrers restriction (see Restricting an API key).

https://developers.google.com/maps/documentation/javascript/error-messages

FFS Google... Pretty important piece of information that would be good to clarify on setup...

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

How do I completely rename an Xcode project (i.e. inclusive of folders)?

XCode 11.0+.

It's really simple now. Just go to Project Navigator left panel of the XCode window.
Press Enter to make it active for rename, just like you change the folder name.
enter image description here

Just change the new name here, and XCode will ask you for renaming other pieces of stuff.

enter image description here.

Tap on Rename here and you are done.
If you are confused about your root folder name that why it's not changed, well it's just a folder. just renamed it with a new name.
enter image description here

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

RecyclerView - How to smooth scroll to top of item on a certain position?

Override the calculateDyToMakeVisible/calculateDxToMakeVisible function in LinearSmoothScroller to implement the offset Y/X position

override fun calculateDyToMakeVisible(view: View, snapPreference: Int): Int {
    return super.calculateDyToMakeVisible(view, snapPreference) - ConvertUtils.dp2px(10f)
}

Could not load the Tomcat server configuration

You tried to start Tomcat and got the following error:

Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete

How to solve:

  • Close Eclipse
  • Copy all files from TOMCAT_7_HOME/conf to WORKSPACE_FOLDER/Servers/Tomcat v7.0 Server at localhost-config
  • Start Eclipse
  • Expand the Servers project, click on the Tomcat 7 project and hit F5
  • Start Tomcat from Eclipse

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

npm config set registry "http://registry.npmjs.org"

Solved the issue for me. Note that it wouldn't accecpt a forward slash at the end of the url and it had to be entered exactly as shown above.

RecyclerView: Inconsistency detected. Invalid item position

Use notifyDataSetChanged() instead notifyItem... in this case.

Java - Writing strings to a CSV file

I think this is a simple code in java which will show the string value in CSV after compile this code.

public class CsvWriter {

    public static void main(String args[]) {
        // File input path
        System.out.println("Starting....");
        File file = new File("/home/Desktop/test/output.csv");
        try {
            FileWriter output = new FileWriter(file);
            CSVWriter write = new CSVWriter(output);

            // Header column value
            String[] header = { "ID", "Name", "Address", "Phone Number" };
            write.writeNext(header);
            // Value
            String[] data1 = { "1", "First Name", "Address1", "12345" };
            write.writeNext(data1);
            String[] data2 = { "2", "Second Name", "Address2", "123456" };
            write.writeNext(data2);
            String[] data3 = { "3", "Third Name", "Address3", "1234567" };
            write.writeNext(data3);
            write.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }

        System.out.println("End.");

    }
}

Visual Studio 2015 or 2017 does not discover unit tests

For me upgrading to version 3.7 of NUnit worked.

Android Studio gradle takes too long to build

I had a similar issue on my computer. Windows Defender was blocking some part of Gradle Building. I've disabled it, worked fine after that.

Open web in new tab Selenium + Python

I tried for a very long time to duplicate tabs in Chrome running using action_keys and send_keys on body. The only thing that worked for me was an answer here. This is what my duplicate tabs def ended up looking like, probably not the best but it works fine for me.

def duplicate_tabs(number, chromewebdriver):
#Once on the page we want to open a bunch of tabs
url = chromewebdriver.current_url
for i in range(number):
    print('opened tab: '+str(i))
    chromewebdriver.execute_script("window.open('"+url+"', 'new_window"+str(i)+"')")

It basically runs some java from inside of python, it's incredibly useful. Hope this helps somebody.

Note: I am using Ubuntu, it shouldn't make a difference but if it doesn't work for you this could be the reason.

Getting a "This application is modifying the autolayout engine from a background thread" error?

Swift 4,

Suppose, if you are calling some method using operation queue

operationQueue.addOperation({
            self.searchFavourites()
        })

And suppose function searchFavourites is like,

func searchFavourites() {
     DispatchQueue.main.async {
                    //Your code
                }
}

if you call, all code inside the method "searchFavourites" on the main thread, it will still give an error if you are updating some UI in it.

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread.

So use solution,

operationQueue.addOperation({
            DispatchQueue.main.async {
                self.searchFavourites()
            }
        })

For this kind of scenario.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Sending a file over TCP sockets in Python

Client need to notify that it finished sending, using socket.shutdown (not socket.close which close both reading/writing part of the socket):

...
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()

UPDATE

Client sends Hello server! to the server; which is written to the file in the server side.

s.send("Hello server!")

Remove above line to avoid it.

How do I resolve `The following packages have unmet dependencies`

First, run

sudo apt-get install nodejs-dev node-gyp libssl1.0-dev

then run

sudo apt install npm

Touch move getting stuck Ignored attempt to cancel a touchmove

Please remove e.preventDefault(), because event.cancelable of touchmove is false. So you can't call this method.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

If you're using react native and react-native-firebase, make sure you link up the Google-Services.plist file (https://github.com/invertase/react-native-firebase/issues/313#issuecomment-320435560)

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

Calling one method from another within same class in Python

To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.

class YourClass():

    def your_function(self, *args):

        self.callable_function(param) # if you need to pass any parameter

    def callable_function(self, *params): 
        print('Your param:', param)

Database corruption with MariaDB : Table doesn't exist in engine

Ok folks, I ran into this problem this weekend when my OpenStack environment crashed. Another post about that coming soon on how to recover.

I found a solution that worked for me with a SQL Server instance running under the Ver 15.1 Distrib 10.1.21-MariaDB with Fedora 25 Server as the host. Do not listen to all the other posts that say your database is corrupted if you completely copied your old mariadb-server's /var/lib/mysql directory and the database you are copying is not already corrupted. This process is based on a system where the OS became corrupted but its files were still accessible.

Here are the steps I followed.

  1. Make sure that you have completely uninstalled any current versions of SQL only on the NEW server. Also, make sure ALL mysql-server or mariadb-server processes on the NEW AND OLD servers have been halted by running:

    service mysqld stop or service mariadb stop.

  2. On the NEW SQL server go into the /var/lib/mysql directory and ensure that there are no files at all in this directory. If there are files in this directory then your process for removing the database server from the new machine did not work and is possibly corrupted. Make sure it completely uninstalled from the new machine.

  3. On the OLD SQL server:

    mkdir /OLDMYSQL-DIR cd /OLDMYSQL-DIR tar cvf mysql-olddirectory.tar /var/lib/mysql gzip mysql-olddirectory.tar

  4. Make sure you have sshd running on both the OLD and NEW servers. Make sure there is network connectivity between the two servers.

  5. On the NEW SQL server:

    mkdir /NEWMYSQL-DIR

  6. On the OLD SQL server:

    cd /OLDMYSQL-DIR scp mysql-olddirectory.tar.gz @:/NEWMYSQL-DIR

  7. On the NEW SQL server:

    cd /NEWMYSQL-DIR gunzip mysql-olddirectory.tar.gz OR tar zxvf mysql-olddirectory.tar.gz (if tar zxvf doesn't work) tar xvf mysql-olddirectory.tar.gz

  8. You should now have a "mysql" directory file sitting in the NEWMYSQL-DIR. Resist the urge to run a "cp" command alone with no switches. It will not work. Run the following "cp" command and ensure you use the same switches I did.

    cd mysql/ cp -rfp * /var/lib/mysql/

  9. Now you should have a copy of all of your old SQL server files on the NEW server with permissions in tact. On the NEW SQL server:

    cd /var/lib/mysql/

VERY IMPORTANT STEP. DO NOT SKIP

> rm -rfp ib_logfile*
  1. Now install mariadb-server or mysql-server on the NEW SQL server. If you already have it installed and/or running then you have not followed the directions and these steps will fail.

FOR MARIADB-SERVER and DNF:

> dnf install mariadb-server
> service mariadb restart

FOR MYSQL-SERVER and YUM:

> yum install mysql-server
> service mysqld restart

Xcode 6 Bug: Unknown class in Interface Builder file

In my case, I added a flag -ObjC to Other Linker Flags in project settings to make it work. Also I tried with -all_load flag and it worked well too.

enter image description here

android download pdf from url then open it with a pdf reader

Hi the problem is in FileDownloader class

 urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.

Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)

Attaching the working code with screenshots.

enter image description here

enter image description here

MainActivity.java

package com.example.downloadread;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void download(View v)
    {
        new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf"); 
    }

    public void view(View v)
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }


}

FileDownloader.java

package com.example.downloadread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloadread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="download"
        android:onClick="download" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="38dp"
        android:text="view"
        android:onClick="view" />

</RelativeLayout>

"break;" out of "if" statement?

I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if inside. So, I'll try to answer this question with this particular interpretation.

If you have if inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if or was it ended "naturally"? So, your sample code can be modified in this way:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; break;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

The problem with this code is that the if statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break statement) variant will be:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; continue;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.

UPDATE:

Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break to exit from both loops and switch.

Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.

curl: (60) SSL certificate problem: unable to get local issuer certificate

It is failing as cURL is unable to verify the certificate provided by the server.

There are two options to get this to work:

  1. Use cURL with -k option which allows curl to make insecure connections, that is cURL does not verify the certificate.

  2. Add the root CA (the CA signing the server certificate) to /etc/ssl/certs/ca-certificates.crt

You should use option 2 as it's the option that ensures that you are connecting to secure FTP server.

Python equivalent of a given wget command

import urllib2
import time

max_attempts = 80
attempts = 0
sleeptime = 10 #in seconds, no reason to continuously try if network is down

#while true: #Possibly Dangerous
while attempts < max_attempts:
    time.sleep(sleeptime)
    try:
        response = urllib2.urlopen("http://example.com", timeout = 5)
        content = response.read()
        f = open( "local/index.html", 'w' )
        f.write( content )
        f.close()
        break
    except urllib2.URLError as e:
        attempts += 1
        print type(e)

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

How can I get the IP address from NIC in Python?

Alternatively, if you want to get the IP address of whichever interface is used to connect to the network without having to know its name, you can use this:

import socket
def get_ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    return s.getsockname()[0]

I know it's a little different than your question, but others may arrive here and find this one more useful. You do not have to have a route to 8.8.8.8 to use this. All it is doing is opening a socket, but not sending any data.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

The finalizeQueue may be too long

i think that java may require GC.SuppressFinalize() & GC.ReRegisterForFinalize() to let user reduce the finalizedQueue length explicitly

if the JVM' source code is available, may implement these method ourself, such as android ROM maker

Get MAC address using shell script

Here's an alternative answer in case the ones listed above don't work for you. You can use the following solution(s) as well, which was found here:

ip addr

OR

ip addr show

OR

ip link

All three of these will show your MAC address(es) next to link/ether. I stumbled on this because I had just done a fresh install of Debian 9.5 from a USB stick without internet access, so I could only do a very minimal install, and received

-bash: ifconfig: command not found

when I tried some of the above solutions. I figured somebody else may come across this problem as well. Hope it helps.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

If nothing happens even if you added all the annotation needed, try to add this dependency to your pom.xml, I just faced the same problem and resolved it by adding this one here:

<dependency>
   <groupId>commons-configuration</groupId>
   <artifactId>commons-configuration</artifactId>
   <version>1.9</version>
</dependency>

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

How to make java delay for a few seconds?

A couple problems, you aren't delaying by much (.sleep is milliseconds, not seconds), and you're attempting to print in your catch statement. Your code should look more like:

if (i==1) {
    try {
        System.out.println("Scanning...");
        Thread.sleep(1000); // 1 second
    } catch (InterruptedException ex) {
        // handle error
    }
}

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

Entity Framework rollback and remove bad migration

You have 2 options:

  • You can take the Down from the bad migration and put it in a new migration (you will also need to make the subsequent changes to the model). This is effectively rolling up to a better version.

    I use this option on things that have gone to multiple environments.

  • The other option is to actually run Update-Database –TargetMigration: TheLastGoodMigration against your deployed database and then delete the migration from your solution. This is kinda the hulk smash alternative and requires this to be performed against any database deployed with the bad version.

    Note: to rescaffold the migration you can use Add-Migration [existingname] -Force. This will however overwrite your existing migration, so be sure to do this only if you have removed the existing migration from the database. This does the same thing as deleting the existing migration file and running add-migration

    I use this option while developing.

Excel VBA Password via Hex Editor

If you deal with .xlsm file instead of .xls you can use the old method. I was trying to modify vbaProject.bin in .xlsm several times using DBP->DBx method by it didn't work, also changing value of DBP didn't. So I was very suprised that following worked :
1. Save .xlsm as .xls.
2. Use DBP->DBx method on .xls.
3. Unfortunately some erros may occur when using modified .xls file, I had to save .xls as .xlsx and add modules, then save as .xlsm.

UTF-8 output from PowerShell

Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error

fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported

I solved the problem by changing the line that generated the output file from:

out-file -FilePath GITVersion.h -InputObject $result

to:

out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result

Custom thread pool in Java 8 parallel stream

If you don't mind using a third-party library, with cyclops-react you can mix sequential and parallel Streams within the same pipeline and provide custom ForkJoinPools. For example

 ReactiveSeq.range(1, 1_000_000)
            .foldParallel(new ForkJoinPool(10),
                          s->s.filter(i->true)
                              .peek(i->System.out.println("Thread " + Thread.currentThread().getId()))
                              .max(Comparator.naturalOrder()));

Or if we wished to continue processing within a sequential Stream

 ReactiveSeq.range(1, 1_000_000)
            .parallel(new ForkJoinPool(10),
                      s->s.filter(i->true)
                          .peek(i->System.out.println("Thread " + Thread.currentThread().getId())))
            .map(this::processSequentially)
            .forEach(System.out::println);

[Disclosure I am the lead developer of cyclops-react]

ORA-01843 not a valid month- Comparing Dates

If you don't need to check exact timestamp, use

SELECT * FROM MYTABLE WHERE trunc(DATEIN) = TO_DATE('23-04-49','DD-MM-YY');

otherwise, you can use

SELECT * FROM MYTABLE WHERE DATEIN = TO_DATE('23-04-49 20:18:07','DD-MM-YY HH24:MI:SS');

Here, you use hard code date,if you directly compare then you must use DD-MM-YY HH24:MI:SS else you might get ORA-01849: hour must be between 1 and 12.

Catching KeyboardInterrupt in Python during program shutdown

You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN) before you start your cleanup code.

Cannot find firefox binary in PATH. Make sure firefox is installed

java -jar selenium-server-standalone-2.53.1.jar -Dwebdriver.firefox.bin="C:\Program Files (x86)\Mozilla Firefox\firefox.exe"

Put selenium jar file on desktop, go to cmd and run the above command.

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

In my case, I use nginx as reverse-proxy for an API Gateway URL. I got same error.

I resolved the issue when I added the following two lines to the Nginx config:

proxy_set_header Host "XXXXXX.execute-api.REGION.amazonaws.com";
proxy_ssl_server_name on;

Source is here: Setting up proxy_pass on nginx to make API calls to API Gateway

VirtualBox error "Failed to open a session for the virtual machine"

Killing VM process dint work in my case.

Right click on the VM and click on "Discard Saved State".

 Right click on the VM and click on "Discard Saved State".

This worked for me.

Read line with Scanner


For everybody who still can't read in a simple .txt file with the Java scanner.


I had the problem that the scanner couldn't read in the next line, when I Copy and Pasted the information, or when there was to much text in my file.

The solution is: Coder your .txt file into UTF-8.
This can be done fairly simple by saving opening the file again and changing the coding to UTF-8. (Under Win7 near the bottom right corner)

The Scanner shouldn't have any problem after this.

Log record changes in SQL server in an audit table

Take a look at this article on Simple-talk.com by Pop Rivett. It walks you through creating a generic trigger that will log the OLDVALUE and the NEWVALUE for all updated columns. The code is very generic and you can apply it to any table you want to audit, also for any CRUD operation i.e. INSERT, UPDATE and DELETE. The only requirement is that your table to be audited should have a PRIMARY KEY (which most well designed tables should have anyway).

Here's the code relevant for your GUESTS Table.

  1. Create AUDIT Table.
    IF NOT EXISTS
          (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Audit]') 
                   AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
           CREATE TABLE Audit 
                   (Type CHAR(1), 
                   TableName VARCHAR(128), 
                   PK VARCHAR(1000), 
                   FieldName VARCHAR(128), 
                   OldValue VARCHAR(1000), 
                   NewValue VARCHAR(1000), 
                   UpdateDate datetime, 
                   UserName VARCHAR(128))
    GO
  1. CREATE an UPDATE Trigger on the GUESTS Table as follows.
    CREATE TRIGGER TR_GUESTS_AUDIT ON GUESTS FOR UPDATE
    AS
    
    DECLARE @bit INT ,
           @field INT ,
           @maxfield INT ,
           @char INT ,
           @fieldname VARCHAR(128) ,
           @TableName VARCHAR(128) ,
           @PKCols VARCHAR(1000) ,
           @sql VARCHAR(2000), 
           @UpdateDate VARCHAR(21) ,
           @UserName VARCHAR(128) ,
           @Type CHAR(1) ,
           @PKSelect VARCHAR(1000)
           
    
    --You will need to change @TableName to match the table to be audited. 
    -- Here we made GUESTS for your example.
    SELECT @TableName = 'GUESTS'
    
    -- date and user
    SELECT         @UserName = SYSTEM_USER ,
           @UpdateDate = CONVERT (NVARCHAR(30),GETDATE(),126)
    
    -- Action
    IF EXISTS (SELECT * FROM inserted)
           IF EXISTS (SELECT * FROM deleted)
                   SELECT @Type = 'U'
           ELSE
                   SELECT @Type = 'I'
    ELSE
           SELECT @Type = 'D'
    
    -- get list of columns
    SELECT * INTO #ins FROM inserted
    SELECT * INTO #del FROM deleted
    
    -- Get primary key columns for full outer join
    SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
                   + ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
           FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
    
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE   pk.TABLE_NAME = @TableName
           AND     CONSTRAINT_TYPE = 'PRIMARY KEY'
           AND     c.TABLE_NAME = pk.TABLE_NAME
           AND     c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
    
    -- Get primary key select for insert
    SELECT @PKSelect = COALESCE(@PKSelect+'+','') 
           + '''<' + COLUMN_NAME 
           + '=''+convert(varchar(100),
    coalesce(i.' + COLUMN_NAME +',d.' + COLUMN_NAME + '))+''>''' 
           FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
                   INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE   pk.TABLE_NAME = @TableName
           AND     CONSTRAINT_TYPE = 'PRIMARY KEY'
           AND     c.TABLE_NAME = pk.TABLE_NAME
           AND     c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
    
    IF @PKCols IS NULL
    BEGIN
           RAISERROR('no PK on table %s', 16, -1, @TableName)
           RETURN
    END
    
    SELECT         @field = 0, 
           @maxfield = MAX(ORDINAL_POSITION) 
           FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName
    WHILE @field < @maxfield
    BEGIN
           SELECT @field = MIN(ORDINAL_POSITION) 
                   FROM INFORMATION_SCHEMA.COLUMNS 
                   WHERE TABLE_NAME = @TableName 
                   AND ORDINAL_POSITION > @field
           SELECT @bit = (@field - 1 )% 8 + 1
           SELECT @bit = POWER(2,@bit - 1)
           SELECT @char = ((@field - 1) / 8) + 1
           IF SUBSTRING(COLUMNS_UPDATED(),@char, 1) & @bit > 0
                                           OR @Type IN ('I','D')
           BEGIN
                   SELECT @fieldname = COLUMN_NAME 
                           FROM INFORMATION_SCHEMA.COLUMNS 
                           WHERE TABLE_NAME = @TableName 
                           AND ORDINAL_POSITION = @field
                   SELECT @sql = '
    insert Audit (    Type, 
                   TableName, 
                   PK, 
                   FieldName, 
                   OldValue, 
                   NewValue, 
                   UpdateDate, 
                   UserName)
    select ''' + @Type + ''',''' 
           + @TableName + ''',' + @PKSelect
           + ',''' + @fieldname + ''''
           + ',convert(varchar(1000),d.' + @fieldname + ')'
           + ',convert(varchar(1000),i.' + @fieldname + ')'
           + ',''' + @UpdateDate + ''''
           + ',''' + @UserName + ''''
           + ' from #ins i full outer join #del d'
           + @PKCols
           + ' where i.' + @fieldname + ' <> d.' + @fieldname 
           + ' or (i.' + @fieldname + ' is null and  d.'
                                    + @fieldname
                                    + ' is not null)' 
           + ' or (i.' + @fieldname + ' is not null and  d.' 
                                    + @fieldname
                                    + ' is null)' 
                   EXEC (@sql)
           END
    END
    
    GO

How to check if bootstrap modal is open, so I can use jquery validate?

On bootstrap-modal.js v2.2.0:

( $('element').data('modal') || {}).isShown

SSL Connection / Connection Reset with IISExpress

The issue that I had was related to @Jason Kleban's answer, but I had one small problem with my settings in the Visual Studio Properties for IIS Express.

Make sure that after you've changed the port to be in the range: 44300 to 44399, the address also starts with HTTPS

enter image description here

LEFT JOIN in LINQ to entities?

You can read an article i have written for joins in LINQ here

var query = 
from  u in Repo.T_Benutzer
join bg in Repo.T_Benutzer_Benutzergruppen
    on u.BE_ID equals bg.BEBG_BE
into temp
from j in temp.DefaultIfEmpty()
select new
{
    BE_User = u.BE_User,
    BEBG_BG = (int?)j.BEBG_BG// == null ? -1 : j.BEBG_BG
            //, bg.Name 
}

The following is the equivalent using extension methods:

var query = 
Repo.T_Benutzer
.GroupJoin
(
    Repo.T_Benutzer_Benutzergruppen,
    x=>x.BE_ID,
    x=>x.BEBG_BE,
    (o,i)=>new {o,i}
)
.SelectMany
(
    x => x.i.DefaultIfEmpty(),
    (o,i) => new
    {
        BE_User = o.o.BE_User,
        BEBG_BG = (int?)i.BEBG_BG
    }
);

How to fix corrupt HDFS FIles

start all daemons and run the command as "hadoop namenode -recover -force" stop the daemons and start again.. wait some time to recover data.

How to fix corrupted git repository?

I wanted to add this as a comment under Zoey Hewil's awesome answer above, but I don't currently have enough rep to do so, so I have to add it here and give credit for her work :P

If you're using Poshgit and are feeling exceptionally lazy, you can use the following to automatically extract your URL from your git config and make an easy job even easier. Standard caveats apply about testing this on a copy/backing up your local repo first in case it blows up in your face.

$config = get-content .git\config
$url = $config -match " url = (?<content>.*)"
$url = $url.trim().Substring(6)
$url

move-item -v .git .git_old;
git init;
git remote add origin "$url";
git fetch;
git reset origin/master --mixed

How to process SIGTERM signal gracefully?

I think you are near to a possible solution.

Execute mainloop in a separate thread and extend it with the property shutdown_flag. The signal can be caught with signal.signal(signal.SIGTERM, handler) in the main thread (not in a separate thread). The signal handler should set shutdown_flag to True and wait for the thread to end with thread.join()

Java Multithreading concept and join() method

I came across the join() while learning about race condition and I will clear the doubts I was having. So let us take this small example

Thread t2 = new Thread(
             new Runnable() {
                 public void run () {
                     //do something
                 }
              }
);
Thread t1 = new Thread(
             new Runnable() {
                 public void run () {
                     //do something
                 }
              }
);
t2.start(); //Line 11
t1.start(); //Line 12
t2.join();  //Line 13
t1.join();  //Line 14
System.out.print("<Want to print something that was being modified by t2 and t1>")

My AIM
Three threads are running namely t1, t2 and the main thread. I want to print something after the t1 and t2 has finished. The printing operation is on my main thread therefore for the expected answer I need to let t1 and t2 finish and then print my output.

So t1.join() just makes the main thread wait, till the t1 thread completes before going to the next line in program.

Here is the definition as per GeeksforGeeks:

java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution.

Here is one question that might solve your doubt

Q-> Will t1 thread get the time slice to run by the thread scheduler, when the program is processing the t2.join() at Line 13?

ANS-> Yes it will be eligible to get the time slice to run as we have already made it eligible by running the line t1.start() at Line 11.
t2.join() only applies the condition when the JVM will go to next line, that is Line 14.
It might be also possible that t1 might get finished processing at Line 13.

stale element reference: element is not attached to the page document

What is the line which gives exception ??

The reason for this is because the element to which you have referred is removed from the DOM structure

I was facing the same problem while working with IEDriver. The reason was because javascript loaded the element one more time after i have referred so my date reference pointed to an unexisting object even if it was right their on UI. I used the following workaround.

try {
    WebElement date = driver.findElement(By.linkText(Utility.getSheetData(path, 7, 1, 2)));
    date.click();
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
    WebElement date = driver.findElement(By.linkText(Utility.getSheetData(path, 7, 1, 2)));
    date.click();
}

See if the same can help you !

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

Long story short, it probably doesn't matter. Use whichever you think looks nicest.

Longer answer, using Oracle's Java 7 JDK specifically, since this isn't defined at the JLS:

String.valueOf or Character.toString work the same way, so use whichever you feel looks nicer. In fact, Character.toString simply calls String.valueOf (source).

So the question is, should you use one of those or String.substring. Here again it doesn't matter much. String.substring uses the original string's char[] and so allocates one object fewer than String.valueOf. This also prevents the original string from being GC'ed until the one-character string is available for GC (which can be a memory leak), but in your example, they'll both be available for GC after each iteration, so that doesn't matter. The allocation you save also doesn't matter -- a char[1] is cheap to allocate, and short-lived objects (as the one-char string will be) are cheap to GC, too.

If you have a large enough data set that the three are even measurable, substring will probably give a slight edge. Like, really slight. But that "if... measurable" contains the real key to this answer: why don't you just try all three and measure which one is fastest?

jQuery $.cookie is not a function

Solve jQuery $.cookie is not a function this Problem jquery cdn update in solve this problem

 <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>

XAMPP - MySQL shutdown unexpectedly

Rename below files from mysql/data ib_logfile0 ib_logfile1 ibdata1

my.cnf innodb_buffer_pool_size to 200M as per your ram innodb_log_buffer_size to 32M

Restart your apache server

hope it helps you

Concept behind putting wait(),notify() methods in Object class

wait - wait method tells the current thread to give up monitor and go to sleep.

notify - Wakes up a single thread that is waiting on this object's monitor.

So you see wait() and notify() methods work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait() method and through notify method (or notifyAll) threads which are waiting on the object's monitor are notified that threads can wake up.

Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class. To reiterate threads wait on an Object's monitor (lock) and notify() is also called on an object to wake up a thread waiting on the Object's monitor.

How is CountDownLatch used in Java Multithreading?

CountDownLatch in Java is a type of synchronizer which allows one Thread to wait for one or more Threads before it starts processing.

CountDownLatch works on latch principle, thread will wait until gate is open. One thread waits for n number of threads specified while creating CountDownLatch.

e.g. final CountDownLatch latch = new CountDownLatch(3);

Here we set the counter to 3.

Any thread, usually main thread of application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another Thread. All other threads are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, the Thread awaiting starts running.

Here the count is get decremented by CountDownLatch.countDown() method.

The Thread which calls the await() method will wait until the initial count reaches to zero.

To make count zero other threads need to call the countDown() method. Once the count become zero the thread which invoked the await() method will resume (start its execution).

The disadvantage of CountDownLatch is that it's not reusable: once the count become zero it is no longer usable.

PHP - get base64 img string decode and save as jpg (resulting empty image )

A minor simplification on the example by @naresh. Should deal with permission issues and offer some clarification.

$data = '<base64_encoded_string>';

$data = base64_decode($data);

$img = imagecreatefromstring($data);

header('Content-Type: image/png');

$file = '<path_to_home_or_user_directory>/decoded_images/test.png';

imagepng($img, $file);

imagedestroy($img);

How do I change the UUID of a virtual disk?

Even though this question asked is old, note that changing a UUID on a virtual HDD in a windows system will make windows treat it as a not activated machine (as it notices the disk change) and will ask for reactivation !

Java - creating a new thread

Please try this. You will understand all perfectly after you will take a look on my solution.

There are only 2 ways of creating threads in java

with implements Runnable

class One implements Runnable {
@Override
public void run() {
    System.out.println("Running thread 1 ... ");
}

with extends Thread

class Two extends Thread {
@Override
public void run() {
    System.out.println("Running thread 2 ... ");
}

Your MAIN class here

public class ExampleMain {
public static void main(String[] args) {

    One demo1 = new One();
    Thread t1 = new Thread(demo1);
    t1.start();

    Two demo2 = new Two();
    Thread t2 = new Thread(demo2);
    t2.start();
}

}

Using jQuery's ajax method to retrieve images as a blob

You can't do this with jQuery ajax, but with native XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        //this.response is what you're looking for
        handler(this.response);
        console.log(this.response, typeof this.response);
        var img = document.getElementById('img');
        var url = window.URL || window.webkitURL;
        img.src = url.createObjectURL(this.response);
    }
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();      

EDIT

So revisiting this topic, it seems it is indeed possible to do this with jQuery 3

_x000D_
_x000D_
jQuery.ajax({_x000D_
        url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
        cache:false,_x000D_
        xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
            var xhr = new XMLHttpRequest();_x000D_
            xhr.responseType= 'blob'_x000D_
            return xhr;_x000D_
        },_x000D_
        success: function(data){_x000D_
            var img = document.getElementById('img');_x000D_
            var url = window.URL || window.webkitURL;_x000D_
            img.src = url.createObjectURL(data);_x000D_
        },_x000D_
        error:function(){_x000D_
            _x000D_
        }_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
_x000D_
_x000D_

or

use xhrFields to set the responseType

_x000D_
_x000D_
    jQuery.ajax({_x000D_
            url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
            cache:false,_x000D_
            xhrFields:{_x000D_
                responseType: 'blob'_x000D_
            },_x000D_
            success: function(data){_x000D_
                var img = document.getElementById('img');_x000D_
                var url = window.URL || window.webkitURL;_x000D_
                img.src = url.createObjectURL(data);_x000D_
            },_x000D_
            error:function(){_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
    <img id="img" width=100%>
_x000D_
_x000D_
_x000D_

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

To add to the above: If interrupt is not working, you can restart the kernel.

Go to the kernel dropdown >> restart >> restart and clear output. This usually does the trick. If this still doesn't work, kill the kernel in the terminal (or task manager) and then restart.

Interrupt doesn't work well for all processes. I especially have this problem using the R kernel.

How can I wait for 10 second without locking application UI in android

do this on a new thread (seperate it from main thread)

 new Thread(new Runnable() {
     @Override
     public void run() {
        // TODO Auto-generated method stub
     }
}).run();

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Printing Even and Odd using two Threads in Java

package pkgscjp;

public class OddPrint implements Runnable {

    public static boolean flag = true;

    public void run() {
        for (int i = 1; i <= 99;) {
            if (flag) {
                System.out.println(i);
                flag = false;
                i = i + 2;
            }
        }
    }

}


package pkgscjp;

public class EvenPrint implements Runnable {
    public void run() {
        for (int i = 2; i <= 100;) {
            if (!OddPrint.flag) {
                System.out.println(i);
                OddPrint.flag = true;
                i = i + 2;
            }
        }

    }
}


package pkgscjp;

public class NaturalNumberThreadMain {
    public static void main(String args[]) {
        EvenPrint ep = new EvenPrint();
        OddPrint op = new OddPrint();
        Thread te = new Thread(ep);
        Thread to = new Thread(op);
        to.start();
        te.start();

    }

}

How do I deserialize a complex JSON object in C# .NET?

First install newtonsoft.json package to Visual Studio using NuGet Package Manager then add the following code:

ClassName ObjectName = JsonConvert.DeserializeObject < ClassName > (jsonObject);

TypeError: $(...).autocomplete is not a function

you missed jquery ui library. Use CDN of Jquery UI or if you want it locally then download the file from Jquery Ui

<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="YourJquery source path"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

Hibernate Error: a different object with the same identifier value was already associated with the session

In addition to all the previous answers, a possible fix to this problem in a large scale project, if your using a Value Object for your classes don't set the id attribute in the VO Transformer class.

What does this thread join code mean?

join() means waiting for a thread to complete. This is a blocker method. Your main thread (the one that does the join()) will wait on the t1.join() line until t1 finishes its work, and then will do the same for t2.join().

Text overflow ellipsis on two lines

In my angular app the following style worked for me to achieve ellipsis on the overflow of text on the second line:

 <div style="height:45px; overflow: hidden; position: relative;">
     <span class=" block h6 font-semibold clear" style="overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box; 
        line-height: 20px; /* fallback */
        max-height: 40px; /* fallback */
        -webkit-line-clamp: 2; /* number of lines to show */
        -webkit-box-orient: vertical;">
        {{ event?.name}} </span>
 </div>

Hope it helps someone.

How to set delay in android?

If you use delay frequently in your app, use this utility class

import android.os.Handler;


public class Utils {

    // Delay mechanism

    public interface DelayCallback{
        void afterDelay();
    }

    public static void delay(int secs, final DelayCallback delayCallback){
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                delayCallback.afterDelay();
            }
        }, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
    }
}

Usage:

// Call this method directly from java file

int secs = 2; // Delay in seconds

Utils.delay(secs, new Utils.DelayCallback() {
    @Override
    public void afterDelay() {
        // Do something after delay

    }
});

Do HttpClient and HttpClientHandler have to be disposed between requests?

Since it doesn't appear that anyone has mentioned it here yet, the new best way to manage HttpClient and HttpClientHandler in .NET Core 2.1 is using HttpClientFactory.

It solves most of the aforementioned issues and gotchas in a clean and easy-to-use way. From Steve Gordon's great blog post:

Add the following packages to your .Net Core (2.1.1 or later) project:

Microsoft.AspNetCore.All
Microsoft.Extensions.Http

Add this to Startup.cs:

services.AddHttpClient();

Inject and use:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    private readonly IHttpClientFactory _httpClientFactory;

    public ValuesController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    [HttpGet]
    public async Task<ActionResult> Get()
    {
        var client = _httpClientFactory.CreateClient();
        var result = await client.GetStringAsync("http://www.google.com");
        return Ok(result);
    }
}

Explore the series of posts in Steve's blog for lots more features.

How can I run code on a background thread on Android?

I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible?

Most likely mechanizm that you are looking for is AsyncTask. It directly designated for performing background process on background Thread. Also its main benefit is that offers a few methods which run on Main(UI) Thread and make possible to update your UI if you want to annouce user about some progress in task or update UI with data retrieved from background process.

If you don't know how to start here is nice tutorial:

Note: Also there is possibility to use IntentService with ResultReceiver that works as well.

Exception in thread "main" java.util.NoSuchElementException

Everyone explained pretty well on it. Let me answer when should this class be used.

When Should You Use NoSuchElementException?

Java includes a few different ways to iterate through elements in a collection. The first of these classes, Enumeration, was introduced in JDK1.0 and is generally considered deprecated in favor of newer iteration classes, like Iterator and ListIterator.

As with most programming languages, the Iterator class includes a hasNext() method that returns a boolean indicating if the iteration has anymore elements. If hasNext() returns true, then the next() method will return the next element in the iteration. Unlike Enumeration, Iterator also has a remove() method, which removes the last element that was obtained via next().

While Iterator is generalized for use with all collections in the Java Collections Framework, ListIterator is more specialized and only works with List-based collections, like ArrayList, LinkedList, and so forth. However, ListIterator adds even more functionality by allowing iteration to traverse in both directions via hasPrevious() and previous() methods.

How to wait for async method to complete?

The following snippet shows a way to ensure the awaited method completes before returning to the caller. HOWEVER, I wouldn't say it's good practice. Please edit my answer with explanations if you think otherwise.

public async Task AnAsyncMethodThatCompletes()
{
    await SomeAsyncMethod();
    DoSomeMoreStuff();
    await Task.Factory.StartNew(() => { }); // <-- This line here, at the end
}

await AnAsyncMethodThatCompletes();
Console.WriteLine("AnAsyncMethodThatCompletes() completed.")

Arrays vs Vectors: Introductory Similarities and Differences

I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).

Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.

What does 'corrupted double-linked list' mean

This might be caused due to different reasons, some user have mentioned other possibilities and I add my case:

I got this error when using multi-threading (both std::pthread and std::thread) and the error occurred because I forgot to lock a variable which multi threads may change at the same time. this error comes randomly in some runs but not all because ... you know accident between to threads is random.

That variable in my case was a global std::vector which I tried to push_back() something into it in a function called by threads.. and then I used a std::mutex and never got this error again.

may help some

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I faced the same issue, I tried the below solution and it worked for me In Android SDK Manager Window, click on Tools->Options-> under "Others", check "Force https://... sources to be fetched using http://..."

Kill Attached Screen in Linux

For result find: Click Here

Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells. There is a scrollback history buffer for each virtual terminal and a copy-and-paste mechanism that allows the user to move text regions between windows.

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I am a newbie to the iOS app development. I was practising to develop iOS apps from the very beginning and while running a very basic Hello World app, I also faced same issue that only a black blank screen appears after building and running the app in iOS simulator. Somehow while struggling to find out a solution to the problem I accidentally clicked Window-->Scale-->50% in iOS simulator and it did solve my problem. I could then see the Home page with my app and clicking on app icon I was able to run my app successfully. App versions: Xcode 5.1 iOS Simulator: 7.1 OSX: 10.9.3

How to restart a rails server on Heroku?

If you have several heroku apps, you must type heroku restart --app app_name or heroku restart -a app_name

"Large data" workflows using pandas

If your datasets are between 1 and 20GB, you should get a workstation with 48GB of RAM. Then Pandas can hold the entire dataset in RAM. I know its not the answer you're looking for here, but doing scientific computing on a notebook with 4GB of RAM isn't reasonable.

byte array to pdf

Usually this happens if something is wrong with the byte array.

File.WriteAllBytes("filename.PDF", Byte[]);

This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

Asynchronous implementation of this is also available.

public static System.Threading.Tasks.Task WriteAllBytesAsync 
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);

Double free or corruption after queue::push

You can also try to check null before delete such that

if(myArray) { delete[] myArray; myArray = NULL; }

or you can define all delete operations ina safe manner like this:

#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p) { delete (p); (p) = NULL; } }
#endif

#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p) = NULL; } }
#endif

and then use

SAFE_DELETE_ARRAY(myArray);

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

Corrupted Access .accdb file: "Unrecognized Database Format"

Try to create a new database and import every table, query etc into this new database. With this import Access recreates all the objects from scratch. If there is some sort of corruption in an object, it should be solved.

If you're Lucky only the corrupted item(s) will be lost, if any.

Hive load CSV with commas in quoted fields

keep the delimiter in single quotes it will work.

ROW FORMAT DELIMITED 
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';

This will work

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:

RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’

And from there I ran a restore statement with MOVE using logical names.

RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'

When it was done restoring, I almost wept with joy.

Good luck!

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

How to save an HTML5 Canvas as an image on a server?

Here is an example of how to achieve what you need:

  1. Draw something (taken from canvas tutorial)

_x000D_
_x000D_
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // begin custom shape
  context.beginPath();
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);

  // complete custom shape
  context.closePath();
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.fill();
  context.strokeStyle = 'blue';
  context.stroke();
</script>
_x000D_
_x000D_
_x000D_

  1. Convert canvas image to URL format (base64)

    var dataURL = canvas.toDataURL();

  2. Send it to your server via Ajax

_x000D_
_x000D_
    $.ajax({
      type: "POST",
      url: "script.php",
      data: { 
         imgBase64: dataURL
      }
    }).done(function(o) {
      console.log('saved'); 
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.
    });
_x000D_
_x000D_
_x000D_

  1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):

How to kill a while loop with a keystroke?

The easiest way is to just interrupt it with the usual Ctrl-C (SIGINT).

try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

Since Ctrl-C causes KeyboardInterrupt to be raised, just catch it outside the loop and ignore it.

How do I shut down a python simpleHTTPserver?

or you can just do kill %1, which will kill the first job put in background

The cause of "bad magic number" error when loading a workspace and how to avoid it?

I got that error when I accidentally used load() instead of source() or readRDS().

Failure during conversion to COFF: file invalid or corrupt

I had this issue and I solved it with this thread

disable incremental linking, by going to

    Project Properties 
       -> Configuration Properties 
           -> Linker (General) 
              -> Enable Incremental Linking -> "No (/INCREMENTAL:NO)"

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

Read CSV file column by column

Well, how about this !!

This code calculates both row and column count in a csv file. Try this out !!

    static int[] getRowsColsNo() {
    Scanner scanIn = null;
    int rows = 0;
    int cols = 0;
    String InputLine = "";
    try {
        scanIn = new Scanner(new BufferedReader(
                new FileReader("filename.csv")));
        scanIn.useDelimiter(",");
        while (scanIn.hasNextLine()) {
            InputLine = scanIn.nextLine();
            String[] InArray = InputLine.split(",");
            rows++;
            cols = InArray.length;
        }

    } catch (Exception e) {
        System.out.println(e);
    }
    return new int[] { rows, cols };
}

Could not autowire field in spring. why?

I've faced the same issue today. Turned out to be I forgot to mention @Service/@Component annotation for my service implementation file, for which spring is not able autowire and failing to create the bean.

How to output (to a log) a multi-level array in a format that is human-readable?

http://php.net/manual/en/function.print-r.php This function can be used to format output,

$output = print_r($array,1);

$output is a string variable, it can be logged like every other string. In pure php you can use trigger_error

Ex. trigger_error($output);

http://php.net/manual/en/function.trigger-error.php

if you need to format it also in html, you can use <pre> tag

How to fix Git error: object file is empty?

In my case, this error occurred because I was typing the commit message and my notebook turned off.

I did these steps to fix the error:

  • git checkout -b backup-branch # Create a backup branch
  • git reset --hard HEAD~4 # Reset to the commit where everything works well. In my case, I had to back 4 commits in the head, that is until my head be at the point before I was typing the commit message. Before doing this step, copy the hash of the commits you will reset, in my case I copied the hash of the 4 last commits
  • git cherry-pick <commit-hash> # Cherry pick the reseted commits (in my case are 4 commits, so I did this step 4 times) from the old branch to the new branch.
  • git push origin backup-branch # Push the new branch to be sure everything works well
  • git branch -D your-branch # Delete the branch locally ('your-branch' is the branch with problem)
  • git push origin :your-branch # Delete the branch from remote
  • git branch -m backup-branch your-branch # Rename the backup branch to have the name of the branch that had the problem
  • git push origin your-branch # Push the new branch
  • git push origin :backup-branch # Delete the backup branch from remote

deleted object would be re-saved by cascade (remove deleted object from associations)

Kind of Inception going on here.

for (PlaylistadMap playlistadMap : playlistadMaps) {
        PlayList innerPlayList = playlistadMap.getPlayList();
        for (Iterator<PlaylistadMap> iterator = innerPlayList.getPlaylistadMaps().iterator(); iterator.hasNext();) {
            PlaylistadMap innerPlaylistadMap = iterator.next();
            if (innerPlaylistadMap.equals(PlaylistadMap)) {
                iterator.remove();
                session.delete(innerPlaylistadMap);
            }
        }
    }

.gitignore is ignored by Git

One thing to also look at: Are you saving your .gitignore file with the correct line endings?

Windows:

If you're using it on Windows, are you saving it with Windows line endings? Not all programs will do this by default; Notepad++ and many PHP editors default to Linux line endings so the files will be server compatible. One easy way to check this, is open the file in Windows Notepad. If everything appears on one line, then the file was saved with Linux line endings.

Linux:

If you are having trouble with the file working in a Linux environment, open the file in an editor such as Emacs or nano. If you see any non-printable characters, then the file was saved with Windows line endings.

How do we use runOnUiThread in Android?

Just wrap it as a function, then call this function from your background thread.

public void debugMsg(String msg) {
    final String str = msg;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mInfo.setText(str);
        }
    });
}

Hibernate error: ids for this class must be manually assigned before calling save():

For hibernate it is important to know that your object WILL have an id, when you want to persist/save it. Thus, make sure that

    private String U_id;

will have a value, by the time you are going to persist your object. You can do that with the @GeneratedValue annotation or by assigning a value manually.

In the case you need or want to assign your id's manually (and that's what the above error is actually about), I would prefer passing the values for the fields to your constructor, at least for U_id, e.g.

  public Role (String U_id) { ... }

This ensures that your object has an id, by the time you have instantiated it. I don't know what your use case is and how your application behaves in concurrency, however, in some cases this is not recommended. You need to ensure that your id is unique.

Further note: Hibernate will still require a default constructor, as stated in the hibernate documentation. In order to prevent you (and maybe other programmers if you're designing an api) of instantiations of Role using the default constructor, just declare it as private.

Driver executable must be set by the webdriver.ie.driver system property

I just put the driver files directly into my project to not get any dependency to my local machine.

final File file = new File("driver/chromedriver_2_22_mac");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());

driver = new ChromeDriver();

How to properly stop the Thread in Java?

In the IndexProcessor class you need a way of setting a flag which informs the thread that it will need to terminate, similar to the variable run that you have used just in the class scope.

When you wish to stop the thread, you set this flag and call join() on the thread and wait for it to finish.

Make sure that the flag is thread safe by using a volatile variable or by using getter and setter methods which are synchronised with the variable being used as the flag.

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
    private volatile boolean running = true;

    public void terminate() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                running = false;
            }
        }

    }
}

Then in SearchEngineContextListener:

public class SearchEngineContextListener implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);

    private Thread thread = null;
    private IndexProcessor runnable = null;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        runnable = new IndexProcessor();
        thread = new Thread(runnable);
        LOGGER.debug("Starting thread: " + thread);
        thread.start();
        LOGGER.debug("Background process successfully started.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        LOGGER.debug("Stopping thread: " + thread);
        if (thread != null) {
            runnable.terminate();
            thread.join();
            LOGGER.debug("Thread successfully stopped.");
        }
    }
}

Fragment MyFragment not attached to Activity

I had a similar error message "Fragment MyFragment not attached to Context" in Xamarine Android.

this error messege getting because of this resource calling

button.Text = Resources.GetString(Resource.String.please_wait)

I did fix that by using in Xamarine Android.

if (Context != null && IsAdded){ 
    button.Text = Resources.GetString(Resource.String.please_wait);
}

Understanding Matlab FFT example

There are some misconceptions here.

Frequencies above 500 can be represented in an FFT result of length 1000. Unfortunately these frequencies are all folded together and mixed into the first 500 FFT result bins. So normally you don't want to feed an FFT a signal containing any frequencies at or above half the sampling rate, as the FFT won't care and will just mix the high frequencies together with the low ones (aliasing) making the result pretty much useless. That's why data should be low-pass filtered before being sampled and fed to an FFT.

The FFT returns amplitudes without frequencies because the frequencies depend, not just on the length of the FFT, but also on the sample rate of the data, which isn't part of the FFT itself or it's input. You can feed the same length FFT data at any sample rate, as thus get any range of frequencies out of it.

The reason the result plots ends at 500 is that, for any real data input, the frequencies above half the length of the FFT are just mirrored repeats (complex conjugated) of the data in the first half. Since they are duplicates, most people just ignore them. Why plot duplicates? The FFT calculates the other half of the result for people who feed the FFT complex data (with both real and imaginary components), which does create two different halves.

Function to Calculate a CRC16 Checksum

This function works for CRC-16 Modbus version. Not for CRC-16

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

I normally use this statement:

ALTER TABLE `table_name`
  CHANGE COLUMN `col_name` `col_name` VARCHAR(10000);

But, I think SET will work too, never have tried it. :)

How to repair a serialized string which has been corrupted by an incorrect byte count length?

This error is caused because your charset is wrong.

Set charset after open tag:

header('Content-Type: text/html; charset=utf-8');

And set charset utf8 in your database :

mysql_query("SET NAMES 'utf8'");

Subversion stuck due to "previous operation has not finished"?

I tried removing the .svn folder to other location and placed it back in the same root folder. After when I tried to update the SVN, it got updated. I don't know how exactly it worked.

How do I add an "Add to Favorites" button or link on my website?

This code is the corrected version of iambriansreed's answer:

<script type="text/javascript">
    $(function() {
        $("#bookmarkme").click(function() {
            // Mozilla Firefox Bookmark
            if ('sidebar' in window && 'addPanel' in window.sidebar) { 
                window.sidebar.addPanel(location.href,document.title,"");
            } else if( /*@cc_on!@*/false) { // IE Favorite
                window.external.AddFavorite(location.href,document.title); 
            } else { // webkit - safari/chrome
                alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
            }
        });
    });
</script>

PHP-FPM and Nginx: 502 Bad Gateway

I'm very late to this game, but my problem started when I upgraded php on my server. I was able to just remove the .socket file and restart my services. Then, everything worked. Not sure why it made a difference, since the file is size 0 and the ownership and permissions are the same, but it worked.

MVC: How to Return a String as JSON

All answers here provide good and working code. But someone would be dissatisfied that they all use ContentType as return type and not JsonResult.

Unfortunately JsonResult is using JavaScriptSerializer without option to disable it. The best way to get around this is to inherit JsonResult.

I copied most of the code from original JsonResult and created JsonStringResult class that returns passed string as application/json. Code for this class is below

public class JsonStringResult : JsonResult
    {
        public JsonStringResult(string data)
        {
            JsonRequestBehavior = JsonRequestBehavior.DenyGet;
            Data = data;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Get request is not allowed!");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                response.Write(Data);
            }
        }
    }

Example usage:

var json = JsonConvert.SerializeObject(data);
return new JsonStringResult(json);

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was

excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
    Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
    Excel.XlSaveConflictResolution.xlUserResolution, true, 
    Missing.Value, Missing.Value, Missing.Value);

I hope this helps someone else in the future.


Missing.Value is found in the System.Reflection namespace.

AsyncTask Android example

Shortest example for just doing something asynchronously:

class MyAsyncTask extends android.os.AsyncTask {
    @Override
    protected Object doInBackground(Object[] objects) {
        // Do something asynchronously
        return null;
    }
}

To run it:

(new MyAsyncTask()).execute();

python xlrd unsupported format, or corrupt file.

Sometimes help to add ?raw=true at the end of a file path. For example:

wb = xlrd.open_workbook("Z:\\Data\\Locates\\3.8 locates.xls?raw=true")

Android Use Done button on Keyboard to click button

max.setOnKeyListener(new OnKeyListener(){
  @Override
  public boolean onKey(View v, int keyCode, KeyEvent event){
    if(keyCode == event.KEYCODE_ENTER){
        //do what you want
    }
  }
});

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

I had a similar problem and although I made sure that referenced entities were saved first it keeps failing with the same exception. After hours of investigation it turns out that the problem was because the "version" column of the referenced entity was NULL. In my particular setup i was inserting it first in an HSQLDB(that was a unit test) a row like that:

INSERT INTO project VALUES (1,1,'2013-08-28 13:05:38','2013-08-28 13:05:38','aProject','aa',NULL,'bb','dd','ee','ff','gg','ii',NULL,'LEGACY','0','CREATED',NULL,NULL,1,'0',NULL,NULL,NULL,NULL,'0','0', NULL);

The problem of the above is the version column used by hibernate was set to null, so even if the object was correctly saved, Hibernate considered it as unsaved. When making sure the version had a NON-NULL(1 in this case) value the exception disappeared and everything worked fine.

I am putting it here in case someone else had the same problem, since this took me a long time to figure this out and the solution is completely different than the above.

Throwing exceptions in a PHP Try Catch block

To rethrow do

 throw $e;

not the message.

Creating virtual directories in IIS express

In VS2013 I did this in the following steps:

1.Right-click the web application project and hit Properties

2.View the "Web" tab of the Properties page

3.Under Servers, with "IIS Express" being the default choice of the dropdown, in the "Project Url" change the url using the port number to one that suits you. For example I deleted the port number and added "/MVCDemo4" after the localhost.

4.Click the "Create Virtual Directory" button.

5.Run your project and the new url will be used

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Once you have detected the bounding box of the document, you can perform a four-point perspective transform to obtain a top-down birds eye view of the image. This will fix the skew and isolate only the desired object.


Input image:

Detected text object

Top-down view of text document

Code

from imutils.perspective import four_point_transform
import cv2
import numpy

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7,7), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Find contours and sort for largest contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None

for c in cnts:
    # Perform contour approximation
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    if len(approx) == 4:
        displayCnt = approx
        break

# Obtain birds' eye view of image
warped = four_point_transform(image, displayCnt.reshape(4, 2))

cv2.imshow("thresh", thresh)
cv2.imshow("warped", warped)
cv2.imshow("image", image)
cv2.waitKey()

Run CSS3 animation only once (at page loading)

After hours of googling: No, it's not possible without JavaScript. The animation-iteration-count: 1; is internally saved in the animation shothand attribute, which gets resetted and overwritten on :hover. When we blur the <a> and release the :hover the old class reapplies and therefore again resets the animation attribute.

There sadly is no way to save a certain attribute states across element states.

You'll have to use JavaScript.

How can I interrupt a running code in R with a keyboard command?

Self Answer (pretty much summary of other's comments and answers):

  • In RStudio, Esc works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).

  • If the process is ran in say ubuntu shell (and this is not R specific), for example using:

    Rscript my_file.R
    

    Ctrl + c kills the process

    Ctrl + z suspends the process

  • Within R shell, Ctrl + C kills helps you escape it

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Android: show/hide status bar/power bar

For Some People, Showing status bar by clearing FLAG_FULLSCREEN may not work,

Here is the solution that worked for me, (Documentation) (Flag Reference)

Hide Status Bar

// Hide Status Bar
if (Build.VERSION.SDK_INT < 16) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
   View decorView = getWindow().getDecorView();
  // Hide Status Bar.
   int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
   decorView.setSystemUiVisibility(uiOptions);
}

Show Status Bar

   if (Build.VERSION.SDK_INT < 16) {
              getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    else {
       View decorView = getWindow().getDecorView();
      // Show Status Bar.
       int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
       decorView.setSystemUiVisibility(uiOptions);
    }

Correct way to quit a Qt program?

//How to Run App

bool ok = QProcess::startDetached("C:\\TTEC\\CozxyLogger\\CozxyLogger.exe");
qDebug() <<  "Run = " << ok;


//How to Kill App

system("taskkill /im CozxyLogger.exe /f");
qDebug() << "Close";

example

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

You should trigger the animation to revert once it's completed w/ javascript.

  $(".item").live("animationend webkitAnimationEnd", function(){
    $(this).removeClass('animate');
  });

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

Apply these two things.

  1. You need to set the character set of your database to be utf8.

  2. You need to call the mysql_set_charset('utf8') in the file where you made the connection with the database and right after the selection of database like mysql_select_db use the mysql_set_charset. That will allow you to add and retrieve data properly in whatever the language.

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

MySQL > Table doesn't exist. But it does (or it should)

Had a similar problem with a ghost table. Thankfully had an SQL dump from before the failure.

In my case, I had to:

  1. Stop mySQL
  2. Move ib* files from /var/mysql off to a backup
  3. Delete /var/mysql/{dbname}
  4. Restart mySQL
  5. Recreate empty database
  6. Restore dump file

NOTE: Requires dump file.

Subtract 1 day with PHP

How to add 1 year to a date and then subtract 1 day from it in asp.net c#

Convert.ToDateTime(txtDate.Value.Trim()).AddYears(1).AddDays(-1);

Corrupt jar file

This is the common issue with "manifest" in the error? Yes it happens a lot, here's a link: http://dev-answers.blogspot.com/2006/07/invalid-or-corrupt-jarfile.html

Solution:

Using the ant task to create the manifest file on-the-fly gives you and entry like:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.2
Created-By: 1.4.2_07-b05 (Sun Microsystems Inc.)
Main-Class: com.example.MyMainClass

Creating the manifest file myself, with the bare essentials fixes the issue:

Manifest-Version: 1.0
Main-Class: com.example.MyMainClass

With more investigation I'm sure I could have got the dynamic meta-file creation working with Ant as I know other people do - there must be some peculiarity in the combination of my ant version (1.6.2), java version (1.4.2_07) and perhaps the current phase of the moon.

Notes:

Parsing of the Meta-inf file has been an issue that has come-up, been fixed and then come-up again for sun. See: Bug Id: 4991229. If you can work out if this bug exists in the your (or my) version of the Java SE you have more patience that me.

Java Wait and Notify: IllegalMonitorStateException

You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

class Runner implements Runnable
{
  public void run()
  {
    try
    {
      synchronized(Main.main) {
        Main.main.wait();
      }
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");
  }
}

The same rule applies to notify()/notifyAll() as well.

The Javadocs for wait() mention this:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:

IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

And from notify():

A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

How to make a deep copy of Java ArrayList

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

In your executing code:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

Text file with 0D 0D 0A line breaks

The CRCRLF is known as result of a Windows XP notepad word wrap bug.

For future reference, here's an extract of relevance from the linked blog:

When you press the Enter key on Windows computers, two characters are actually stored: a carriage return (CR) and a line feed (LF). The operating system always interprets the character sequence CR LF the same way as the Enter key: it moves to the next line. However when there are extra CR or LF characters on their own, this can sometimes cause problems.

There is a bug in the Windows XP version of Notepad that can cause extra CR characters to be stored in the display window. The bug happens in the following situation:

If you have the word wrap option turned on and the display window contains long lines that wrap around, then saving the file causes Notepad to insert the characters CR CR LF at each wrap point in the display window, but not in the saved file.

The CR CR LF characters can cause oddities if you copy and paste them into other programs. They also prevent Notepad from properly re-wrapping the lines if you resize the Notepad window.

You can remove the CR CR LF characters by turning off the word wrap feature, then turning it back on if desired. However, the cursor is repositioned at the beginning of the display window when you do this.

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds):

Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.

The documentation now reads:

--depth <depth>::

Create a 'shallow' clone with a history truncated to the specified number of revisions.

That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.

All the details are in "shallow.c: the 8 steps to select new commits for .git/shallow".

Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)


Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster -- in commit 7e3e80a, 20 Jan 2016)

This is "Documentation/user-manual.txt"

A <<def_shallow_clone,shallow clone>> is created by specifying the git-clone --depth switch.
The depth can later be changed with the git-fetch --depth switch, or full history restored with --unshallow.

Merging inside a <<def_shallow_clone,shallow clone>> will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.

Update 2020:

  • git 2.11.1 introduced option git fetch --shallow-exclude= to prevent fetching all history
  • git 2.11.1 introduced option git fetch --shallow-since= to prevent fetching old commits.

For more on the shallow clone update process, see "How to update a git shallow clone?".


As commented by Richard Michael:

to backfill history: git pull --unshallow

And Olle Härstedt adds in the comments:

To backfill part of the history: git fetch --depth=100.

What is the use of <<<EOD in PHP?

That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

The HTML in your example will be:

    <tr>
      <td>TEST</td>
    </tr>

Read the PHP documentation that explains it.

How to catch an Exception from a thread

Also from Java 8 you can write Dan Cruz answer as:

Thread t = new Thread(()->{
            System.out.println("Sleeping ...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Interrupted.");
            }
            System.out.println("Throwing exception ...");
            throw new RuntimeException(); });


t.setUncaughtExceptionHandler((th, ex)-> log(String.format("Exception in thread %d id: %s", th.getId(), ex)));
t.start();

Simple export and import of a SQLite database on Android

I use this code in the SQLiteOpenHelper in one of my applications to import a database file.

EDIT: I pasted my FileUtils.copyFile() method into the question.

SQLiteOpenHelper

public static String DB_FILEPATH = "/data/data/{package_name}/databases/database.db";

/**
 * Copies the database file at the specified location over the current
 * internal application database.
 * */
public boolean importDatabase(String dbPath) throws IOException {

    // Close the SQLiteOpenHelper so it will commit the created empty
    // database to internal storage.
    close();
    File newDb = new File(dbPath);
    File oldDb = new File(DB_FILEPATH);
    if (newDb.exists()) {
        FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
        // Access the copied database so SQLiteHelper will cache it and mark
        // it as created.
        getWritableDatabase().close();
        return true;
    }
    return false;
}

FileUtils

public class FileUtils {
    /**
     * Creates the specified <code>toFile</code> as a byte for byte copy of the
     * <code>fromFile</code>. If <code>toFile</code> already exists, then it
     * will be replaced with a copy of <code>fromFile</code>. The name and path
     * of <code>toFile</code> will be that of <code>toFile</code>.<br/>
     * <br/>
     * <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
     * this function.</i>
     * 
     * @param fromFile
     *            - FileInputStream for the file to copy from.
     * @param toFile
     *            - FileInputStream for the file to copy to.
     */
    public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = fromFile.getChannel();
            toChannel = toFile.getChannel();
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            try {
                if (fromChannel != null) {
                    fromChannel.close();
                }
            } finally {
                if (toChannel != null) {
                    toChannel.close();
                }
            }
        }
    }
}

Don't forget to delete the old database file if necessary.

How can I check Drupal log files?

Make sure drush is installed (you may also need to make sure the dblog module is enabled) and use:

drush watchdog-show --tail

Available in drush v8 and below.

This will give you a live look at the logs from your console.

ListView inside ScrollView is not scrolling on Android

Use the following method and enjoy!

private void setListViewScrollable(final ListView list) {
    list.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            listViewTouchAction = event.getAction();
            if (listViewTouchAction == MotionEvent.ACTION_MOVE) {
                list.scrollBy(0, 1);
            }
            return false;
        }
    });

    list.setOnScrollListener(new OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (listViewTouchAction == MotionEvent.ACTION_MOVE) {
                list.scrollBy(0, -1);
            }
        }
    });
}

listViewTouchAction is a global integer value. If you can replace the line

list.scrollBy(0, 1);

with something else please share it with us.

Enjoy!

How to "wait" a Thread in Android

You can try this one it is short :)

SystemClock.sleep(7000);

It will sleep for 7 sec look at documentation

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

In my case this was actually a symptom of the server, hosted on AWS, lacking an IP for the external network. It would attempt to download namespaces from springframework.org and fail to make a connection.

is there a 'block until condition becomes true' function in java?

EboMike's answer and Toby's answer are both on the right track, but they both contain a fatal flaw. The flaw is called lost notification.

The problem is, if a thread calls foo.notify(), it will not do anything at all unless some other thread is already sleeping in a foo.wait() call. The object, foo, does not remember that it was notified.

There's a reason why you aren't allowed to call foo.wait() or foo.notify() unless the thread is synchronized on foo. It's because the only way to avoid lost notification is to protect the condition with a mutex. When it's done right, it looks like this:

Consumer thread:

try {
    synchronized(foo) {
        while(! conditionIsTrue()) {
            foo.wait();
        }
        doSomethingThatRequiresConditionToBeTrue();
    }
} catch (InterruptedException e) {
    handleInterruption();
}

Producer thread:

synchronized(foo) {
    doSomethingThatMakesConditionTrue();
    foo.notify();
}

The code that changes the condition and the code that checks the condition is all synchronized on the same object, and the consumer thread explicitly tests the condition before it waits. There is no way for the consumer to miss the notification and end up stuck forever in a wait() call when the condition is already true.

Also note that the wait() is in a loop. That's because, in the general case, by the time the consumer re-acquires the foo lock and wakes up, some other thread might have made the condition false again. Even if that's not possible in your program, what is possible, in some operating systems, is for foo.wait() to return even when foo.notify() has not been called. That's called a spurious wakeup, and it is allowed to happen because it makes wait/notify easier to implement on certain operating systems.

How to check size of a file using Bash?

If your find handles this syntax, you can use it:

find -maxdepth 1 -name "file.txt" -size -90k

This will output file.txt to stdout if and only if the size of file.txt is less than 90k. To execute a script script if file.txt has a size less than 90k:

find -maxdepth 1 -name "file.txt" -size -90k -exec script \;

OSX - How to auto Close Terminal window after the "exit" command executed.

In the Terminal app, Preference >> Profiles tab.

Select the Shell tab on the right. enter image description here

You can choose Never Ask before closing to suppress the warning.

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

A simple work around on this issue. As "delete" command only removes the user record in "user" table of "mysql" database, we could add it back and then drop the user completely. Then you could create user with same name.

Step 1. find the record format of user table in mysql database

use mysql;
select * from user;

Step 2. According to the columns showed in step1, create a dummy record with the user name. Insert it into the table, for example, be reminded to replace the "username" with your username.

Insert into user value ('%','username','N','N','N','N','N',
'N','N','N','N','N','N','N','N','N','N','N','N','N','N','N',
'N','N','N','N','N','N','N','N','N','','','','','0','0','0',
'0','mysql_native_password',
'*52C5E3AC6BC5E2E0BFF86978BF62A1481AC79D58','N',
'2016-12-10 23:59:12',null,'N');

Note: sometimes you may encounter issues in inserting, just change the data to make it work.

Step 3. Drop the user.

drop user username;

Now you are able to create user with same name.

Why is this program erroneously rejected by three C++ compilers?

This program is valid -- I can find no errors.

My guess is you have a virus on your machine. It would be best if you reformat your drive, and reinstall the operating system.

Let us know how that works out, or if you need help with the reinstall.

I hate viruses.

Getting the parameters of a running JVM

I am adding this new answer because as per JDK8 documentation jcmd is suggested approach now.

It is suggested to use the latest utility, jcmd instead of the previous jstack, jinfo, and jmap utilities for enhanced diagnostics and reduced performance overhead.

Below are commands to get your properties/flags you want.

jcmd pid VM.system_properties
jcmd pid VM.flags

We need pid, for this use jcmd -l, like below

username@users-Air:~/javacode$ jcmd -l 
11441 Test 
6294 Test 
29197 jdk.jcmd/sun.tools.jcmd.JCmd -l 

Now time to use these pids to get properties/flags you want

Command: jcmd 11441 VM.system_properties

11441:
#Tue Oct 17 12:44:50 IST 2017
gopherProxySet=false
awt.toolkit=sun.lwawt.macosx.LWCToolkit
file.encoding.pkg=sun.io
java.specification.version=9
sun.cpu.isalist=
sun.jnu.encoding=UTF-8
java.class.path=.
java.vm.vendor=Oracle Corporation
sun.arch.data.model=64
java.vendor.url=http\://java.oracle.com/
user.timezone=Asia/Kolkata
java.vm.specification.version=9
os.name=Mac OS X
sun.java.launcher=SUN_STANDARD
user.country=US
sun.boot.library.path=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib
sun.java.command=Test
http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
jdk.debug=release
sun.cpu.endian=little
user.home=/Users/XXXX
user.language=en
java.specification.vendor=Oracle Corporation
java.home=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
file.separator=/
java.vm.compressedOopsMode=Zero based
line.separator=\n
java.specification.name=Java Platform API Specification
java.vm.specification.vendor=Oracle Corporation
java.awt.graphicsenv=sun.awt.CGraphicsEnvironment
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
java.runtime.version=9+181
user.name=XXXX
path.separator=\:
os.version=10.12.6
java.runtime.name=Java(TM) SE Runtime Environment
file.encoding=UTF-8
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
java.vendor.url.bug=http\://bugreport.java.com/bugreport/
java.io.tmpdir=/var/folders/dm/gd6lc90d0hg220lzw_m7krr00000gn/T/
java.version=9
user.dir=/Users/XXXX/javacode
os.arch=x86_64
java.vm.specification.name=Java Virtual Machine Specification
java.awt.printerjob=sun.lwawt.macosx.CPrinterJob
sun.os.patch.level=unknown
MyParam=2
java.library.path=/Users/XXXX/Library/Java/Extensions\:/Library/Java/Extensions\:/Network/Library/Java/Extensions\:/System/Library/Java/Extensions\:/usr/lib/java\:.
java.vm.info=mixed mode
java.vendor=Oracle Corporation
java.vm.version=9+181
sun.io.unicode.encoding=UnicodeBig
java.class.version=53.0
socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16

Command : jcmd 11441 VM.flags output:

11441:
-XX:CICompilerCount=3 -XX:ConcGCThreads=1 -XX:G1ConcRefinementThreads=4 -XX:G1HeapRegionSize=1048576 -XX:InitialHeapSize=67108864 -XX:MarkStackSize=4194304 -XX:MaxHeapSize=1073741824 -XX:MaxNewSize=643825664 -XX:MinHeapDeltaBytes=1048576 -XX:NonNMethodCodeHeapSize=5830092 -XX:NonProfiledCodeHeapSize=122914074 -XX:ProfiledCodeHeapSize=122914074 -XX:ReservedCodeCacheSize=251658240 -XX:+SegmentedCodeCache -XX:-UseAOT -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:+UseG1GC 

For more instructions of usages of jcmd, see my blog post

Android "Only the original thread that created a view hierarchy can touch its views."

For the people struggling in Kotlin, it works like this:

lateinit var runnable: Runnable //global variable

 runOnUiThread { //Lambda
            runnable = Runnable {

                //do something here

                runDelayedHandler(5000)
            }
        }

        runnable.run()

 //you need to keep the handler outside the runnable body to work in kotlin
 fun runDelayedHandler(timeToWait: Long) {

        //Keep it running
        val handler = Handler()
        handler.postDelayed(runnable, timeToWait)
    }

How to export a MySQL database to JSON?

If you have Ruby, you can install the mysql2xxxx gem (not the mysql2json gem, which is a different gem):

$ gem install mysql2xxxx

and then run the command

$ mysql2json --user=root --password=password --database=database_name --execute "select * from mytable" >mytable.json

The gem also provides mysql2csv and mysql2xml. It's not as fast as mysqldump, but also doesn't suffer from some of mysqldump's weirdnesses (like only being able to dump CSV from the same computer as the MySQL server itself)

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

You can have the @Transactional in the child class, but you have to override each of the methods and call the super method in order to get it to work.

Example:

@Transactional(readOnly = true)
public class Bob<SomeClass> {
   @Override
   public SomeClass getValue() {
       return super.getValue();
   }
}

This allows it to set it up for each of the methods it's needed for.

Illegal access: this web application instance has been stopped already

If it's a local development tomcat launched from IDE, then restarting this IDE and rebuild project also helps.

Update:

You could also try to find if there is any running tomcat process in the background and kill it.

Fatal error: "No Target Architecture" in Visual Studio

If you are building 32bit then make sure you don't have _WIN64 defined for your project.

Python [Errno 98] Address already in use

This happens because you trying to run service at the same port and there is an already running application.

This can happen because your service is not stopped in the process stack. Then you just have to kill this process.

There is no need to install anything here is the one line command to kill all running python processes.

for Linux based OS:

Bash:

kill -9 $(ps -A | grep python | awk '{print $1}')

Fish:

kill -9 (ps -A | grep python | awk '{print $1}')

Strange Jackson exception being thrown when serializing Hibernate object

I had a similar problem with lazy loading via the hibernate proxy object. Got around it by annotating the class having lazyloaded private properties with:

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

I assume you can add the properties on your proxy object that breaks the JSON serialization to that annotation.

Avoid Jackson serialization on non fetched lazy objects

Is ini_set('max_execution_time', 0) a bad idea?

Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.

  1. You can halt server, corrupt work of other people by memory consuming script without even knowing it.
  2. You will not be seeing mistakes where something, let's say, infinite loop happened, and it will be harder to diagnose.
  3. Such site may be easily DoSed by single user, when requesting pages with long execution time

Git: "Corrupt loose object"

Runnning git stash; git stash pop fixed my problem

Method to Add new or update existing item in Dictionary

The only problem could be if one day

map[key] = value

will transform to -

map[key]++;

and that will cause a KeyNotFoundException.

Capture keyboardinterrupt in Python without try-except

If someone is in search for a quick minimal solution,

import signal

# The code which crashes program on interruption

signal.signal(signal.SIGINT, call_this_function_if_interrupted)

# The code skipped if interrupted

How do I deal with corrupted Git object files?

You can use "find" for remove all files in the /objects directory with 0 in size with the command:

find .git/objects/ -size 0 -delete

Backup is recommended.

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I had this problem recently when I changed the development server for a project. I was getting this error on the line of code where I declared a new OracleConnection variable.

After trying many things, including installing hotfixes, I tried changing the references Oracle.DataAccess and System.Data.OracleClient in the project and it worked!

When a project is moved to a new machine, I suggest you renew all the references added in that project.

Running multiple AsyncTasks at the same time -- not possible?

Just to include the latest update (UPDATE 4) in @Arhimed 's immaculate answer in the very good summary of @sulai:

void doTheTask(AsyncTask task) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Android 4.4 (API 19) and above
        // Parallel AsyncTasks are possible, with the thread-pool size dependent on device
        // hardware
        task.execute(params);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Android 3.0 to
        // Android 4.3
        // Parallel AsyncTasks are not possible unless using executeOnExecutor
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    } else { // Below Android 3.0
        // Parallel AsyncTasks are possible, with fixed thread-pool size
        task.execute(params);
    }
}

How to change package name of an Android Application

Here's how you could do this in Eclipse:

  1. Right-click on the package name (src/com.android.gesture.builder).
  2. Select Refactor > Rename and change the name, for example to com.android.gestureNEW.builder.
  3. Open the manifest file. Inside the <manifest> tag, change the package name to com.android.gestureNEW.builder.
  4. Open each of the two Activity files and do Ctrl+Shift+O to add missing import packages, then save each file.
  5. Run the GestureBuilder application on the emulator.

Link to post

Update super easy way right click on your project... enter image description here

Handling InterruptedException in Java

The correct default choice is add InterruptedException to your throws list. An Interrupt indicates that another thread wishes your thread to end. The reason for this request is not made evident and is entirely contextual, so if you don't have any additional knowledge you should assume it's just a friendly shutdown, and anything that avoids that shutdown is a non-friendly response.

Java will not randomly throw InterruptedException's, all advice will not affect your application but I have run into a case where developer's following the "swallow" strategy became very inconvenient. A team had developed a large set of tests and used Thread.Sleep a lot. Now we started to run the tests in our CI server, and sometimes due to defects in the code would get stuck into permanent waits. To make the situation worse, when attempting to cancel the CI job it never closed because the Thread.Interrupt that was intended to abort the test did not abort the job. We had to login to the box and manually kill the processes.

So long story short, if you simply throw the InterruptedException you are matching the default intent that your thread should end. If you can't add InterruptedException to your throw list, I'd wrap it in a RuntimeException.

There is a very rational argument to be made that InterruptedException should be a RuntimeException itself, since that would encourage a better "default" handling. It's not a RuntimeException only because the designers stuck to a categorical rule that a RuntimeException should represent an error in your code. Since an InterruptedException does not arise directly from an error in your code, it's not. But the reality is that often an InterruptedException arises because there is an error in your code, (i.e. endless loop, dead-lock), and the Interrupt is some other thread's method for dealing with that error.

If you know there is rational cleanup to be done, then do it. If you know a deeper cause for the Interrupt, you can take on more comprehensive handling.

So in summary your choices for handling should follow this list:

  1. By default, add to throws.
  2. If not allowed to add to throws, throw RuntimeException(e). (Best choice of multiple bad options)
  3. Only when you know an explicit cause of the Interrupt, handle as desired. If your handling is local to your method, then reset interrupted by a call to Thread.currentThread().interrupt().

$ is not a function - jQuery error

It's really hard to tell, but one of the 9001 ads on the page may be clobbering the $ object.

jQuery provides the global jQuery object (which is present on your page). You can do the following to "get" $ back:

jQuery(document).ready(function ($) {
    // Your code here
});

If you think you're having jQuery problems, please use the debug (non-production) versions of the library.

Also, it's probably not best to be editing a live site like that ...

Raise warning in Python without interrupting program

You shouldn't raise the warning, you should be using warnings module. By raising it you're generating error, rather than warning.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

I had the same as well.Making the Id (0) doing "(your Model value).setId(0)" solved my problem.

Is it safe to use Project Lombok?

I'm not recommend it. I used to use it, but then when I work with NetBeans 7.4 it was messing my codes. I've to remove lombok in all of files in my projects. There is delombok, but how can I be sure it would not screw my codes. I have to spends days just to remove lombok and back to ordinary Java styles. I just too spicy...

Git - How to fix "corrupted" interactive rebase?

tried everything else but a reboot, what worked for me is rm -fr .git/REBASE_HEAD

Displaying the Indian currency symbol on a website

Image approach is not bad either. It hardly takes 400Bytes.
Download from here http://i.stack.imgur.com/vJZ9m.png

<span class="rupee"></span>

Well i found it better than webrupee.

For colors edit the image as below

    .rupee{
    background-position:left;
    width: 10px; 
    height: 14px;
    background-image: url('rupee.png');
    display:block; 
    background-repeat: no-repeat;
}

What does java.lang.Thread.interrupt() do?

What is interrupt ?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

How is it implemented ?

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static Thread.isInterrupted, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

Quote from Thread.interrupt() API:

Interrupts this thread. First the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

Check this out for complete understanding about same :

http://download.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

Reading CSV files using C#

Here's a solution I coded up today for a situation where I needed to parse a CSV without relying on external libraries. I haven't tested performance for large files since it wasn't relevant to my particular use case but I'd expect it to perform reasonably well for most situations.

        static List<List<string>> ParseCsv(string csv) {
            var parsedCsv = new List<List<string>>();
            var row = new List<string>();
            string field = "";
            bool inQuotedField = false;

            for (int i = 0; i < csv.Length; i++) {
                char current = csv[i];
                char next = i == csv.Length - 1 ? ' ' : csv[i + 1];

                // if current character is not a quote or comma or carriage return or newline (or not a quote and currently in an a quoted field), just add the character to the current field text
                if ((current != '"' && current != ',' && current != '\r' && current != '\n') || (current != '"' && inQuotedField)) {
                    field += current;
                } else if (current == ' ' || current == '\t') {
                    continue; // ignore whitespace outside a quoted field
                } else if (current == '"') {
                    if (inQuotedField && next == '"') { // quote is escaping a quote within a quoted field
                        i++; // skip escaping quote
                        field += current;
                    } else if (inQuotedField) { // quote signifies the end of a quoted field
                        row.Add(field);
                        if (next == ',') {
                            i++; // skip the comma separator since we've already found the end of the field
                        }
                        field = "";
                        inQuotedField = false;
                    } else { // quote signifies the beginning of a quoted field
                        inQuotedField = true; 
                    }
                } else if (current == ',') { //
                    row.Add(field);
                    field = "";
                } else if (current == '\n') {
                    row.Add(field);
                    parsedCsv.Add(new List<string>(row));
                    field = "";
                    row.Clear();
                }
            }

            return parsedCsv;
        }

HTML code for INR

Here is one more example based on Intl.NumberFormat native api.

_x000D_
_x000D_
var number = 123456.789;_x000D_
_x000D_
// India uses thousands/lakh/crore separators_x000D_
console.log(new Intl.NumberFormat('en-IN', {_x000D_
  style: 'currency',_x000D_
  currency: 'INR',_x000D_
  // limit to six significant digits (Possible values are from 1 to 21)._x000D_
  maximumSignificantDigits: 6_x000D_
}).format(number));
_x000D_
_x000D_
_x000D_

Apache VirtualHost and localhost

This worked for me!

To run projects like http://localhost/projectName

<VirtualHost localhost:80>
   ServerAdmin localhost
    DocumentRoot path/to/htdocs/
    ServerName localhost
</VirtualHost>

To run projects like http://somewebsite.com locally

<VirtualHost somewebsite.com:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/somewebsiteFolder
     ServerName www.somewebsite.com
     ServerAlias somewebsite.com
</VirtualHost>

Same for other websites

<VirtualHost anothersite.local:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/anotherSiteFolder
     ServerName www.anothersite.local
     ServerAlias anothersite.com
</VirtualHost>

Mutex example / tutorial?

While a mutex may be used to solve other problems, the primary reason they exist is to provide mutual exclusion and thereby solve what is known as a race condition. When two (or more) threads or processes are attempting to access the same variable concurrently, we have potential for a race condition. Consider the following code

//somewhere long ago, we have i declared as int
void my_concurrently_called_function()
{
  i++;
}

The internals of this function look so simple. It's only one statement. However, a typical pseudo-assembly language equivalent might be:

load i from memory into a register
add 1 to i
store i back into memory

Because the equivalent assembly-language instructions are all required to perform the increment operation on i, we say that incrementing i is a non-atmoic operation. An atomic operation is one that can be completed on the hardware with a gurantee of not being interrupted once the instruction execution has begun. Incrementing i consists of a chain of 3 atomic instructions. In a concurrent system where several threads are calling the function, problems arise when a thread reads or writes at the wrong time. Imagine we have two threads running simultaneoulsy and one calls the function immediately after the other. Let's also say that we have i initialized to 0. Also assume that we have plenty of registers and that the two threads are using completely different registers, so there will be no collisions. The actual timing of these events may be:

thread 1 load 0 into register from memory corresponding to i //register is currently 0
thread 1 add 1 to a register //register is now 1, but not memory is 0
thread 2 load 0 into register from memory corresponding to i
thread 2 add 1 to a register //register is now 1, but not memory is 0
thread 1 write register to memory //memory is now 1
thread 2 write register to memory //memory is now 1

What's happened is that we have two threads incrementing i concurrently, our function gets called twice, but the outcome is inconsistent with that fact. It looks like the function was only called once. This is because the atomicity is "broken" at the machine level, meaning threads can interrupt each other or work together at the wrong times.

We need a mechanism to solve this. We need to impose some ordering to the instructions above. One common mechanism is to block all threads except one. Pthread mutex uses this mechanism.

Any thread which has to execute some lines of code which may unsafely modify shared values by other threads at the same time (using the phone to talk to his wife), should first be made acquire a lock on a mutex. In this way, any thread that requires access to the shared data must pass through the mutex lock. Only then will a thread be able to execute the code. This section of code is called a critical section.

Once the thread has executed the critical section, it should release the lock on the mutex so that another thread can acquire a lock on the mutex.

The concept of having a mutex seems a bit odd when considering humans seeking exclusive access to real, physical objects but when programming, we must be intentional. Concurrent threads and processes don't have the social and cultural upbringing that we do, so we must force them to share data nicely.

So technically speaking, how does a mutex work? Doesn't it suffer from the same race conditions that we mentioned earlier? Isn't pthread_mutex_lock() a bit more complex that a simple increment of a variable?

Technically speaking, we need some hardware support to help us out. The hardware designers give us machine instructions that do more than one thing but are guranteed to be atomic. A classic example of such an instruction is the test-and-set (TAS). When trying to acquire a lock on a resource, we might use the TAS might check to see if a value in memory is 0. If it is, that would be our signal that the resource is in use and we do nothing (or more accurately, we wait by some mechanism. A pthreads mutex will put us into a special queue in the operating system and will notify us when the resource becomes available. Dumber systems may require us to do a tight spin loop, testing the condition over and over). If the value in memory is not 0, the TAS sets the location to something other than 0 without using any other instructions. It's like combining two assembly instructions into 1 to give us atomicity. Thus, testing and changing the value (if changing is appropriate) cannot be interrupted once it has begun. We can build mutexes on top of such an instruction.

Note: some sections may appear similar to an earlier answer. I accepted his invite to edit, he preferred the original way it was, so I'm keeping what I had which is infused with a little bit of his verbiage.

ListBox with ItemTemplate (and ScrollBar!)

ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...

If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...

HTH

jQuery - how can I find the element with a certain id?

I don't know if this solves your problem but instead of:

$("#tbIntervalos").find("td").attr("id", horaInicial);

you can just do:

$("#tbIntervalos td#" + horaInicial);

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

You module and class AthleteList have the same name. Change:

import AthleteList

to:

from AthleteList import AthleteList

This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList

Why is the gets function so dangerous that it should not be used?

You can't remove API functions without breaking the API. If you would, many applications would no longer compile or run at all.

This is the reason that one reference gives:

Reading a line that overflows the array pointed to by s results in undefined behavior. The use of fgets() is recommended.

Log4Net configuring log level

you can use log4net.Filter.LevelMatchFilter. other options can be found at log4net tutorial - filters

in ur appender section add

<filter type="log4net.Filter.LevelMatchFilter">
    <levelToMatch value="Info" />
    <acceptOnMatch value="true" />
</filter>

the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters

Where do I configure log4j in a JUnit test class?

I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)

Python Selenium accessing HTML source

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()
html_source_code = driver.execute_script("return document.body.innerHTML;")
html_soup: BeautifulSoup = BeautifulSoup(html_source_code, 'html.parser')

Now you can apply BeautifulSoup function to extract data...

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

Anyone facing this while using cmake build, the solution is to make sure you have included the four supported platforms in your app module's android{} block:

 externalNativeBuild {
            cmake {
                cppFlags "-std=c++14"
                abiFilters "arm64-v8a", "x86", "armeabi-v7a", "x86_64"
            }
        }

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

How to dynamically add elements to String array?

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

mysql command for showing current configuration variables

What you are looking for is this:

SHOW VARIABLES;  

You can modify it further like any query:

SHOW VARIABLES LIKE '%max%';  

Get current URL path in PHP

<?php
function current_url()
{
    $url      = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $validURL = str_replace("&", "&amp", $url);
    return $validURL;
}
//echo "page URL is : ".current_url();

$offer_url = current_url();

?>



<?php

if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>

<?php
}
?>

How to make bootstrap 3 fluid layout without horizontal scrollbar

It's already fluid by default. If you want to be fluid for less width instead of col-md-6 use col-sm-6 or col-xs-6.

Best way to "push" into C# array

Your question is a little off the mark. In particular, you say "that the element needs to be added into the first empty slot in an array, lie (sic) a Java push function would do."

  1. Java's Array does not have a push operation - JavaScript does. Java and JavaScript are two very different languages
  2. JavaScript's push function does not behave as you describe. When you "push" a value into a JavaScript array, the array is extended by one element, and that new element is assigned the pushed value, see: Mozilla's Array.prototype.push function docs

The verb "Push" is not something that is used with an Array in any language that I know of except JavaScript. I suspect that it's only in JavaScript because it could be there (since JavaScript is a completely dynamic language). I'm pretty sure it wasn't designed in intentionally.

A JavaScript-style Push operation in C# could be written in this somewhat inefficient manner:

int [] myArray = new int [] {1, 2, 3, 4};
var tempList = myArray.ToList();
tempList.Add(5);
myArray = tempList.ToArray();   //equiv: myArray.Push(5);

"Push" is used in some types of containers, particularly Stacks, Queues and Deques (which get two pushes - one from the front, one from the back). I urge you not to include Push as a verb in your explanation of arrays. It adds nothing to a CS student's vocabulary.

In C#, as in most traditional procedural languages, an array is a collection of elements of a single type, contained in a fixed length contiguous block of memory. When you allocate an array, the space for every array element is allocated (and, in C# those elements are initialized to the default value of the type, null for reference types).

In C#, arrays of reference types are filled with object references; arrays of value types are filled with instances of that value type. As a result, an array of 4 strings uses the same memory as an array of 4 instance of your application class (since they are both reference types). But, an array of 4 DateTime instances is significantly longer that of an array of 4 short integers.

In C#, an instance of an array is an instance of System.Array, a reference type. Arrays have a few properties and methods (like the Length property). Otherwise, there isn't much you can do with an array: you can read (or write) from (or to) individual elements using an array index. Arrays of type T also implement IEnumerable<T>, so you can iterate through the elements of an array.

Arrays are mutable (the values in an array can be written to), but they have a fixed length - they can't be extended or shortened. They are ordered, and they can't be re-arranged (except by swizzling the values manually).

C# arrays are covariant. If you were to ask the C# language designers, this would be the feature they regret the most. It's one of the few ways you can break C# type safety. Consider this code (assuming that Cat and Dog classes inherit from Animal):

Cat[] myCats = new Cat[]{myCat, yourCat, theirCat};
Animal[] animals = (Animal[]) myCats;     //legal but dangerous
animals[1] = new Dog();                   //heading off the cliff
myCats[1].Speak();                        //Woof!

That "feature" is the result of the lack of generic types and explicit covariance/contravariance in the initial version of the .NET Framework and the urge to copy a Java "feature".

Arrays do show up in many core .NET APIs (for example, System.Reflection). They are there, again, because the initial release did not support generic collections.

In general, an experienced C# programmer will not use many arrays in his applications, preferring to use more capable collections such as List<T>, Dictionary<TKey, TValue>, HashSet<T> and friends. In particular, that programmer will tend to pass collections around using IEnumerable<T> an interface that all collections implement. The big advantage of using IEnumerable<T> as parameters and return types (where possible and logical) is that collections accessed via IEnumerable<T> references are immutable. It's kinda-sorta like using const correctly in C++.

One thing you might consider adding in to your lectures on arrays - after everyone has mastered the basics - is the new Span<T> type. Spans may make C# arrays useful.

Finally, LINQ (Language Integrated Query) introduced a lot of functionality to collections (by adding Extension Methods to IEnumerable<T>). Make sure your student do not have a using System.Linq; statement up at the top of their code - mixing LINQ in to a beginning student's class on arrays would bewilder him or her.

BTW: what kind of class is it you teach? At what level?

How to make the first option of <select> selected with jQuery

If you're storing the jQuery object of the select element:

var jQuerySelectObject = $("...");

...

jQuerySelectObject.val(jQuerySelectObject.children().eq(0).val());

How to put a horizontal divisor line between edit text's in a activity

How about defining your own view? I have used the class below, using a LinearLayout around a view whose background color is set. This allows me to pre-define layout parameters for it. If you don't need that just extend View and set the background color instead.

public class HorizontalRulerView extends LinearLayout {

    static final int COLOR = Color.DKGRAY;
    static final int HEIGHT = 2;
    static final int VERTICAL_MARGIN = 10;
    static final int HORIZONTAL_MARGIN = 5;
    static final int TOP_MARGIN = VERTICAL_MARGIN;
    static final int BOTTOM_MARGIN = VERTICAL_MARGIN;
    static final int LEFT_MARGIN = HORIZONTAL_MARGIN;
    static final int RIGHT_MARGIN = HORIZONTAL_MARGIN;

    public HorizontalRulerView(Context context) {
        this(context, null);
    }

    public HorizontalRulerView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public HorizontalRulerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setOrientation(VERTICAL);
        View v = new View(context);
        v.setBackgroundColor(COLOR);
        LayoutParams lp = new LayoutParams(
            LayoutParams.MATCH_PARENT,
            HEIGHT
        );
        lp.topMargin = TOP_MARGIN;
        lp.bottomMargin = BOTTOM_MARGIN;
        lp.leftMargin = LEFT_MARGIN;
        lp.rightMargin = RIGHT_MARGIN;
        addView(v, lp);
    }

}

Use it programmatically or in Eclipse (Custom & Library Views -- just pull it into your layout).

How to watch for a route change in AngularJS?

Note: This is a proper answer for a legacy version of AngularJS. See this question for updated versions.

$scope.$on('$routeChangeStart', function($event, next, current) { 
   // ... you could trigger something here ...
 });

The following events are also available (their callback functions take different arguments):

  • $routeChangeSuccess
  • $routeChangeError
  • $routeUpdate - if reloadOnSearch property has been set to false

See the $route docs.

There are two other undocumented events:

  • $locationChangeStart
  • $locationChangeSuccess

See What's the difference between $locationChangeSuccess and $locationChangeStart?

Styling Google Maps InfoWindow

I have design google map infowindow with image & some content as per below.

enter image description here

map_script (Just for infowindow html reference)

for (i = 0; i < locations.length; i++) { 
    var latlng = new google.maps.LatLng(locations[i][1], locations[i][2]);
    marker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: "<?php echo plugins_url( 'assets/img/map-pin.png', ELEMENTOR_ES__FILE__ ); ?>"
    });

    var property_img = locations[i][6],
    title = locations[i][0],
    price = locations[i][3],
    bedrooms = locations[i][4],
    type = locations[i][5],
    listed_on = locations[i][7],
    prop_url = locations[i][8];

    content = "<div class='map_info_wrapper'><a href="+prop_url+"><div class='img_wrapper'><img src="+property_img+"></div>"+
    "<div class='property_content_wrap'>"+
    "<div class='property_title'>"+
    "<span>"+title+"</span>"+
    "</div>"+

    "<div class='property_price'>"+
    "<span>"+price+"</span>"+
    "</div>"+

    "<div class='property_bed_type'>"+
    "<span>"+bedrooms+"</span>"+
    "<ul><li>"+type+"</li></ul>"+
    "</div>"+

    "<div class='property_listed_date'>"+
    "<span>Listed on "+listed_on+"</span>"+
    "</div>"+
    "</div></a></div>";

    google.maps.event.addListener(marker, 'click', (function(marker, content, i) {
        return function() {
            infowindow.setContent(content);
            infowindow.open(map, marker);
        }
    })(marker, content, i));
}

Most important thing is CSS

 #propertymap .gm-style-iw{
    box-shadow:none;
    color:#515151;
    font-family: "Georgia", "Open Sans", Sans-serif;
    text-align: center;
    width: 100% !important;
    border-radius: 0;
    left: 0 !important;
    top: 20px !important;
}

 #propertymap .gm-style > div > div > div > div > div > div > div {
    background: none!important;
}

.gm-style > div > div > div > div > div > div > div:nth-child(2) {
     box-shadow: none!important;
}
 #propertymap .gm-style-iw > div > div{
    background: #FFF!important;
}

 #propertymap .gm-style-iw a{
    text-decoration: none;
}

 #propertymap .gm-style-iw > div{
    width: 245px !important
}

 #propertymap .gm-style-iw .img_wrapper {
    height: 150px;  
    overflow: hidden;
    width: 100%;
    text-align: center;
    margin: 0px auto;
}

 #propertymap .gm-style-iw .img_wrapper > img {
    width: 100%;
    height:auto;
}

 #propertymap .gm-style-iw .property_content_wrap {
    padding: 0px 20px;
}

 #propertymap .gm-style-iw .property_title{
    min-height: auto;
}

JAX-WS client : what's the correct path to access the local WSDL?

For those of you using Spring, you can simply reference any classpath-resource using the classpath-protocol. So in case of the wsdlLocation, this becomes:

<wsdlLocation>classpath:META-INF/webservice.wsdl</wsdlLocation>

Note that is not standard Java behavior. See also: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/resources.html

Spring Boot: Cannot access REST Controller on localhost (404)

Replace @RequestMapping( "/item" ) with @GetMapping(value="/item", produces=MediaType.APPLICATION_JSON_VALUE).

Maybe it will help somebody.

How to scale a BufferedImage

Unfortunately the performance of getScaledInstance() is very poor if not problematic.

The alternative approach is to create a new BufferedImage and and draw a scaled version of the original on the new one.

BufferedImage resized = new BufferedImage(newWidth, newHeight, original.getType());
Graphics2D g = resized.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(original, 0, 0, newWidth, newHeight, 0, 0, original.getWidth(),
    original.getHeight(), null);
g.dispose();

newWidth,newHeight indicate the new BufferedImage size and have to be properly calculated. In case of factor scaling:

int newWidth = new Double(original.getWidth() * widthFactor).intValue();
int newHeight = new Double(original.getHeight() * heightFactor).intValue();

EDIT: Found the article illustrating the performance issue: The Perils of Image.getScaledInstance()

Set database timeout in Entity Framework

For Database first Aproach:

We can still set it in a constructor, by override the ContextName.Context.tt T4 Template this way:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
    public <#=code.Escape(container)#>()
        : base("name=<#=container.Name#>")
    {
        Database.CommandTimeout = 180;
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
        this.Configuration.LazyLoadingEnabled = false;
<#
}

Database.CommandTimeout = 180; is the acutaly change.

The generated output is this:

public ContextName() : base("name=ContextName")
{
    Database.CommandTimeout = 180;
}

If you change your Database Model, this template stays, but the actualy class will be updated.

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

Get current batchfile directory

Very simple:

setlocal
cd /d %~dp0
File.exe

How do I make a list of data frames?

The other answers show you how to make a list of data.frames when you already have a bunch of data.frames, e.g., d1, d2, .... Having sequentially named data frames is a problem, and putting them in a list is a good fix, but best practice is to avoid having a bunch of data.frames not in a list in the first place.

The other answers give plenty of detail of how to assign data frames to list elements, access them, etc. We'll cover that a little here too, but the Main Point is to say don't wait until you have a bunch of a data.frames to add them to a list. Start with the list.

The rest of the this answer will cover some common cases where you might be tempted to create sequential variables, and show you how to go straight to lists. If you're new to lists in R, you might want to also read What's the difference between [[ and [ in accessing elements of a list?.


Lists from the start

Don't ever create d1 d2 d3, ..., dn in the first place. Create a list d with n elements.

Reading multiple files into a list of data frames

This is done pretty easily when reading in files. Maybe you've got files data1.csv, data2.csv, ... in a directory. Your goal is a list of data.frames called mydata. The first thing you need is a vector with all the file names. You can construct this with paste (e.g., my_files = paste0("data", 1:5, ".csv")), but it's probably easier to use list.files to grab all the appropriate files: my_files <- list.files(pattern = "\\.csv$"). You can use regular expressions to match the files, read more about regular expressions in other questions if you need help there. This way you can grab all CSV files even if they don't follow a nice naming scheme. Or you can use a fancier regex pattern if you need to pick certain CSV files out from a bunch of them.

At this point, most R beginners will use a for loop, and there's nothing wrong with that, it works just fine.

my_data <- list()
for (i in seq_along(my_files)) {
    my_data[[i]] <- read.csv(file = my_files[i])
}

A more R-like way to do it is with lapply, which is a shortcut for the above

my_data <- lapply(my_files, read.csv)

Of course, substitute other data import function for read.csv as appropriate. readr::read_csv or data.table::fread will be faster, or you may also need a different function for a different file type.

Either way, it's handy to name the list elements to match the files

names(my_data) <- gsub("\\.csv$", "", my_files)
# or, if you prefer the consistent syntax of stringr
names(my_data) <- stringr::str_replace(my_files, pattern = ".csv", replacement = "")

Splitting a data frame into a list of data frames

This is super-easy, the base function split() does it for you. You can split by a column (or columns) of the data, or by anything else you want

mt_list = split(mtcars, f = mtcars$cyl)
# This gives a list of three data frames, one for each value of cyl

This is also a nice way to break a data frame into pieces for cross-validation. Maybe you want to split mtcars into training, test, and validation pieces.

groups = sample(c("train", "test", "validate"),
                size = nrow(mtcars), replace = TRUE)
mt_split = split(mtcars, f = groups)
# and mt_split has appropriate names already!

Simulating a list of data frames

Maybe you're simulating data, something like this:

my_sim_data = data.frame(x = rnorm(50), y = rnorm(50))

But who does only one simulation? You want to do this 100 times, 1000 times, more! But you don't want 10,000 data frames in your workspace. Use replicate and put them in a list:

sim_list = replicate(n = 10,
                     expr = {data.frame(x = rnorm(50), y = rnorm(50))},
                     simplify = F)

In this case especially, you should also consider whether you really need separate data frames, or would a single data frame with a "group" column work just as well? Using data.table or dplyr it's quite easy to do things "by group" to a data frame.

I didn't put my data in a list :( I will next time, but what can I do now?

If they're an odd assortment (which is unusual), you can simply assign them:

mylist <- list()
mylist[[1]] <- mtcars
mylist[[2]] <- data.frame(a = rnorm(50), b = runif(50))
...

If you have data frames named in a pattern, e.g., df1, df2, df3, and you want them in a list, you can get them if you can write a regular expression to match the names. Something like

df_list = mget(ls(pattern = "df[0-9]"))
# this would match any object with "df" followed by a digit in its name
# you can test what objects will be got by just running the
ls(pattern = "df[0-9]")
# part and adjusting the pattern until it gets the right objects.

Generally, mget is used to get multiple objects and return them in a named list. Its counterpart get is used to get a single object and return it (not in a list).

Combining a list of data frames into a single data frame

A common task is combining a list of data frames into one big data frame. If you want to stack them on top of each other, you would use rbind for a pair of them, but for a list of data frames here are three good choices:

# base option - slower but not extra dependencies
big_data = do.call(what = rbind, args = df_list)

# data table and dplyr have nice functions for this that
#  - are much faster
#  - add id columns to identify the source
#  - fill in missing values if some data frames have more columns than others
# see their help pages for details
big_data = data.table::rbindlist(df_list)
big_data = dplyr::bind_rows(df_list)

(Similarly using cbind or dplyr::bind_cols for columns.)

To merge (join) a list of data frames, you can see these answers. Often, the idea is to use Reduce with merge (or some other joining function) to get them together.

Why put the data in a list?

Put similar data in lists because you want to do similar things to each data frame, and functions like lapply, sapply do.call, the purrr package, and the old plyr l*ply functions make it easy to do that. Examples of people easily doing things with lists are all over SO.

Even if you use a lowly for loop, it's much easier to loop over the elements of a list than it is to construct variable names with paste and access the objects with get. Easier to debug, too.

Think of scalability. If you really only need three variables, it's fine to use d1, d2, d3. But then if it turns out you really need 6, that's a lot more typing. And next time, when you need 10 or 20, you find yourself copying and pasting lines of code, maybe using find/replace to change d14 to d15, and you're thinking this isn't how programming should be. If you use a list, the difference between 3 cases, 30 cases, and 300 cases is at most one line of code---no change at all if your number of cases is automatically detected by, e.g., how many .csv files are in your directory.

You can name the elements of a list, in case you want to use something other than numeric indices to access your data frames (and you can use both, this isn't an XOR choice).

Overall, using lists will lead you to write cleaner, easier-to-read code, which will result in fewer bugs and less confusion.

Android: How to detect double-tap?

To detect the type of gesture tap one can implement something inline with this: ( here projectText is an EditText )

    projectText.setOnTouchListener(new View.OnTouchListener() {
        private GestureDetector gestureDetector = new GestureDetector(activity, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                projectText.setInputType(InputType.TYPE_CLASS_TEXT);
                activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
                return super.onDoubleTap(e);
            }
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                    projectText.setInputType(InputType.TYPE_NULL); // disable soft input
                    final int itemPosition = getLayoutPosition();
                    if(!projects.get(itemPosition).getProjectId().equals("-1"))
                        listener.selectedClick(projects.get(itemPosition));

                return super.onSingleTapUp(e);
            }

        });

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            gestureDetector.onTouchEvent(event);
            return false; //true stops propagation of the event
        }

    });

S3 limit to objects in a bucket

While you can store an unlimited number of files/objects in a single bucket, when you go to list a "directory" in a bucket, it will only give you the first 1000 files/objects in that bucket by default. To access all the files in a large "directory" like this, you need to make multiple calls to their API.

How to add "Maven Managed Dependencies" library in build path eclipse?

If you use an eclipse plugin to do your maven tasks (there are 2 of them : M2ecipse from sonatype the 'official' one and q4e on Google Code) then, there are options in the contextual menus (right click on the project) to do that painlessly.

You can have both plugins running at the same time in your eclipse workbench and use them indifferently on a per project basis.

Meaning of @classmethod and @staticmethod for beginner?

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).

React Native absolute positioning horizontal centre

You can center absolute items by providing the left property with the width of the device divided by two and subtracting out half of the element you'd like to center's width.

For example, your style might look something like this.

bottom: {
    position: 'absolute',
    left: (Dimensions.get('window').width / 2) - 25,
    top: height*0.93,
}

Can we add div inside table above every <tr>?

In the html tables, <table> tag expect <tr> tag right after itself and <tr> tag expect <td> tag right after itself. So if you want to put a div in table, you can put it in between <td> and </td> tags as data.

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div>_x000D_
        <p>It works well</p>_x000D_
      </div>_x000D_
     </td>_x000D_
  </tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

How can I commit files with git?

I faced the same problem , i resolved it by typing :q! then hit Enter And it resolved my problem After that run the the following command git commit -a -m "your comment here"

This should resolve your problem.

Find files and tar them (with spaces)

Another solution as seen here:

find var/log/ -iname "anaconda.*" -exec tar -cvzf file.tar.gz {} +

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

How do you implement a circular buffer in C?

Can you enumerate the types needed at the time you code up the buffer, or do you need to be able to add types at run time via dynamic calls? If the former, then I would create the buffer as a heap-allocated array of n structs, where each struct consists of two elements: an enum tag identifying the data type, and a union of all the data types. What you lose in terms of extra storage for small elements, you make up in terms of not having to deal with allocation/deallocation and the resulting memory fragmentation. Then you just need to keep track of the start and end indices that define the head and tail elements of the buffer, and make sure to compute mod n when incrementing/decrementing the indices.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

As mentioned above the following would solve the problem: mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

However in my case the provider did this [0..1] or [0..*] serialization rather as a bug and I could not enforce fixing. On the other hand it did not want to impact my strict mapper for all other cases which needs to be validated strictly.

So I did a Jackson NASTY HACK (which should not be copied in general ;-) ), especially because my SingleOrListElement had only few properties to patch:

@JsonProperty(value = "SingleOrListElement", access = JsonProperty.Access.WRITE_ONLY)
private Object singleOrListElement; 

public List<SingleOrListElement> patch(Object singleOrListElement) {
  if (singleOrListElement instanceof List) {
    return (ArrayList<SingleOrListElement>) singleOrListElement;
  } else {
    LinkedHashMap map = (LinkedHashMap) singleOrListElement;
    return Collections.singletonList(SingletonList.builder()
                            .property1((String) map.get("p1"))
                            .property2((Integer) map.get("p2"))
                            .build());
  }

Is there a way to cast float as a decimal without rounding and preserving its precision?

Try SELECT CAST(field1 AS DECIMAL(10,2)) field1 and replace 10,2 with whatever precision you need.

What is the best way to implement "remember me" for a website?

I would store a user ID and a token. When the user comes back to the site, compare those two pieces of information against something persistent like a database entry.

As for security, just don't put anything in there that will allow someone to modify the cookie to gain extra benefits. For example, don't store their user groups or their password. Anything that can be modified that would circumvent your security should not be stored in the cookie.

How to enable explicit_defaults_for_timestamp?

On my system (Windows 8.1), the problem was with the server configuration. The server worked for the first time when I installed it. However, I forgot to check the "run as a service" option and this caused all the problem. I tried all possible solutions available on SO but nothing worked. So, I decided to reinstall MySQL Workbench. On executing the same msi file that I earlier used to install MySQL workbench, I reconfigured the server and allowed to run the server as a service.

What is difference between Lightsail and EC2?

In lightsail a virtual machine, SSD-based storage, data transfer, DNS management, and a static IP are all offered as a package. Whereas in normal case you provision an EC2 instance and then setup the rest of these things.Also Bandwidth included in the price, no security groups to set up, no need to worry about EBS volumes sizing.

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

Import Google Play Services library in Android Studio

I had similar issue Cannot resolve com.google.android.gms.common.

I followed setup guide http://developer.android.com/google/play-services/setup.html and it works!

Summary:

  1. Installed/Updated Google Play Services, and Google Repository from SDK Manager
  2. Added dependency in build.gradle: compile 'com.google.android.gms:play-services:4.0.30'
  3. Updated AndroidManifest.xml with <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

$on and $broadcast in angular

//Your broadcast in service

(function () { 
    angular.module('appModule').factory('AppService', function ($rootScope, $timeout) {

    function refreshData() {  
        $timeout(function() {         
            $rootScope.$broadcast('refreshData');
        }, 0, true);      
    }

    return {           
        RefreshData: refreshData
    };
}); }());

//Controller Implementation
 (function () {
    angular.module('appModule').controller('AppController', function ($rootScope, $scope, $timeout, AppService) {            

       //Removes Listeners before adding them 
       //This line will solve the problem for multiple broadcast call                             
       $scope.$$listeners['refreshData'] = [];

       $scope.$on('refreshData', function() {                                                    
          $scope.showData();             
       });

       $scope.onSaveDataComplete = function() { 
         AppService.RefreshData();
       };
    }); }());

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

DataTables fixed headers misaligned with columns in wide tables

try this

this works for me... i added the css for my solution and it works... although i didnt change anything in datatable css except { border-collapse: separate;}

.dataTables_scrollHeadInner {    /*for positioning header when scrolling is applied*/
padding:0% ! important
}

Running code in main thread from another thread

More precise Kotlin code using handler :

Handler(Looper.getMainLooper()).post {  
 // your codes here run on main Thread
 }

How to destroy JWT Tokens on logout?

You cannot manually expire a token after it has been created. Thus, you cannot log out with JWT on the server-side as you do with sessions.

JWT is stateless, meaning that you should store everything you need in the payload and skip performing a DB query on every request. But if you plan to have a strict log out functionality, that cannot wait for the token auto-expiration, even though you have cleaned the token from the client-side, then you might need to neglect the stateless logic and do some queries. so what's a solution?

  • Set a reasonable expiration time on tokens

  • Delete the stored token from client-side upon log out

  • Query provided token against The Blacklist on every authorized request

Blacklist

“Blacklist” of all the tokens that are valid no more and have not expired yet. You can use a DB that has a TTL option on documents which would be set to the amount of time left until the token is expired.

Redis

Redis is a good option for blacklist, which will allow fast in-memory access to the list. Then, in the middleware of some kind that runs on every authorized request, you should check if the provided token is in The Blacklist. If it is you should throw an unauthorized error. And if it is not, let it go and the JWT verification will handle it and identify if it is expired or still active.

For more information, see How to log out when using JWT. by Arpy Vanyan

Installing SetupTools on 64-bit Windows

I tried the above and adding the registry keys to the LOCALMACHINE was not getting the job done. So in case you are still stuck , try this.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\SOFTWARE\Python]

[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore]

[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7]

[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help]

[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help\Main Python Documentation] @="C:\Python27\Doc\python272.chm"

[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath] @="C:\Python27\"

[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath\InstallGroup] @="Python 2.7"

[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Modules]

[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\PythonPath] @="C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk"

Copy paste the above in notepad and save it as Python27.reg . Now run/merge the file as mentioned in the answers above. (Make sure the paths of Python installation are corrected as per your installation.

It simply does ,what the above answers suggest for a local machine ,to the current user.

How to run a script at a certain time on Linux?

Usually in Linux you use crontab for this kind of scduled tasks. But you have to specify the time when you "setup the timer" - so if you want it to be configurable in the file itself, you will have to create some mechanism to do that.

But in general, you would use for example:

30 1 * * 5 /path/to/script/script.sh

Would execute the script every Friday at 1:30 (AM) Here:

30 is minutes

1 is hour

next 2 *'s are day of month and month (in that order) and 5 is weekday

Google Colab: how to read data from my google drive?

from google.colab import drive
drive.mount('/content/drive')

This worked perfect for me I was later able to use the os library to access my files just like how I access them on my PC

INSERT INTO...SELECT for all MySQL columns

For the syntax, it looks like this (leave out the column list to implicitly mean "all")

INSERT INTO this_table_archive
SELECT *
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00'

For avoiding primary key errors if you already have data in the archive table

INSERT INTO this_table_archive
SELECT t.*
FROM this_table t
LEFT JOIN this_table_archive a on a.id=t.id
WHERE t.entry_date < '2011-01-01 00:00:00'
  AND a.id is null  # does not yet exist in archive

Is generator.next() visible in Python 3?

If your code must run under Python2 and Python3, use the 2to3 six library like this:

import six

six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'

Handling Enter Key in Vue.js

In vue 2, You can catch enter event with v-on:keyup.enter check the documentation:

https://vuejs.org/v2/guide/events.html#Key-Modifiers

I leave a very simple example:

_x000D_
_x000D_
var vm = new Vue({_x000D_
  el: '#app',_x000D_
  data: {msg: ''},_x000D_
  methods: {_x000D_
    onEnter: function() {_x000D_
       this.msg = 'on enter event';_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/vue"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input v-on:keyup.enter="onEnter" />_x000D_
  <h1>{{ msg }}</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Good luck

How do I get a button to open another activity?

A. Make sure your other activity is declared in manifest:

<activity
    android:name="MyOtherActivity"
    android:label="@string/app_name">
</activity>

All activities must be declared in manifest, even if they do not have an intent filter assigned to them.


B. In your MainActivity do something like this:

Button btn = (Button)findViewById(R.id.open_activity_button);    

btn.setOnClickListener(new View.OnClickListener() {         
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
        }
});

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

TableExport

TableExport - The simple, easy-to-implement library to export HTML tables to xlsx, xls, csv, and txt files.

To use this library, simple call the TableExport constructor:

new TableExport(document.getElementsByTagName("table"));

// OR simply

TableExport(document.getElementsByTagName("table"));

// OR using jQuery

$("table").tableExport(); 

Additional properties can be passed-in to customize the look and feel of your tables, buttons, and exported data. See here more info

How to install and run Typescript locally in npm?

You can now use ts-node, which makes your life as simple as

npm install -D ts-node
npm install -D typescript

ts-node script.ts

How do I correct the character encoding of a file?

On OS X Synalyze It! lets you display parts of your file in different encodings (all which are supported by the ICU library). Once you know what's the source encoding you can copy the whole file (bytes) via clipboard and insert into a new document where the target encoding (UTF-8 or whatever you like) is selected.

Very helpful when working with UTF-8 or other Unicode representations is UnicodeChecker

SSIS how to set connection string dynamically from a config file

First add a variable to your SSIS package (Package Scope) - I used FileName, OleRootFilePath, OleProperties, OleProvider. The type for each variable is "string". Then I create a Configuration file (Select each variable - value) - populate the values in the configuration file - Eg: for OleProperties - Microsoft.ACE.OLEDB.12.0; for OleProperties - Excel 8.0;HDR=, OleRootFilePath - Your Excel file path, FileName - FileName

In the Connection manager - I then set the Properties-> Expressions-> Connection string expression dynamically eg:

"Provider=" + @[User::OleProvider] + "Data Source=" + @[User::OleRootFilePath]
+ @[User::FileName]  + ";Extended Properties=\"" + @[User::OleProperties] + "NO \""+";"

This way once you set the variables values and change it in your configuration file - the connection string will change dynamically - this helps especially in moving from development to production environments.

Can we use join for two different database tables?

You could use Synonyms part in the database.

enter image description here

Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply. enter image description here

Visual Studio displaying errors even if projects build

I solved this problem by deleting the temporary files of Microsoft .NET framework. Location: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files and C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

Java ArrayList copy

List.copyOf ? unmodifiable list

You asked:

Is there no other way to assign a copy of a list

Java 9 brought the List.of methods for using literals to create an unmodifiable List of unknown concrete class.

LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
List< LocalDate > dates = List.of( 
    today.minusDays( 1 ) ,  // Yesterday
    today ,                 // Today
    today.plusDays( 1 )     // Tomorrow
);

Along with that we also got List.copyOf. This method too returns an unmodifiable List of unknown concrete class.

List< String > colors = new ArrayList<>( 4 ) ;          // Creates a modifiable `List`. 
colors.add ( "AliceBlue" ) ;
colors.add ( "PapayaWhip" ) ;
colors.add ( "Chartreuse" ) ;
colors.add ( "DarkSlateGray" ) ;
List< String > masterColors = List.copyOf( colors ) ;   // Creates an unmodifiable `List`.

By “unmodifiable” we mean the number of elements in the list, and the object referent held in each slot as an element, is fixed. You cannot add, drop, or replace elements. But the object referent held in each element may or may not be mutable.

colors.remove( 2 ) ;          // SUCCEEDS. 
masterColors.remove( 2 ) ;    // FAIL - ERROR.

See this code run live at IdeOne.com.

dates.toString(): [2020-02-02, 2020-02-03, 2020-02-04]

colors.toString(): [AliceBlue, PapayaWhip, DarkSlateGray]

masterColors.toString(): [AliceBlue, PapayaWhip, Chartreuse, DarkSlateGray]

You asked about object references. As others said, if you create one list and assign it to two reference variables (pointers), you still have only one list. Both point to the same list. If you use either pointer to modify the list, both pointers will later see the changes, as there is only one list in memory.

So you need to make a copy of the list. If you want that copy to be unmodifiable, use the List.copyOf method as discussed in this Answer. In this approach, you end up with two separate lists, each with elements that hold a reference to the same content objects. For example, in our example above using String objects to represent colors, the color objects are floating around in memory somewhere. The two lists hold pointers to the same color objects. Here is a diagram.

enter image description here

The first list colors is modifiable. This means that some elements could be removed as seen in code above, where we removed the original 3rd element Chartreuse (index of 2 = ordinal 3). And elements can be added. And the elements can be changed to point to some other String such as OliveDrab or CornflowerBlue.

In contrast, the four elements of masterColors are fixed. No removing, no adding, and no substituting another color. That List implementation is unmodifiable.

How to add extension methods to Enums

According to this site:

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions 
{
  public static DateTime From(this Duration duration, DateTime dateTime) 
  {
    switch (duration) 
    {
      case Day:   return dateTime.AddDays(1);
      case Week:  return dateTime.AddDays(7);
      case Month: return dateTime.AddMonths(1);
      default:    throw new ArgumentOutOfRangeException("duration");
    }
  }
}

I think enums are not the best choice in general but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

You can read more here at Microsft MSDN.

How to get setuptools and easy_install?

For python3 on Ubuntu

 sudo apt-get install python3-setuptools

How can I issue a single command from the command line through sql plus?

sqlplus user/password@sid < sqlfile.sql

This will also work from the DOS command line. In this case the file sqlfile.sql contains the SQL you wish to execute.

How to check if array is not empty?

print(len(a_list))

As many languages have the len() function, in Python this would work for your question.

If the output is not 0, the list is not empty.

Difference between <? super T> and <? extends T> in Java

Based on Bert F's answer I would like to explain my understanding.

Lets say we have 3 classes as

public class Fruit{}

public class Melon extends Fruit{}

public class WaterMelon extends Melon{}

Here We have

List<? extends Fruit> fruitExtendedList = …

//Says that I can be a list of any object as long as this object extends Fruit.

Ok now lets try to get some value from fruitExtendedList

Fruit fruit = fruitExtendedList.get(position)

//This is valid as it can only return Fruit or its subclass.

Again lets try

Melon melon = fruitExtendedList.get(position)

//This is not valid because fruitExtendedList can be a list of Fruit only, it may not be 
//list of Melon or WaterMelon and in java we cannot assign sub class object to 
//super class object reference without explicitly casting it.

Same is the case for

WaterMelon waterMelon = fruitExtendedList.get(position)

Now lets try to set some object in fruitExtendedList

Adding fruit object

fruitExtendedList.add(new Fruit())

//This in not valid because as we know fruitExtendedList can be a list of any 
//object as long as this object extends Fruit. So what if it was the list of  
//WaterMelon or Melon you cannot add Fruit to the list of WaterMelon or Melon.

Adding Melon object

fruitExtendedList.add(new Melon())

//This would be valid if fruitExtendedList was the list of Fruit but it may 
//not be, as it can also be the list of WaterMelon object. So, we see an invalid 
//condition already.

Finally let try to add WaterMelon object

fruitExtendedList.add(new WaterMelon())

//Ok, we got it now we can finally write to fruitExtendedList as WaterMelon 
//can be added to the list of Fruit or Melon as any superclass reference can point 
//to its subclass object.

But wait what if someone decides to make a new type of Lemon lets say for arguments sake SaltyLemon as

public class SaltyLemon extends Lemon{}

Now fruitExtendedList can be list of Fruit, Melon, WaterMelon or SaltyLemon.

So, our statement

fruitExtendedList.add(new WaterMelon())

is not valid either.

Basically we can say that we cannot write anything to a fruitExtendedList.

This sums up List<? extends Fruit>

Now lets see

List<? super Melon> melonSuperList= …

//Says that I can be a list of anything as long as its object has super class of Melon.

Now lets try to get some value from melonSuperList

Fruit fruit = melonSuperList.get(position)

//This is not valid as melonSuperList can be a list of Object as in java all 
//the object extends from Object class. So, Object can be super class of Melon and 
//melonSuperList can be a list of Object type

Similarly Melon, WaterMelon or any other object cannot be read.

But note that we can read Object type instances

Object myObject = melonSuperList.get(position)

//This is valid because Object cannot have any super class and above statement 
//can return only Fruit, Melon, WaterMelon or Object they all can be referenced by
//Object type reference.

Now, lets try to set some value from melonSuperList.

Adding Object type object

melonSuperList.add(new Object())

//This is not valid as melonSuperList can be a list of Fruit or Melon.
//Note that Melon itself can be considered as super class of Melon.

Adding Fruit type object

melonSuperList.add(new Fruit())

//This is also not valid as melonSuperList can be list of Melon

Adding Melon type object

melonSuperList.add(new Melon())

//This is valid because melonSuperList can be list of Object, Fruit or Melon and in 
//this entire list we can add Melon type object.

Adding WaterMelon type object

melonSuperList.add(new WaterMelon())

//This is also valid because of same reason as adding Melon

To sum it up we can add Melon or its subclass in melonSuperList and read only Object type object.

Build error: You must add a reference to System.Runtime

Removing the reference over the Nuget Package Manager and re-adding it solved the problem for me.

Locking a file in Python

I have been working on a situation like this where I run multiple copies of the same program from within the same directory/folder and logging errors. My approach was to write a "lock file" to the disc before opening the log file. The program checks for the presence of the "lock file" before proceeding, and waits for its turn if the "lock file" exists.

Here is the code:

def errlogger(error):

    while True:
        if not exists('errloglock'):
            lock = open('errloglock', 'w')
            if exists('errorlog'): log = open('errorlog', 'a')
            else: log = open('errorlog', 'w')
            log.write(str(datetime.utcnow())[0:-7] + ' ' + error + '\n')
            log.close()
            remove('errloglock')
            return
        else:
            check = stat('errloglock')
            if time() - check.st_ctime > 0.01: remove('errloglock')
            print('waiting my turn')

EDIT--- After thinking over some of the comments about stale locks above I edited the code to add a check for staleness of the "lock file." Timing several thousand iterations of this function on my system gave and average of 0.002066... seconds from just before:

lock = open('errloglock', 'w')

to just after:

remove('errloglock')

so I figured I will start with 5 times that amount to indicate staleness and monitor the situation for problems.

Also, as I was working with the timing, I realized that I had a bit of code that was not really necessary:

lock.close()

which I had immediately following the open statement, so I have removed it in this edit.

How to get child element by ID in JavaScript?

Here is a pure JavaScript solution (without jQuery)

var _Utils = function ()
{
    this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern 
    {
        var retElement = null;
        var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;

        for (var i = 0; i < lstChildren.length; i++)
        {
            if (lstChildren[i].id == childID)
            {
                retElement = lstChildren[i];
                break;
            }
        }

        return retElement;
    }

    this.getAllDescendant = function (element, lstChildrenNodes)
    {
        lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];

        var lstChildren = element.childNodes;

        for (var i = 0; i < lstChildren.length; i++) 
        {
            if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
            {
                lstChildrenNodes.push(lstChildren[i]);
                lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
            }
        }

        return lstChildrenNodes;
    }        
}
var Utils = new _Utils;

Example of use:

var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
                        "<tr>" +
                            "<td>" +
                                "<div id='divIdToSearch'>" +
                                "</div>" +
                            "</td>" +
                        "</tr>" +
                    "</table>";

var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);

How to connect to SQL Server database from JavaScript in the browser?

Web services

SQL 2005+ supports native WebServices that you could almost use although I wouldn't suggest it, because of security risks you may face. Why did I say almost. Well Javascript is not SOAP native, so it would be a bit more complicated to actually make it. You'd have to send and receive SOAP via XmlHttpRequest. Check google for Javascript SOAP clients.

Importing Excel files into R, xlsx or xls

For a solution that is free of fiddly external dependencies*, there is now readxl:

The readxl package makes it easy to get data out of Excel and into R. Compared to many of the existing packages (e.g. gdata, xlsx, xlsReadWrite) readxl has no external dependencies so it's easy to install and use on all operating systems. It is designed to work with tabular data stored in a single sheet.

Readxl supports both the legacy .xls format and the modern xml-based .xlsx format. .xls support is made possible the with libxls C library, which abstracts away many of the complexities of the underlying binary format. To parse .xlsx, we use the RapidXML C++ library.

It can be installed like so:

install.packages("readxl") # CRAN version

or

devtools::install_github("hadley/readxl") # development version

Usage

library(readxl)

# read_excel reads both xls and xlsx files
read_excel("my-old-spreadsheet.xls")
read_excel("my-new-spreadsheet.xlsx")

# Specify sheet with a number or name
read_excel("my-spreadsheet.xls", sheet = "data")
read_excel("my-spreadsheet.xls", sheet = 2)

# If NAs are represented by something other than blank cells,
# set the na argument
read_excel("my-spreadsheet.xls", na = "NA")

* not strictly true, it requires the Rcpp package, which in turn requires Rtools (for Windows) or Xcode (for OSX), which are dependencies external to R. But they don't require any fiddling with paths, etc., so that's an advantage over Java and Perl dependencies.

Update There is now the rexcel package. This promises to get Excel formatting, functions and many other kinds of information from the Excel file and into R.

MySQL select where column is not empty

you can use like operator wildcard to achieve this:

SELECT t.phone, 
       t.phone2 
FROM jewishyellow.users t
WHERE t.phone LIKE '813%' 
  AND t.phone2 like '[0-9]';

in this way, you could get all phone2 that have a number prefix.

What is the difference between bool and Boolean types in C#

I don't believe there is one.

bool is just an alias for System.Boolean

NPM clean modules

For windows environment:

"scripts": {
    "clean": "rmdir /s /q node_modules",
    ...
}

Easy pretty printing of floats in python?

List comps are your friend.

print ", ".join("%.2f" % f for f in list_o_numbers)

Try it:

>>> nums = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999]
>>> print ", ".join("%.2f" % f for f in nums)
9.00, 0.05, 0.03, 0.01

Websocket connections with Postman

I've run into this issue often enough that I finally created my own barebones GUI for testing websockets. It's called Socket Wrench, it supports

  • multiple concurrent connections to servers (with all responses and connections displayed in the same view),
  • comprehensive message history to enable easy re-use of messages, and
  • custom headers for the initial connection request.

It's available for Mac OS X, Windows and Linux and you can get it from here.

Case Statement Equivalent in R

Mixing plyr::mutate and dplyr::case_when works for me and is readable.

iris %>%
plyr::mutate(coolness =
     dplyr::case_when(Species  == "setosa"     ~ "not cool",
                      Species  == "versicolor" ~ "not cool",
                      Species  == "virginica"  ~ "super awesome",
                      TRUE                     ~ "undetermined"
       )) -> testIris
head(testIris)
levels(testIris$coolness)  ## NULL
testIris$coolness <- as.factor(testIris$coolness)
levels(testIris$coolness)  ## ok now
testIris[97:103,4:6]

Bonus points if the column can come out of mutate as a factor instead of char! The last line of the case_when statement, which catches all un-matched rows is very important.

     Petal.Width    Species      coolness
 97         1.3  versicolor      not cool
 98         1.3  versicolor      not cool  
 99         1.1  versicolor      not cool
100         1.3  versicolor      not cool
101         2.5  virginica     super awesome
102         1.9  virginica     super awesome
103         2.1  virginica     super awesome

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

Override method authenticationManagerBean in WebSecurityConfigurerAdapter to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder) as a Spring bean:

For example:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }

Ifelse statement in R with multiple conditions

another solution using dplyr is:

df <- ## your data ##
df <- df %>%
        mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))

Using LIMIT within GROUP BY to get N results per group?

No, you can't LIMIT subqueries arbitrarily (you can do it to a limited extent in newer MySQLs, but not for 5 results per group).

This is a groupwise-maximum type query, which is not trivial to do in SQL. There are various ways to tackle that which can be more efficient for some cases, but for top-n in general you'll want to look at Bill's answer to a similar previous question.

As with most solutions to this problem, it can return more than five rows if there are multiple rows with the same rate value, so you may still need a quantity of post-processing to check for that.

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

Because some database can throw an exception at dbContextTransaction.Commit() so better this:

using (var context = new BloggingContext()) 
{ 
  using (var dbContextTransaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      context.Database.ExecuteSqlCommand( 
          @"UPDATE Blogs SET Rating = 5" + 
              " WHERE Name LIKE '%Entity Framework%'" 
          ); 

      var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
      foreach (var post in query) 
      { 
          post.Title += "[Cool Blog]"; 
      } 

      context.SaveChanges(false); 

      dbContextTransaction.Commit(); 

      context.AcceptAllChanges();
    } 
    catch (Exception) 
    { 
      dbContextTransaction.Rollback(); 
    } 
  } 
} 

String comparison using '==' vs. 'strcmp()'

if ($password === $password2) { ... } is not a safe thing to do when comparing passwords or password hashes where one of the inputs is user controlled.
In that case it creates a timing oracle allowing an attacker to derive the actual password hash from execution time differences.
Use if (hash_equals($password, $password2)) { ... } instead, because hash_equals performs "timing attack safe string comparison".

How to convert JSON string into List of Java object?

You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

ASP.Net MVC Redirect To A Different View

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is:

return RedirectToAction("Index", model);

Then in your Index method, return the view you want.

Remove Android App Title Bar

There are two options I'd like to present:

  1. Change the visibility of the SupportActionBar in JAVA code
  2. Choose another Style in your project's style.xml

1: Add getSupportActionBar().hide(); to your onCreate method.

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

2: Another option is to change the style of your Application. Check out the styles.xml in "app->res->values" and change

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

SQL/mysql - Select distinct/UNIQUE but return all columns?

I would suggest using

SELECT  * from table where field1 in 
(
  select distinct field1 from table
)

this way if you have the same value in field1 across multiple rows, all the records will be returned.

How to increase scrollback buffer size in tmux?

The history limit is a pane attribute that is fixed at the time of pane creation and cannot be changed for existing panes. The value is taken from the history-limit session option (the default value is 2000).

To create a pane with a different value you will need to set the appropriate history-limit option before creating the pane.

To establish a different default, you can put a line like the following in your .tmux.conf file:

set-option -g history-limit 3000

Note: Be careful setting a very large default value, it can easily consume lots of RAM if you create many panes.

For a new pane (or the initial pane in a new window) in an existing session, you can set that session’s history-limit. You might use a command like this (from a shell):

tmux set-option history-limit 5000 \; new-window

For (the initial pane of the initial window in) a new session you will need to set the “global” history-limit before creating the session:

tmux set-option -g history-limit 5000 \; new-session

Note: If you do not re-set the history-limit value, then the new value will be also used for other panes/windows/sessions created in the future; there is currently no direct way to create a single new pane/window/session with its own specific limit without (at least temporarily) changing history-limit (though show-option (especially in 1.7 and later) can help with retrieving the current value so that you restore it later).

How to get the cursor to change to the hand when hovering a <button> tag

 #more {
    background:none;
    border:none;
    color:#FFF;
    font-family:Verdana, Geneva, sans-serif;
    cursor: pointer;
}

Select mySQL based only on month and year

Yeah this is working, but it returns one row only while there is several rows to retrieve using selected columns only. Like SELECT Title,Date FROM mytable WHERE YEAR(Date)=2017 AND MONTH(Date)=09 returns only one row.

Dictionary with list of strings as value

Just create a new array in your dictionary

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));

php delete a single file in directory

// This code was tested by me (Helio Barbosa)

    // this directory (../backup) is for try only.
    // it is necessary create it and put files into him.

    $hDir = '../backup';
    if ($handle = opendir( $hDir )) {
        echo "Manipulador de diretório: $handle\n";
        echo "Arquivos:\n";

        /* Esta é a forma correta de varrer o diretório */
        /* Here is the correct form to do find files into the directory */
        while (false !== ($file = readdir($handle))) {
            // echo($file . "</br>");
            $filepath = $hDir . "/" . $file ;
            // echo( $filepath . "</br>" );
            if(is_file($filepath))
            {
                echo("Deleting:" . $file . "</br>");
                unlink($filepath);
            }           
        }

        closedir($handle);
    }

macro for Hide rows in excel 2010

Well, you're on the right path, Benno!

There are some tips regarding VBA programming that might help you out.

  1. Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.

  2. As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.

  3. Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.

Now, let's have a draft code...

Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.

Hope it helps!

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim oSheet As Excel.Worksheet

    'We only want to do something if the changed cell is B6, right?
    If Target.Address = "$B$6" Then

        'Checks if it's a number...
        If IsNumeric(Target.Value) Then

            'Let's avoid values out of your bonds, correct?
            If Target.Value > 0 And Target.Value < 51 Then

                'Let's assign the worksheet we'll show / hide rows to one variable and then
                '   use only the reference to the variable itself instead of the sheet name.
                '   It's safer.

                'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
                '   the sheet index within the workbook
                Set oSheet = ActiveWorkbook.Sheets("Sheet 2")

                'We'll unhide before hide, to ensure we hide the correct ones
                oSheet.Range("A7:A56").EntireRow.Hidden = False

                oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True

            End If

        End If

    End If

End Sub

PHP class: Global variable as property in class

You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible. The key is the part where you assign by reference in the constructor.

$GLOBALS = array(
    'MyNumber' => 1
);

class Foo {
    protected $glob;

    public function __construct() {
        global $GLOBALS;
        $this->glob =& $GLOBALS;
    }

    public function getGlob() {
        return $this->glob['MyNumber'];
    }
}

$f = new Foo;

echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";

The output will be

1
2

which indicates that it's being assigned by reference, not value.

As I said, it will be a nightmare to debug, so you really shouldn't do this. Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.

Remove last specific character in a string c#

Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))

output:

1,5,12,34,123

jQuery Datepicker with text input that doesn't allow user input

$("#txtfromdate").datepicker({         
    numberOfMonths: 2,
    maxDate: 0,               
    dateFormat: 'dd-M-yy'       
}).attr('readonly', 'readonly');

add the readonly attribute in the jquery.

How to read a CSV file from a URL with Python?

Using pandas it is very simple to read a csv file directly from a url

import pandas as pd
data = pd.read_csv('https://example.com/passkey=wedsmdjsjmdd')

This will read your data in tabular format, which will be very easy to process

What are the advantages and disadvantages of recursion?

Recursion gets a bad rep, I'm always surprised by the number of developers that wont even touch recursion because someone told them it was evil incarnate.

I've learned through trial and error that when done properly recursion can be one of the fastest ways to iterate over something, it is not a steadfast rule and each language/ compiler/ engine has it's own quirks so mileage will vary.

In javascript I can reliably speed up almost any iterative process by introducing recursion with the added benefit of reducing side effects and making the code more clear concise and reusable. Also pro tip its possible to get around the stack overflow issue (and no you dont disable the warning).

My personal Pros & Cons:

Pros:

- Reduces side effects.
- Makes code more concise and easier to reason about.
- Reduces system resource usage and performs better than the traditional for loop.

Cons:

- Can lead to stack overflow.
- More complicated to setup than a traditional for loop.

Mileage will vary depending on language/ complier/ engine.

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

For me, the problem occurs when I've downloaded macOS Compressed Archive which underlying directory contains

jdk-11.0.8.jdk
- Contents
  - Home
    - bin
    - ...
  - MacOS
  - _CodeSignature

So, to solve the problem, JAVA_HOME should be pointed directly to /Path-to-JDK/Contents/Home.

Java Look and Feel (L&F)

You can try L&F which i am developing - WebLaF
It combines three parts required for successful UI development:

  • Cross-platform re-stylable L&F for Swing applications
  • Large set of extended Swing components
  • Various utilities and managers

Binaries: https://github.com/mgarin/weblaf/releases
Source: https://github.com/mgarin/weblaf
Licenses: GPLv3 and Commercial

A few examples showing how some of WebLaF components look like: Some of WebLaF components

Main reason why i have started with a totally new L&F is that most of existing L&F lack flexibility - you cannot re-style them in most cases (you can only change a few colors and turn on/off some UI elements in best case) and/or there are only inconvenient ways to do that. Its even worse when it comes to custom/3rd party components styling - they doesn't look similar to other components styled by some specific L&F or even totally different - that makes your application look unprofessional and unpleasant.

My goal is to provide a fully customizable L&F with a pack of additional widely-known and useful components (for example: date chooser, tree table, dockable and document panes and lots of other) and additional helpful managers and utilities, which will reduce the amount of code required to quickly integrate WebLaF into your application and help creating awesome UIs using Swing.

How can I beautify JSON programmatically?

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

get user timezone

Just as Oded has answered. You need to have this sort of detection functionality in javascript.

I've struggled with this myself and realized that the offset is not enough. It does not give you any information about daylight saving for example. I ended up writing some code to map to zoneinfo database keys.

By checking several dates around a year you can more accurately determine a timezone.

Try the script here: http://jsfiddle.net/pellepim/CsNcf/

Simply change your system timezone and click run to test it. If you are running chrome you need to do each test in a new tab though (and safar needs to be restarted to pick up timezone changes).

If you want more details of the code check out: https://bitbucket.org/pellepim/jstimezonedetect/

How do I get the last character of a string?

public String lastChars(String a) {
if(a.length()>=1{
String str1 =a.substring(b.length()-1);
}
return str1;
}

Set size of HTML page and browser window

You could use width: 100%; in your css.

Creating a button in Android Toolbar

I have added text in ToolBar :

menu_skip.xml

<menu 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"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_settings"
        android:title="@string/text_skip"
        app:showAsAction="never" />
</menu>

MainActivity.java

@Override
boolean onCreateOptionsMenu(Menu menu) {
    inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_otp_skip, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // action with ID action_refresh was selected
        case R.id.menu_item_skip:
            Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
                    .show();
            break;
        default:
            break;
    }
    return true;
}

Compare 2 arrays which returns difference

Array operations like this is not jQuery's strongest point. You should consider a library such as Underscorejs, specifically the difference function.

How do I type a TAB character in PowerShell?

If it helps you can embed a tab character in a double quoted string:

PS> "`t hello"

How to fluently build JSON in Java?

See the Java EE 7 Json specification. This is the right way:

String json = Json.createObjectBuilder()
            .add("key1", "value1")
            .add("key2", "value2")
            .build()
            .toString();

Combine two ActiveRecord::Relation objects

This is how I've "handled" it if you use pluck to get an identifier for each of the records, join the arrays together and then finally do a query for those joined ids:

  transaction_ids = @club.type_a_trans.pluck(:id) + @club.type_b_transactions.pluck(:id) + @club.type_c_transactions.pluck(:id)
  @transactions = Transaction.where(id: transaction_ids).limit(100)

Push method in React Hooks (useState)?

setTheArray([...theArray, newElement]); is the simplest answer but be careful for the mutation of items in theArray. Use deep cloning of array items.

How to always show the vertical scrollbar in a browser?

Add the class to the div you want to be scrollable.

overflow-x: hidden; hides the horizantal scrollbar. While overflow-y: scroll; allows you to scroll vertically.

<!DOCTYPE html>
<html>
<head>
<style>
.scroll {
    width: 500px;
    height: 300px;
    overflow-x: hidden; 
    overflow-y: scroll;
}


</style>
</head>
<body>

<div class="scroll"><h1> DATA </h1></div>

Given the lat/long coordinates, how can we find out the city/country?

You need geopy

pip install geopy

and then:

from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.reverse("48.8588443, 2.2943506")

print(location.address)

to get more information:

print (location.raw)

{'place_id': '24066644', 'osm_id': '2387784956', 'lat': '41.442115', 'lon': '-8.2939909', 'boundingbox': ['41.442015', '41.442215', '-8.2940909', '-8.2938909'], 'address': {'country': 'Portugal', 'suburb': 'Oliveira do Castelo', 'house_number': '99', 'city_district': 'Oliveira do Castelo', 'country_code': 'pt', 'city': 'Oliveira, São Paio e São Sebastião', 'state': 'Norte', 'state_district': 'Ave', 'pedestrian': 'Rua Doutor Avelino Germano', 'postcode': '4800-443', 'county': 'Guimarães'}, 'osm_type': 'node', 'display_name': '99, Rua Doutor Avelino Germano, Oliveira do Castelo, Oliveira, São Paio e São Sebastião, Guimarães, Braga, Ave, Norte, 4800-443, Portugal', 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright'}

Do not want scientific notation on plot axis

Try this. I purposely broke out various parts so you can move things around.

library(sfsmisc)

#Generate the data
x <- 1:100000
y <- 1:100000

#Setup the plot area
par(pty="m", plt=c(0.1, 1, 0.1, 1), omd=c(0.1,0.9,0.1,0.9))

#Plot a blank graph without completing the x or y axis
plot(x, y, type = "n", xaxt = "n", yaxt="n", xlab="", ylab="", log = "x", col="blue")
mtext(side=3, text="Test Plot", line=1.2, cex=1.5)

#Complete the x axis
eaxis(1, padj=-0.5, cex.axis=0.8)
mtext(side=1, text="x", line=2.5)

#Complete the y axis and add the grid
aty <- seq(par("yaxp")[1], par("yaxp")[2], (par("yaxp")[2] - par("yaxp")[1])/par("yaxp")[3])
axis(2, at=aty, labels=format(aty, scientific=FALSE), hadj=0.9, cex.axis=0.8, las=2)
mtext(side=2, text="y", line=4.5)
grid()

#Add the line last so it will be on top of the grid
lines(x, y, col="blue")

enter image description here

How would I extract a single file (or changes to a file) from a git stash?

The simplest concept to understand, although maybe not the best, is you have three files changed and you want to stash one file.

If you do git stash to stash them all, git stash apply to bring them back again and then git checkout f.c on the file in question to effectively reset it.

When you want to unstash that file run do a git reset --hard and then run git stash apply again, taking advantage ofthe fact that git stash apply doesn't clear the diff from the stash stack.

Numpy - add row to array

If no calculations are necessary after every row, it's much quicker to add rows in python, then convert to numpy. Here are timing tests using python 3.6 vs. numpy 1.14, adding 100 rows, one at a time:

import numpy as np 
from time import perf_counter, sleep

def time_it():
    # Compare performance of two methods for adding rows to numpy array
    py_array = [[0, 1, 2], [0, 2, 0]]
    py_row = [4, 5, 6]
    numpy_array = np.array(py_array)
    numpy_row = np.array([4,5,6])
    n_loops = 100

    start_clock = perf_counter()
    for count in range(0, n_loops):
       numpy_array = np.vstack([numpy_array, numpy_row]) # 5.8 micros
    duration = perf_counter() - start_clock
    print('numpy 1.14 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))

    start_clock = perf_counter()
    for count in range(0, n_loops):
        py_array.append(py_row) # .15 micros
    numpy_array = np.array(py_array) # 43.9 micros       
    duration = perf_counter() - start_clock
    print('python 3.6 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
    sleep(15)

#time_it() prints:

numpy 1.14 takes 5.971 micros per row
python 3.6 takes 0.694 micros per row

So, the simple solution to the original question, from seven years ago, is to use vstack() to add a new row after converting the row to a numpy array. But a more realistic solution should consider vstack's poor performance under those circumstances. If you don't need to run data analysis on the array after every addition, it is better to buffer the new rows to a python list of rows (a list of lists, really), and add them as a group to the numpy array using vstack() before doing any data analysis.

Convert timedelta to total seconds

You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) expression.

(1) If all you need is the difference between two instants in seconds, the very simple time.time() does the job.

(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:

gmtime() returns a time tuple in UTC but mktime() expects a time tuple in local time.

I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31

>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time

You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow() which won't jump by an hour when DST goes on/off and may give you more precision than time.time()

How do I tell if a regular file does not exist in Bash?

It's worth mentioning that if you need to execute a single command you can abbreviate

if [ ! -f "$file" ]; then
    echo "$file"
fi

to

test -f "$file" || echo "$file"

or

[ -f "$file" ] || echo "$file"

javascript create empty array of a given size

As of ES5 (when this answer was given):

If you want an empty array of undefined elements, you could simply do

var whatever = new Array(5);

this would give you

[undefined, undefined, undefined, undefined, undefined]

and then if you wanted it to be filled with empty strings, you could do

whatever.fill('');

which would give you

["", "", "", "", ""]

And if you want to do it in one line:

var whatever = Array(5).fill('');

How to get the URL without any parameters in JavaScript?

You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]

How to use conditional breakpoint in Eclipse?

Put your breakpoint. Right-click the breakpoint image on the margin and choose Breakpoint Properties:

enter image description here

Configure condition as you see fit:

enter image description here

How to check if all inputs are not empty with jQuery

Use each:

var isValid;
$("input").each(function() {
   var element = $(this);
   if (element.val() == "") {
       isValid = false;
   }
});

However you probably will be better off using something like jQuery validate which IMO is cleaner.

How can I scroll a web page using selenium webdriver in python?

None of these answers worked for me, at least not for scrolling down a facebook search result page, but I found after a lot of testing this solution:

while driver.find_element_by_tag_name('div'):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    Divs=driver.find_element_by_tag_name('div').text
    if 'End of Results' in Divs:
        print 'end'
        break
    else:
        continue

How to access custom attributes from event object in React?

To help you get the desired outcome in perhaps a different way than you asked:

render: function() {
    ...
    <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
    ...
},
removeTag: function(i) {
    // do whatever
},

Notice the bind(). Because this is all javascript, you can do handy things like that. We no longer need to attach data to DOM nodes in order to keep track of them.

IMO this is much cleaner than relying on DOM events.

Update April 2017: These days I would write onClick={() => this.removeTag(i)} instead of .bind

How can I solve equations in Python?

How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…

What is the time complexity of indexing, inserting and removing from common data structures?

Keep in mind that unless you're writing your own data structure (e.g. linked list in C), it can depend dramatically on the implementation of data structures in your language/framework of choice. As an example, take a look at the benchmarks of Apple's CFArray over at Ridiculous Fish. In this case, the data type, a CFArray from Apple's CoreFoundation framework, actually changes data structures depending on how many objects are actually in the array - changing from linear time to constant time at around 30,000 objects.

This is actually one of the beautiful things about object-oriented programming - you don't need to know how it works, just that it works, and the 'how it works' can change depending on requirements.

When do I need to use AtomicBoolean in Java?

When multiple threads need to check and change the boolean. For example:

if (!initialized) {
   initialize();
   initialized = true;
}

This is not thread-safe. You can fix it by using AtomicBoolean:

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}

git pull aborted with error filename too long

As someone that has ran into this problem constantly with java repositories on Windows, the best solution is to install Cygwin (https://www.cygwin.com/) and use its git installation under all > devel > git.

The reason this is the best solution I have come across is since Cygwin manages the long path names so other provided commands benefit. Ex: find, cp and rm. Trust me, the real problem begins when you have to delete path names that are too long in Windows.

iOS - Calling App Delegate method from ViewController

And if anyone is wondering how to do this in swift:

if let myDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
   myDelegate.someMethod()
}

How to write console output to a txt file

In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.

search in java ArrayList

Personally I rarely write loops myself now when I can get away with it... I use the Jakarta commons libs:

Customer findCustomerByid(final int id){
    return (Customer) CollectionUtils.find(customers, new Predicate() {
        public boolean evaluate(Object arg0) {
            return ((Customer) arg0).getId()==id;
        }
    });
}

Yay! I saved one line!

Java Regex to Validate Full Name allow only Spaces and Letters

This works for me with validation of bootstrap

$(document).ready(function() {
$("#fname").keypress(function(e) {
var regex = new RegExp("^[a-zA-Z ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
 return true;
}

how to get text from textview

You have to do the following:

a=a.replace("\n"," ");
a=a.trim();
String b[]=a.split("+");
int k=Integer.ValueOf(b[0]);
int l=Integer.ValueOf(b[1]);
int sum=k+l;

If statement in aspx page

Here's a simple one written in VB for an ASPX page:

                If myVar > 1 Then
                    response.write("Greater than 1")
                else
                    response.write("Not!")
                End If

How do I create a file AND any folders, if the folders don't exist?

DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
    Directory.GetCreationTime(path));

See this MSDN page.

Hope that helps out!

Why is this rsync connection unexpectedly closed on Windows?

i get the solution. i've using cygwin and this is the problem the rsync command for Windows work only in windows shell and works in the windows powershell.

A few times it has happened the same error between two linux boxes. and appears to be by incompatible versions of rsync

how to stop a for loop

Others ways to do the same is:

el = L[0][0]
m=len(L)

print L == [[el]*m]*m

Or:

first_el = L[0][0]
print all(el == first_el for inner_list in L for el in inner_list)

Iterating over a 2 dimensional python list

zip will transpose the list, after that you can concatenate the outputs.

In [3]: zip(*[ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ])
Out[3]: [('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1')]

Is there a command for formatting HTML in the Atom editor?

You can add atom beauty package for formatting text in atom..

file --> setting --> Install

then you type atom-beautify in search area.

then click Package button.. select atom beuty and install it.

next you can format your text using (Alt + ctrl + b) or right click and select beautify editor contents

Go Back to Previous Page

Depends what it is that you're trying to do it with. You could use something like this:

echo "<a href=\"javascript:history.go(-1)\">GO BACK</a>";

That's the simplest option. The other poster is right about having a proper flow of history but this is an example for you.

Just edited, orig version wasn't indented and looked like nothing. ;)

How to show full height background image?

CSS can do that with background-size: cover;

But to be more detailed and support more browsers...

Use aspect ratio like this:

 aspectRatio      = $bg.width() / $bg.height();

FIDDLE

Possible to perform cross-database queries with PostgreSQL?

I have checked and tried to create a foreign key relationships between 2 tables in 2 different databases using both dblink and postgres_fdw but with no result.

Having read the other peoples feedback on this, for example here and here and in some other sources it looks like there is no way to do that currently:

The dblink and postgres_fdw indeed enable one to connect to and query tables in other databases, which is not possible with the standard Postgres, but they do not allow to establish foreign key relationships between tables in different databases.

Returning a boolean from a Bash function

Why you should care what I say in spite of there being a 250+ upvote answer

It's not that 0 = true and 1 = false. It is: zero means no failure (success) and non-zero means failure (of type N).

While the selected answer is technically "true" please do not put return 1** in your code for false. It will have several unfortunate side effects.

  1. Experienced developers will spot you as an amateur (for the reason below).
  2. Experienced developers don't do this (for all the reasons below).
  3. It is error prone.
    • Even experienced developers can mistake 0 and 1 as false and true respectively (for the reason above).
  4. It requires (or will encourage) extraneous and ridiculous comments.
  5. It's actually less helpful than implicit return statuses.

Learn some bash

The bash manual says (emphasis mine)

return [n]

Cause a shell function to stop executing and return the value n to its caller. If n is not supplied, the return value is the exit status of the last command executed in the function.

Therefore, we don't have to EVER use 0 and 1 to indicate True and False. The fact that they do so is essentially trivial knowledge useful only for debugging code, interview questions, and blowing the minds of newbies.

The bash manual also says

otherwise the function’s return status is the exit status of the last command executed

The bash manual also says

($?) Expands to the exit status of the most recently executed foreground pipeline.

Whoa, wait. Pipeline? Let's turn to the bash manual one more time.

A pipeline is a sequence of one or more commands separated by one of the control operators ‘|’ or ‘|&’.

Yes. They said 1 command is a pipeline. Therefore, all 3 of those quotes are saying the same thing.

  • $? tells you what happened last.
  • It bubbles up.

My answer

So, while @Kambus demonstrated that with such a simple function, no return is needed at all. I think was unrealistically simple compared to the needs of most people who will read this.

Why return?

If a function is going to return its last command's exit status, why use return at all? Because it causes a function to stop executing.

Stop execution under multiple conditions

01  function i_should(){
02      uname="$(uname -a)"
03
04      [[ "$uname" =~ Darwin ]] && return
05
06      if [[ "$uname" =~ Ubuntu ]]; then
07          release="$(lsb_release -a)"
08          [[ "$release" =~ LTS ]]
09          return
10      fi
11
12      false
13  }
14
15  function do_it(){
16      echo "Hello, old friend."
17  }
18
19  if i_should; then
20    do_it
21  fi

What we have here is...

Line 04 is an explicit[-ish] return true because the RHS of && only gets executed if the LHS was true

Line 09 returns either true or false matching the status of line 08

Line 13 returns false because of line 12

(Yes, this can be golfed down, but the entire example is contrived.)

Another common pattern

# Instead of doing this...
some_command
if [[ $? -eq 1 ]]; then
    echo "some_command failed"
fi

# Do this...
some_command
status=$?
if ! $(exit $status); then
    echo "some_command failed"
fi

Notice how setting a status variable demystifies the meaning of $?. (Of course you know what $? means, but someone less knowledgeable than you will have to Google it some day. Unless your code is doing high frequency trading, show some love, set the variable.) But the real take-away is that "if not exist status" or conversely "if exit status" can be read out loud and explain their meaning. However, that last one may be a bit too ambitious because seeing the word exit might make you think it is exiting the script, when in reality it is exiting the $(...) subshell.


** If you absolutely insist on using return 1 for false, I suggest you at least use return 255 instead. This will cause your future self, or any other developer who must maintain your code to question "why is that 255?" Then they will at least be paying attention and have a better chance of avoiding a mistake.

TypeError: can only concatenate list (not "str") to list

You can use:

newinv=inventory+[add]

but using append is better since it doesn't create a new list:

inventory.append(add)

Oracle PL/SQL string compare issue

I compare strings using = and not <>. I've found out that in this context = seems to work in more reasonable fashion than <>. I have specified that two empty (or NULL) strings are equal. The real implementation returns PL/SQL boolean, but here I changed that to pls_integer (0 is false and 1 is true) to be able easily demonstrate the function.

create or replace function is_equal(a in varchar2, b in varchar2)
return pls_integer as
begin
  if a is null and b is null then
    return 1;
  end if;

  if a = b then
    return 1;
  end if;

  return 0;
end;
/
show errors

begin
  /* Prints 0 */
  dbms_output.put_line(is_equal('AAA', 'BBB'));
  dbms_output.put_line(is_equal('AAA', null));
  dbms_output.put_line(is_equal(null, 'BBB'));
  dbms_output.put_line(is_equal('AAA', ''));
  dbms_output.put_line(is_equal('', 'BBB'));

  /* Prints 1 */
  dbms_output.put_line(is_equal(null, null));
  dbms_output.put_line(is_equal(null, ''));
  dbms_output.put_line(is_equal('', ''));
  dbms_output.put_line(is_equal('AAA', 'AAA'));
end;
/

ArrayList insertion and retrieval order

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

Listen to changes within a DIV and act accordingly

http://api.jquery.com/change/

change does only work on input form elements.

you could just trigger a function after your XML / XSL transformation or make a listener:

var html = $('#laneconfigdisplay').html()
setInterval(function(){ if($('#laneconfigdisplay').html() != html){ alert('woo'); html = $('#laneconfigdisplay').html() } }, 10000) //checks your content box all 10 seconds and triggers alert when content has changed...

Angular File Upload

In my case, I'm using http interceptor, thing is that by default my http interceptor sets content-type header as application/json, but for file uploading I'm using multer library. So little bit changing my http.interceptor defines if request body is FormData it removes headers and doesn't touch access token. Here is part of code, which made my day.

if (request.body instanceof FormData) {
  request = request.clone({ headers: request.headers.delete('Content-Type', 'application/json') });
}

if (request.body instanceof FormData) {
  request = request.clone({ headers: request.headers.delete('Accept', 'application/json')});
}

Bloomberg Open API

This API has been available for a long time and enables to get access to market data (including live) if you are running a Bloomberg Terminal or have access to a Bloomberg Server, which is chargeable.

The only difference is that the API (not its code) has been open sourced, so it can now be used as a dependency in an open source project for example, without any copyrights issues, which was not the case before.

File Upload In Angular?

From the answers above I build this with Angular 5.x

Just call uploadFile(url, file).subscribe() to trigger an upload

import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpRequest, HttpEvent} from '@angular/common/http';
import {Observable} from "rxjs";

@Injectable()
export class UploadService {

  constructor(private http: HttpClient) { }

  // file from event.target.files[0]
  uploadFile(url: string, file: File): Observable<HttpEvent<any>> {

    let formData = new FormData();
    formData.append('upload', file);

    let params = new HttpParams();

    const options = {
      params: params,
      reportProgress: true,
    };

    const req = new HttpRequest('POST', url, formData, options);
    return this.http.request(req);
  }
}

Use it like this in your component

  // At the drag drop area
  // (drop)="onDropFile($event)"
  onDropFile(event: DragEvent) {
    event.preventDefault();
    this.uploadFile(event.dataTransfer.files);
  }

  // At the drag drop area
  // (dragover)="onDragOverFile($event)"
  onDragOverFile(event) {
    event.stopPropagation();
    event.preventDefault();
  }

  // At the file input element
  // (change)="selectFile($event)"
  selectFile(event) {
    this.uploadFile(event.target.files);
  }

  uploadFile(files: FileList) {
    if (files.length == 0) {
      console.log("No file selected!");
      return

    }
    let file: File = files[0];

    this.upload.uploadFile(this.appCfg.baseUrl + "/api/flash/upload", file)
      .subscribe(
        event => {
          if (event.type == HttpEventType.UploadProgress) {
            const percentDone = Math.round(100 * event.loaded / event.total);
            console.log(`File is ${percentDone}% loaded.`);
          } else if (event instanceof HttpResponse) {
            console.log('File is completely loaded!');
          }
        },
        (err) => {
          console.log("Upload Error:", err);
        }, () => {
          console.log("Upload done");
        }
      )
  }

Match everything except for specified strings

Matching Anything but Given Strings

If you want to match the entire string where you want to match everything but certain strings you can do it like this:

^(?!(red|green|blue)$).*$

This says, start the match from the beginning of the string where it cannot start and end with red, green, or blue and match anything else to the end of the string.

You can try it here: https://regex101.com/r/rMbYHz/2

Note that this only works with regex engines that support a negative lookahead.

C++: Print out enum value as text

This is a good way,

enum Rank { ACE = 1, DEUCE, TREY, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING };

Print it with an array of character arrays

const char* rank_txt[] = {"Ace", "Deuce", "Trey", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Four", "King" } ;

Like this

std::cout << rank_txt[m_rank - 1]

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

Git pull is actually a combo tool: it runs git fetch (getting the changes) and git merge (merging them with your current copy)

Are you sure you are on the correct branch?

Make Iframe to fit 100% of container's remaining height

If you have access to the content of the iframe that will be loaded, you can tell its parent to resize whenever it resizes..

    $(window).resize(function() {
        $(parent.document)
            .find("iframe")
            .css("height", $("body").css("height"));        
    }).trigger("resize");

If you have more than one iframe on the page, you may need to use id's or other clever methods to enhance .find("iframe") so that you're selecting the correct one.

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

In my case

spring.profiles = production // remove it to fix

in application.properties was the reason

Sorting Directory.GetFiles()

The MSDN Documentation states that there is no guarantee of any order on the return values. You have to use the Sort() method.

How to update Ruby with Homebrew?

To upgrade Ruby with rbenv: Per the rbenv README

  • Update first: brew upgrade rbenv ruby-build
  • See list of Ruby versions: versions available: rbenv install -l
  • Install: rbenv install <selected version>

Does it make sense to use Require.js with Angular.js?

To restate what I think the OP's question really is:

If I'm building an application principally in Angular 1.x, and (implicitly) doing so in the era of Grunt/Gulp/Broccoli and Bower/NPM, and I maybe have a couple additional library dependencies, does Require add clear, specific value beyond what I get by using Angular without Require?

Or, put another way:

"Does vanilla Angular need Require to manage basic Angular component-loading effectively, if I have other ways of handling basic script-loading?"

And I believe the basic answer to that is: "not unless you've got something else going on, and/or you're unable to use newer, more modern tools."

Let's be clear at the outset: RequireJS is a great tool that solved some very important problems, and started us down the road that we're on, toward more scalable, more professional Javascript applications. Importantly, it was the first time many people encountered the concept of modularization and of getting things out of global scope. So, if you're going to build a Javascript application that needs to scale, then Require and the AMD pattern are not bad tools for doing that.

But, is there anything particular about Angular that makes Require/AMD a particularly good fit? No. In fact, Angular provides you with its own modularization and encapsulation pattern, which in many ways renders redundant the basic modularization features of AMD. And, integrating Angular modules into the AMD pattern is not impossible, but it's a bit... finicky. You'll definitely be spending time getting the two patterns to integrate nicely.

For some perspective from the Angular team itself, there's this, from Brian Ford, author of the Angular Batarang and now a member of the Angular core team:

I don't recommend using RequireJS with AngularJS. Although it's certainly possible, I haven't seen any instance where RequireJS was beneficial in practice.

So, on the very specific question of AngularJS: Angular and Require/AMD are orthogonal, and in places overlapping. You can use them together, but there's no reason specifically related to the nature/patterns of Angular itself.

But what about basic management of internal and external dependencies for scalable Javascript applications? Doesn't Require do something really critical for me there?

I recommend checking out Bower and NPM, and particularly NPM. I'm not trying to start a holy war about the comparative benefits of these tools. I merely want to say: there are other ways to skin that cat, and those ways may be even better than AMD/Require. (They certainly have much more popular momentum in late-2015, particularly NPM, combined with ES6 or CommonJS modules. See related SO question.)

What about lazy-loading?

Note that lazy-loading and lazy-downloading are different. Angular's lazy-loading doesn't mean you're pulling them direct from the server. In a Yeoman-style application with javascript automation, you're concatenating and minifying the whole shebang together into a single file. They're present, but not executed/instantiated until needed. The speed and bandwidth improvements you get from doing this vastly, vastly outweigh any alleged improvements from lazy-downloading a particular 20-line controller. In fact, the wasted network latency and transmission overhead for that controller is going to be an order of magnitude greater than the size of the controller itself.

But let's say you really do need lazy-downloading, perhaps for infrequently-used pieces of your application, such as an admin interface. That's a very legitimate case. Require can indeed do that for you. But there are also many other, potentially more flexible options that accomplish the same thing. And Angular 2.0 will apparently take care of this for us, built-in to the router. (Details.)

But what about during development on my local dev boxen?

How can I get all my dozens/hundreds of script files loaded without needing to attach them all to index.html manually?

Have a look at the sub-generators in Yeoman's generator-angular, or at the automation patterns embodied in generator-gulp-angular, or at the standard Webpack automation for React. These provide you a clean, scalable way to either: automatically attach the files at the time that components are scaffolded, or to simply grab them all automatically if they are present in certain folders/match certain glob-patterns. You never again need to think about your own script-loading once you've got the latter options.

Bottom-line?

Require is a great tool, for certain things. But go with the grain whenever possible, and separate your concerns whenever possible. Let Angular worry about Angular's own modularization pattern, and consider using ES6 modules or CommonJS as a general modularization pattern. Let modern automation tools worry about script-loading and dependency-management. And take care of async lazy-loading in a granular way, rather than by tangling it up with the other two concerns.

That said, if you're developing Angular apps but can't install Node on your machine to use Javascript automation tools for some reason, then Require may be a good alternate solution. And I've seen really elaborate setups where people want to dynamically load Angular components that each declare their own dependencies or something. And while I'd probably try to solve that problem another way, I can see the merits of the idea, for that very particular situation.

But otherwise... when starting from scratch with a new Angular application and flexibility to create a modern automation environment... you've got a lot of other, more flexible, more modern options.

(Updated repeatedly to keep up with the evolving JS scene.)

How to asynchronously call a method in Java

You can use @Async annotation from jcabi-aspects and AspectJ:

public class Foo {
  @Async
  public void save() {
    // to be executed in the background
  }
}

When you call save(), a new thread starts and executes its body. Your main thread continues without waiting for the result of save().

Access is denied when attaching a database

Copy Database to an other folder and attach or Log in SQLServer with "Windows Authentication"

enter image description here

Date minus 1 year?

You can use strtotime:

$date = strtotime('2010-01-01 -1 year');

The strtotime function returns a unix timestamp, to get a formatted string you can use date:

echo date('Y-m-d', $date); // echoes '2009-01-01'

How to start new activity on button click

Emmanuel,

I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);

myIntent.putExtra("key", value);

CurrentActivity.this.startActivity(myIntent);

MySQL Trigger: Delete From Table AFTER DELETE

create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;

How to pick a new color for each plotted line within a figure in matplotlib?

You can use a predefined "qualitative colormap" like this:

from matplotlib.cm import get_cmap

name = "Accent"
cmap = get_cmap(name)  # type: matplotlib.colors.ListedColormap
colors = cmap.colors  # type: list
axes.set_prop_cycle(color=colors)

Tested on matplotlib 3.0.3. See https://github.com/matplotlib/matplotlib/issues/10840 for discussion on why you can't call axes.set_prop_cycle(color=cmap).

A list of predefined qualititative colormaps is available at https://matplotlib.org/gallery/color/colormap_reference.html :

List of qualitative colormaps

Why std::cout instead of simply cout?

It seems possible your class may have been using pre-standard C++. An easy way to tell, is to look at your old programs and check, do you see:

#include <iostream.h>

or

#include <iostream>

The former is pre-standard, and you'll be able to just say cout as opposed to std::cout without anything additional. You can get the same behavior in standard C++ by adding

using std::cout;

or

using namespace std;

Just one idea, anyway.

how to instanceof List<MyType>?

This could be used if you want to check that object is instance of List<T>, which is not empty:

if(object instanceof List){
    if(((List)object).size()>0 && (((List)object).get(0) instanceof MyObject)){
        // The object is of List<MyObject> and is not empty. Do something with it.
    }
}

Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

I found another handy solution, which avoids rebuilding all components again and again, in this article: http://bitstopixels.blogspot.ca/2017/04/react-native-windows-10-eperm-operation.html

  1. Execute react-native run-android
  2. As soon as React Packager window opens, close it
  3. Wait for react-native run-android to complete giving you the BUILD SUCCESSFUL message. (The app will be launched with a red error screen complaining connecting to server failed. Don't panic.)
  4. Then run react-native start to start the React Packager, this is the server indicated in the error message of the previous step
  5. Reload the app in emulator or device (Double tap the R key)

TypeScript or JavaScript type casting

You can cast like this:

return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);

Or like this if you want to be compatible with tsx mode:

return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);

Just remember that this is a compile-time cast, and not a runtime cast.

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Remember that you will need to connect to running docker container. So you probably want to use tcp instead of unix socket. Check output of docker ps command and look for running mysql containers. If you find one then use mysql command like this: mysql -h 127.0.0.1 -P <mysql_port> (you will find port in docker ps output). If you can't find any running mysql container in docker ps output then try docker images to find mysql image name and try something like this to run it: docker run -d -p 3306:3306 tutum/mysql where "tutum/mysql" is image name found in docker images.

Escape quotes in JavaScript

<html>
    <body>
        <a href="#" onclick="DoEdit('Preliminary Assessment &quot;Mini&quot;'); return false;">edit</a>
    </body>
</html>

Should do the trick.

Determining image file size + dimensions via Javascript?

Most folks have answered how a downloaded image's dimensions can be known so I'll just try to answer other part of the question - knowing downloaded image's file-size.

You can do this using resource timing api. Very specifically transferSize, encodedBodySize and decodedBodySize properties can be used for the purpose.

Check out my answer here for code snippet and more information if you seek : JavaScript - Get size in bytes from HTML img src

How to keep the spaces at the end and/or at the beginning of a String?

use "" with the string resource value.

Example :

<string>"value with spaces"</string>

OR

use \u0020 code for spaces.

Passive Link in Angular 2 - <a href=""> equivalent

you need to prevent event's default behaviour as follows.

In html

<a href="" (click)="view($event)">view</a>

In ts file

view(event:Event){
 event.preventDefault();
 //remaining code goes here..
}

BLOB to String, SQL Server

Problem was apparently not the SQL server, but the NAV system that updates the field. There is a compression property that can be used on BLOB fields in NAV, that is not a part of SQL Server. So the custom compression made the data unreadable, though the conversion worked.

The solution was to turn off compression through the Object Designer, Table Designer, Properties for the field (Shift+F4 on the field row).

After that the extraction of data can be made with e.g.: select convert(varchar(max), cast(BLOBFIELD as binary)) from Table

Thanks for all answers that were correct in many ways!

Insert a row to pandas dataframe

this might seem overly simple but its incredible that a simple insert new row function isn't built in. i've read a lot about appending a new df to the original, but i'm wondering if this would be faster.

df.loc[0] = [row1data, blah...]
i = len(df) + 1
df.loc[i] = [row2data, blah...]

How to center HTML5 Videos?

I will not prefer to center just using video tag as @user142019 says. I will prefer doing it like this:

_x000D_
_x000D_
.videoDiv_x000D_
{_x000D_
    width: 70%; /*or whatever % you prefer*/_x000D_
    margin: 0 auto;_x000D_
    display: block;_x000D_
}
_x000D_
<div class="videoDiv">_x000D_
  <video width="100%" controls>_x000D_
    <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">_x000D_
    <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">_x000D_
  Your browser does not support the video tag._x000D_
  </video>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will make your video responsive at the same time the panel for controls will have the same size as the video rectangle (I tried what @user142019 says and the video was centered, but it looked ugly in Google Chrome).

Where is Maven Installed on Ubuntu

$ mvn --version

and look for Maven home: in the output , mine is: Maven home: /usr/share/maven

How to create a self-signed certificate for a domain name for development?

Another option is to create a self-signed certificate that allows you to specify the domain name per website. This means you can use it across many domain names.

In IIS Manager

  1. Click machine name node
  2. Open Server Certificates
  3. In Actions panel, choose 'Create Self-Signed Certificate'
  4. In 'Specify a friendly name...' name it *Dev (select 'Personal' from type list)
  5. Save

Now, on your website in IIS...

  1. Manage the bindings
  2. Create a new binding for Https
  3. Choose your self-signed certificate from the list
  4. Once selected, the domain name box will become enabled and you'll be able to input your domain name.

enter image description here

Create numpy matrix filled with NaNs

Another option is to use numpy.full, an option available in NumPy 1.8+

a = np.full([height, width, 9], np.nan)

This is pretty flexible and you can fill it with any other number that you want.

How do I use this JavaScript variable in HTML?

A good place to start learning how to manipulate pages s the Mozilla Developer Network, they've got a great tutorial about the DOM.

One way you could do it is with document.write, which writes html at the end of the currently loaded part of the document - in this case, after the script tag.

<script>
  var name = prompt("What's your name?");
  document.write("<p>" + name.length + "</p>");
</script>

But it's not a very clean way of doing it. Keep document.write for testing purpose because in most cases you can't predict where it will append the content.

EDIT: Here, the "clever" way would be to do something like this:

<script type="text/javascript">
  window.addEventListener("load", function(e) {
    var name = prompt("What's your name?") || "";
    var text = document.createTextNode(name.length);
    document.getElementById("nameLength").appendChild(text);
  });
</script>
<p id="nameLength"></p>

But people are generally lazy and you'll often see .innerHTML = "something" instead of a text node.

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

CSS content property: is it possible to insert HTML instead of Text?

It is not possible prolly cuz it would be so easy to XSS. Also , current HTML sanitizers that are available don't disallow content property.

(Definitely not the greatest answer here but I just wanted to share an insight other than the "according to spec... ")

Text File Parsing in Java

It sounds like you currently have 3 copies of the entire file in memory: the byte array, the string, and the array of the lines.

Instead of reading the bytes into a byte array and then converting to characters using new String() it would be better to use an InputStreamReader, which will convert to characters incrementally, rather than all up-front.

Also, instead of using String.split("\n") to get the individual lines, you should read one line at a time. You can use the readLine() method in BufferedReader.

Try something like this:

BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
try {
  while (true) {
    String line = reader.readLine();
    if (line == null) break;
    String[] fields = line.split(",");
    // process fields here
  }
} finally {
  reader.close();
}

A completely free agile software process tool

You can check out https://kanbanflow.com It's free for now because it's in beta and they say there is no time limit. It behaves very similar to AgileZen

I second the google doc, or you could use an online collaborative board that multiple people can edit.

Or you can host a more robust excel doc in skydrive from MS. I haven't tried that yet.

Mura.ly is another one that I am playing with currently. It has unlimited collaborators, though I think you would probably have to invite them everytime?? with a free account.

Hope that helps!

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

You can achieve what you want by using @RequestParam. For this you should do the following:

  1. Declare the RequestParams parameters that represent your objects and set the required option to false if you want to be able to send a null value.
  2. On the frontend, stringify the objects that you want to send and include them as request parameters.
  3. On the backend turn the JSON strings back into the objects they represent using Jackson ObjectMapper or something like that, and voila!

I know, its a bit of a hack but it works! ;)

Java array assignment (multiple values)

for example i tried all above for characters it fails but that worked for me >> reserved a pointer then assign values

char A[];
A = new char[]{'a', 'b', 'a', 'c', 'd', 'd', 'e', 'f', 'q', 'r'};

Ajax Upload image

Here is simple way using HTML5 and jQuery:

1) include two JS file

<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>

2) include CSS to have cool buttons

<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />

3) create DIV or SPAN

<div class="demo" > </div>

4) write this code in your HTML page

$('.demo').ajaxupload({
    url:'upload.php'
});

5) create you upload.php file to have PHP code to upload data.

You can download required JS file from here Here is Example

Its too cool and too fast And easy too! :)

How to generate classes from wsdl using Maven and wsimport?

I see some people prefer to generate sources into the target via jaxws-maven-plugin AND make this classes visible in source via build-helper-maven-plugin. As an argument for this structure

the version management system (svn/etc.) would always notice changed sources

With git it is not true. So you can just configure jaxws-maven-plugin to put them into your sources, but not under the target folder. Next time you build your project, git will not mark these generated files as changed. Here is the simple solution with only one plugin:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxws-maven-plugin</artifactId>
        <version>2.6</version>

    <dependencies>
      <dependency>
        <groupId>org.jvnet.jaxb2_commons</groupId>
        <artifactId>jaxb2-fluent-api</artifactId>
        <version>3.0</version>
      </dependency>
      <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-tools</artifactId>
        <version>2.3.0</version>
      </dependency>
    </dependencies>

    <executions>
      <execution>
        <goals>
          <goal>wsimport</goal>
        </goals>
        <configuration>
          <packageName>som.path.generated</packageName>
          <xjcArgs>
            <xjcArg>-Xfluent-api</xjcArg>
          </xjcArgs>
          <verbose>true</verbose>
          <keep>true</keep> <!--used by default-->
          <sourceDestDir>${project.build.sourceDirectory}</sourceDestDir>
          <wsdlDirectory>src/main/resources/META-INF/wsdl</wsdlDirectory>
          <wsdlLocation>META-INF/wsdl/soap.wsdl</wsdlLocation>
        </configuration>
      </execution>
    </executions>
  </plugin>

Additionally (just to note) in this example SOAP classes are generated with Fluent API, so you can create them like:

A a = new A()
  .withField1(value1)
  .withField2(value2);

What does -> mean in Python function definitions?

def f(x) -> str:
return x+4

print(f(45))

# will give the result : 
49

# or with other words '-> str' has NO effect to return type:

print(f(45).__class__)

<class 'int'>

How do you remove a Cookie in a Java Servlet

The proper way to remove a cookie is to set the max age to 0 and add the cookie back to the HttpServletResponse object.

Most people don't realize or forget to add the cookie back onto the response object. By doing that it will expire and remove the cookie immediately.

...retrieve cookie from HttpServletRequest
cookie.setMaxAge(0);
response.addCookie(cookie);

How to find out when an Oracle table was updated the last time

If any one is still looking for an answer they can use Oracle Database Change Notification feature coming with Oracle 10g. It requires CHANGE NOTIFICATION system privilege. You can register listeners when to trigger a notification back to the application.

How to set selected value from Combobox?

Try this:

KeyValuePair<string, string> pair = (KeyValuePair<string,string>)this.ComboBox.SelectedItem;

Regex for allowing alphanumeric,-,_ and space

For me I wanted a regex which supports a strings as preceding. Basically, the motive is to support some foreign countries postal format as it should be an alphanumeric with spaces allowed.

  1. ABC123
  2. ABC 123
  3. ABC123(space)
  4. ABC 123 (space)

So I ended up by writing custom regex as below.

/^([a-z]+[\s]*[0-9]+[\s]*)+$/i

enter image description here

Here, I gave * in [\s]* as it is not mandatory to have a space. A postal code may or may not contains space in my case.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml

if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven