Programs & Examples On #Mvvm toolkit

Force add despite the .gitignore file

Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel

Using boolean values in C

Here is the version that I used:

typedef enum { false = 0, true = !false } bool;

Because false only has one value, but a logical true could have many values, but technique sets true to be what the compiler will use for the opposite of false.

This takes care of the problem of someone coding something that would come down to this:

if (true == !false)

I think we would all agree that that is not a good practice, but for the one time cost of doing "true = !false" we eliminate that problem.

[EDIT] In the end I used:

typedef enum { myfalse = 0, mytrue = !myfalse } mybool;

to avoid name collision with other schemes that were defining true and false. But the concept remains the same.

[EDIT] To show conversion of integer to boolean:

mybool somebool;
int someint = 5;
somebool = !!someint;

The first (right most) ! converts the non-zero integer to a 0, then the second (left most) ! converts the 0 to a myfalse value. I will leave it as an exercise for the reader to convert a zero integer.

[EDIT] It is my style to use the explicit setting of a value in an enum when the specific value is required even if the default value would be the same. Example: Because false needs to be zero I use false = 0, rather than false,

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Kotlin:

var ver: String = packageManager.getPackageInfo(packageName, 0).versionName

How to get the server path to the web directory in Symfony2 from inside the controller?

There's actually no direct way to get path to webdir in Symfony2 as the framework is completely independent of the webdir.

You can use getRootDir() on instance of kernel class, just as you write. If you consider renaming /web dir in future, you should make it configurable. For example AsseticBundle has such an option in its DI configuration (see here and here).

Extract a substring using PowerShell

The Substring method provides us a way to extract a particular string from the original string based on a starting position and length. If only one argument is provided, it is taken to be the starting position, and the remainder of the string is outputted.

PS > "test_string".Substring(0,4)
Test
PS > "test_string".Substring(4)
_stringPS >

link text

But this is easier...

 $s = 'Hello World is in here Hello World!'
 $p = 'Hello World'
 $s -match $p

And finally, to recurse through a directory selecting only the .txt files and searching for occurrence of "Hello World":

dir -rec -filter *.txt | Select-String 'Hello World'

How to reference a local XML Schema file correctly?

Add one more slash after file:// in the value of xsi:schemaLocation. (You have two; you need three. Think protocol://host/path where protocol is 'file' and host is empty here, yielding three slashes in a row.) You can also eliminate the double slashes along the path. I believe that the double slashes help with file systems that allow spaces in file and directory names, but you wisely avoided that complication in your path naming.

xsi:schemaLocation="http://www.w3schools.com file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd"

Still not working? I suggest that you carefully copy the full file specification for the XSD into the address bar of Chrome or Firefox:

file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd

If the XSD does not display in the browser, delete all but the last component of the path (email.xsd) and see if you can't display the parent directory. Continue in this manner, walking up the directory structure until you discover where the path diverges from the reality of your local filesystem.

If the XSD does displayed in the browser, state what XML processor you're using, and be prepared to hear that it's broken or that you must work around some limitation. I can tell you that the above fix will work with my Xerces-J-based validator.

How do I assign ls to an array in Linux Bash?

Whenever possible, you should avoid parsing the output of ls (see Greg's wiki on the subject). Basically, the output of ls will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */, what happens is that the shell expands */ to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls command isn't doing anything useful!

Well, ok, it is doing one thing that's useful: if there are no subdirectories, */ will get left as is, ls will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).

The cleaner way to make an array of subdirectory names is to use the glob (*/) without passing it to ls. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):

shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}"  # Note double-quotes to avoid extra parsing of funny characters in filenames

If you want to print an error message if there are no subdirectories, you're better off doing it yourself:

if (( ${#array[@]} == 0 )); then
    echo "No subdirectories found" >&2
fi

What is the reason for a red exclamation mark next to my project in Eclipse?

Mark Circular dependcies as "Warning" in Eclipse tool to avoid "A CYCLE WAS DETECTED IN THE BUILD PATH" error. In Eclipse got to :-> Windows -> Prefereneces -> Java-> Compiler -> Buliding -> Circular Depencies

Thanks

How to find out if a Python object is a string?

Python 2 and 3

(cross-compatible)

If you want to check with no regard for Python version (2.x vs 3.x), use six (PyPI) and its string_types attribute:

import six

if isinstance(obj, six.string_types):
    print('obj is a string!')

Within six (a very light-weight single-file module), it's simply doing this:

import sys
PY3 = sys.version_info[0] == 3

if PY3:
    string_types = str
else:
    string_types = basestring

How to get query params from url in Angular 2?

You cannot get a parameter from the RouterState if it's not defined in the route, so in your example, you have to parse the querystring...

Here is the code I used:

_x000D_
_x000D_
let re = /[?&]([^=#&]+)=([^&#]*)/g;_x000D_
let match;_x000D_
let isMatch = true;_x000D_
let matches = [];_x000D_
while (isMatch) {_x000D_
    match = re.exec(window.location.href);_x000D_
    if (match !== null) {_x000D_
        matches[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);_x000D_
        if (match.index === re.lastIndex) {_x000D_
            re.lastIndex++;_x000D_
        }_x000D_
    }_x000D_
    else {_x000D_
        isMatch = false;_x000D_
    }_x000D_
}_x000D_
console.log(matches);
_x000D_
_x000D_
_x000D_

How can jQuery deferred be used?

1) Use it to ensure an ordered execution of callbacks:

var step1 = new Deferred();
var step2 = new Deferred().done(function() { return step1 });
var step3 = new Deferred().done(function() { return step2 });

step1.done(function() { alert("Step 1") });
step2.done(function() { alert("Step 2") });
step3.done(function() { alert("All done") });
//now the 3 alerts will also be fired in order of 1,2,3
//no matter which Deferred gets resolved first.

step2.resolve();
step3.resolve();
step1.resolve();

2) Use it to verify the status of the app:

var loggedIn = logUserInNow(); //deferred
var databaseReady = openDatabaseNow(); //deferred

jQuery.when(loggedIn, databaseReady).then(function() {
  //do something
});

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

Declare an array in TypeScript

Few ways of declaring a typed array in TypeScript are

const booleans: Array<boolean> = new Array<boolean>();
// OR, JS like type and initialization
const booleans: boolean[] = [];

// or, if you have values to initialize 
const booleans: Array<boolean> = [true, false, true];
// get a vaue from that array normally
const valFalse = booleans[1];

How get permission for camera in android.(Specifically Marshmallow)

First check if the user has granted the permission:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
    == PackageManager.PERMISSION_DENIED)

Then, you could use this to request to the user:

ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);

And in Marshmallow, it will appear in a dialog

How to define servlet filter order of execution using annotations in WAR

You can indeed not define the filter execution order using @WebFilter annotation. However, to minimize the web.xml usage, it's sufficient to annotate all filters with just a filterName so that you don't need the <filter> definition, but just a <filter-mapping> definition in the desired order.

For example,

@WebFilter(filterName="filter1")
public class Filter1 implements Filter {}

@WebFilter(filterName="filter2")
public class Filter2 implements Filter {}

with in web.xml just this:

<filter-mapping>
    <filter-name>filter1</filter-name>
    <url-pattern>/url1/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>filter2</filter-name>
    <url-pattern>/url2/*</url-pattern>
</filter-mapping>

If you'd like to keep the URL pattern in @WebFilter, then you can just do like so,

@WebFilter(filterName="filter1", urlPatterns="/url1/*")
public class Filter1 implements Filter {}

@WebFilter(filterName="filter2", urlPatterns="/url2/*")
public class Filter2 implements Filter {}

but you should still keep the <url-pattern> in web.xml, because it's required as per XSD, although it can be empty:

<filter-mapping>
    <filter-name>filter1</filter-name>
    <url-pattern />
</filter-mapping>
<filter-mapping>
    <filter-name>filter2</filter-name>
    <url-pattern />
</filter-mapping>

Regardless of the approach, this all will fail in Tomcat until version 7.0.28 because it chokes on presence of <filter-mapping> without <filter>. See also Using Tomcat, @WebFilter doesn't work with <filter-mapping> inside web.xml

ERROR 1049 (42000): Unknown database 'mydatabasename'

Whatever the name of your dump file, it's the content which does matter.

You need to check your mydatabase.sql and find this line :

USE mydatabasename;

This name does matter, and it's the one you must use in your command :

mysql -uroot -pmypassword mydatabasename<mydatabase.sql;

Two options for you :

  1. Remove USE mydatabasename; in your dump, and keep using :
    mysql -uroot -pmypassword mydatabase<mydatabase.sql;
  2. Change your local database name to fit the one in your SQL dump, and use :
    mysql -uroot -pmypassword mydatabasename<mydatabase.sql;

Converting a Pandas GroupBy output from Series to DataFrame

Maybe I misunderstand the question but if you want to convert the groupby back to a dataframe you can use .to_frame(). I wanted to reset the index when I did this so I included that part as well.

example code unrelated to question

df = df['TIME'].groupby(df['Name']).min()
df = df.to_frame()
df = df.reset_index(level=['Name',"TIME"])

Log all queries in mysql

Besides what I came across here, running the following was the simplest way to dump queries to a log file without restarting

SET global log_output = 'FILE';
SET global general_log_file='/Applications/MAMP/logs/mysql_general.log';
SET global general_log = 1;

can be turned off with

SET global general_log = 0;

MySQL show current connection info

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

Could not insert new outlet connection: Could not find any information for the class named

Or if none of the above works, type out the name of the outlet into the file first @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! and then click and drag from the outlet in the nib to the variable you just programmatically created. It should work without any of the hassle of cleaning, building, and deleting anything.

File.Move Does Not Work - File Already Exists

Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.

python ValueError: invalid literal for float()

Watch out for possible unintended literals in your argument

for example you can have a space within your argument, rendering it to a string / literal:

float(' 0.33')

After making sure the unintended space did not make it into the argument, I was left with:

float(0.33) 

Like this it works like a charm.

Take away is: Pay Attention for unintended literals (e.g. spaces that you didn't see) within your input.

Plot yerr/xerr as shaded region rather than error bars

Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

enter image description here

See also the matplotlib examples.

Does C# have extension properties?

Update (thanks to @chaost for pointing this update out):

Mads Torgersen: "Extension everything didn’t make it into C# 8.0. It got “caught up”, if you will, in a very exciting debate about the further future of the language, and now we want to make sure we don’t add it in a way that inhibits those future possibilities. Sometimes language design is a very long game!"

Source: comments section in https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/


I stopped counting how many times over the years I opened this question with hopes to have seen this implemented.

Well, finally we can all rejoice! Microsoft is going to introduce this in their upcoming C# 8 release.

So instead of doing this...

public static class IntExtensions
{
   public static bool Even(this int value)
   {
        return value % 2 == 0;
   }
}

We'll be finally able to do it like so...

public extension IntExtension extends int
{
    public bool Even => this % 2 == 0;
}

Source: https://blog.ndepend.com/c-8-0-features-glimpse-future/

How to add composite primary key to table

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

Rename computer and join to domain in one step with PowerShell

As nobody answer, I try something :

I think I understand why Attent one does not work. It's because joining a computer to a domain is somehow also renaming the computer (the domain name part, enter in the name of the machine).

So do you try to do it in full WMI way, you've got a method in Win32_ComputerSystem class called JoinDomainOrWorkgroup. Doing it on the same level perhaps gives you more chance to make it work.

OpenCV !_src.empty() in function 'cvtColor' error

In my case, the image was incorrectly named. Check if the image exists and try

import numpy as np
import cv2

img = cv2.imread('image.png', 0)
cv2.imshow('image', img)

Using an authorization header with Fetch in React Native

completed = (id) => {
    var details = {
        'id': id,

    };

    var formBody = [];
    for (var property in details) {
        var encodedKey = encodeURIComponent(property);
        var encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    fetch(markcompleted, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formBody
    })
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson, 'res JSON');
            if (responseJson.status == "success") {
                console.log(this.state);
                alert("your todolist is completed!!");
            }
        })
        .catch((error) => {
            console.error(error);
        });
};

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

Whether or not the "date" '0000-00-00" is a valid "date" is irrelevant to the question. "Just change the database" is seldom a viable solution.

Facts:

  • MySQL allows a date with the value of zeros.
  • This "feature" enjoys widespread use with other languages.

So, if I "just change the database", thousands of lines of PHP code will break.

Java programmers need to accept the MySQL zero-date and they need to put a zero date back into the database, when other languages rely on this "feature".

A programmer connecting to MySQL needs to handle null and 0000-00-00 as well as valid dates. Changing 0000-00-00 to null is not a viable option, because then you can no longer determine if the date was expected to be 0000-00-00 for writing back to the database.

For 0000-00-00, I suggest checking the date value as a string, then changing it to ("y",1), or ("yyyy-MM-dd",0001-01-01), or into any invalid MySQL date (less than year 1000, iirc). MySQL has another "feature": low dates are automatically converted to 0000-00-00.

I realize my suggestion is a kludge. But so is MySQL's date handling. And two kludges don't make it right. The fact of the matter is, many programmers will have to handle MySQL zero-dates forever.

Edit a commit message in SourceTree Windows (already pushed to remote)

Here are the steps to edit the commit message of a previous commit (which is not the most recent commit) using SourceTree for Windows version 1.5.2.0:

Step 1

Select the commit immediately before the commit that you want to edit. For example, if I want to edit the commit with message "FOOBAR!" then I need to select the commit that comes right before it:

Selecting commit before the one that I want to edit.

Step 2

Right-click on the selected commit and click Rebase children...interactively:

Selecting "Rebase children interactively".

Step 3

Select the commit that you want to edit, then click Edit Message at the bottom. In this case, I'm selecting the commit with the message "FOOBAR!":

Select the commit that you want to edit.

Step 4

Edit the commit message, and then click OK. In my example, I've added "SHAZBOT! SKADOOSH!"

Edit the commit message

Step 5

When you return to interactive rebase window, click on OK to finish the rebase:

Click OK to finish.

Step 6

At this point, you'll need to force-push your new changes since you've rebased commits that you've already pushed. However, the current 1.5.2.0 version of SourceTree for Windows does not allow you to force-push through the GUI, so you'll need to use Git from the command line anyways in order to do that.

Click Terminal from the GUI to open up a terminal.

Click Terminal

Step 7

From the terminal force-push with the following command,

git push origin <branch> -f

where <branch> is the name of the branch that you want to push, and -f means to force the push. The force push will overwrite your commits on your remote repo, but that's OK in your case since you said that you're not sharing your repo with other people.

That's it! You're done!

Show pop-ups the most elegant way

It's funny because I'm learning Angular myself and was watching some video's from their channel on Youtube. The speaker mentions your exact problem in this video https://www.youtube.com/watch?v=ZhfUv0spHCY#t=1681 around the 28:30 minute mark.

It comes down to placing that particular piece of code in a service rather then a controller.

My guess would be to inject new popup elements into the DOM and handle them separate instead of showing and hiding the same element. This way you can have multiple popups.

The whole video is very interesting to watch as well :-)

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

How do I loop through or enumerate a JavaScript object?

for(key in p) {
  alert( p[key] );
}

Note: you can do this over arrays, but you'll iterate over the length and other properties, too.

How to get Current Directory?

WCHAR path[MAX_PATH] = {0};
GetModuleFileName(NULL, path, MAX_PATH);
PathRemoveFileSpec(path);

get the latest fragment in backstack

There is a list of fragments in the fragmentMananger. Be aware that removing a fragment, does not make the list size decrease (the fragment entry just turn to null). Therefore, a valid solution would be:

public Fragment getTopFragment() {
 List<Fragment> fragentList = fragmentManager.getFragments();
 Fragment top = null;
  for (int i = fragentList.size() -1; i>=0 ; i--) {
   top = (Fragment) fragentList.get(i);
     if (top != null) {
       return top;
     }
   }
 return top;
}

How can I match a string with a regex in Bash?

if [[ $STR == *pattern* ]]
then
    echo "It is the string!"
else
    echo "It's not him!"
fi

Works for me! GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

Any way to write a Windows .bat file to kill processes?

taskkill /f /im "devenv.exe"

this will forcibly kill the pid with the exe name "devenv.exe"

equivalent to -9 on the nix'y kill command

javascript push multidimensional array

In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.

Instead, declare valueToPush as an object and push that onto cookie_value_add:

// Create valueToPush as an object {} rather than an array []
var valueToPush = {};

// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;

cookie_value_add.push(valueToPush);

// View the structure of cookie_value_add
console.dir(cookie_value_add);

FULL OUTER JOIN vs. FULL JOIN

Actually they are the same. LEFT OUTER JOIN is same as LEFT JOIN and RIGHT OUTER JOIN is same as RIGHT JOIN. It is more informative way to compare from INNER Join.

See this Wikipedia article for details.

How to format x-axis time scale values in Chart.js v2

I had a different use case, I want different formats based how long between start and end time of data in graph. I found this to be simplest approach

    xAxes = {
        type: "time",
        time: {
            displayFormats: {
                hour: "hA"
            }
        },
        display: true,
        ticks: {
            reverse: true
        },
        gridLines: {display: false}
    }
    // if more than two days between start and end of data,  set format to show date,  not hrs
    if ((parseInt(Cookies.get("epoch_max")) - parseInt(Cookies.get("epoch_min"))) > (1000*60*60*24*2)) {
        xAxes.time.displayFormats.hour = "MMM D";
    }

How to get the ActionBar height?

The action bar height differs according to the applied theme. If you're using AppCompatActivity the height will be different in most of cases from the normal Activity.

If you're using AppCompatActivity you should use R.attr.actionBarSize instead of android.R.attr.actionBarSize

public static int getActionBarHeight(Activity activity) {
        TypedValue typedValue = new TypedValue();

        int attributeResourceId = android.R.attr.actionBarSize;
        if (activity instanceof AppCompatActivity) {
            attributeResourceId = R.attr.actionBarSize;
        }

        if (activity.getTheme().resolveAttribute(attributeResourceId, typedValue, true)) {
            return TypedValue.complexToDimensionPixelSize(typedValue.data, activity.getResources().getDisplayMetrics());
        }

        return (int) Math.floor(activity.getResources()
                .getDimension(R.dimen.my_default_value));
    }

Java Try Catch Finally blocks without Catch

A small note on try/finally: The finally will always execute unless

  • System.exit() is called.
  • The JVM crashes.
  • The try{} block never ends (e.g. endless loop).

SQL Server convert string to datetime

For instance you can use

update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'

You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.

Java get String CompareTo as a comparator object

Again, don't need the comparator for Arrays.binarySearch(Object[] a, Object key) so long as the types of objects are comparable, but with lambda expressions this is now way easier.

Simply replace the comparator with the method reference: String::compareTo

E.g.:

Arrays.binarySearch(someStringArray, "The String to find.", String::compareTo);

You could also use

Arrays.binarySearch(someStringArray, "The String to find.", (a,b) -> a.compareTo(b));

but even before lambdas, there were always anonymous classes:

Arrays.binarySearch(
                someStringArray,
                "The String to find.",
                new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        return o1.compareTo(o2);
                    }
                });

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Make sure you open the .xcworkspace file not the project file from xCode Project menu when working with pods. That should solve the issue with linking.

"CAUTION: provisional headers are shown" in Chrome debugger

I got this error when I tried to print a page in a popup. The print dialog was show and it still waiting my acceptance or cancellation of the printing in the popup while in the master page also was waiting in the background showing the message CAUTION provisional headers are shown when I tried to click another link.

In my case the solution was to remove the window.print (); script that it was executing on the <body> of the popup window to prevent the print dialog.

window.open with target "_blank" in Chrome

You can't do it because you can't have control on the manner Chrome opens its windows

How can I test an AngularJS service from the console?

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

Read Variable from Web.Config

Given the following web.config:

<appSettings>
     <add key="ClientId" value="127605460617602"/>
     <add key="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/>
</appSettings>

Example usage:

using System.Configuration;

string clientId = ConfigurationManager.AppSettings["ClientId"];
string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];

Generating matplotlib graphs without a running X server

@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg') before importing matplotlib.pyplot, and then continue as normal.

E.g.

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')

You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.

Alternately, you can just set the backend parameter in your .matplotlibrc file to automatically have matplotlib.pyplot use the given renderer.

What is the difference between java and core java?

I think when you see the phrase "core Java," they are talking about the basics of the language and maybe some knowledge of Java SE. I don't know why they would bother to put the "core" on there.

Best way to check if a character array is empty

This will work to find if a character array is empty. It probably is also the fastest.

if(text[0] == '\0') {}

This will also be fast if the text array is empty. If it contains characters it needs to count all the characters in it first.

if(strlen(text) == 0) {}

How to negate the whole regex?

\b(?=\w)(?!(ma|(t){1}))\b(\w*)

this is for the given regex.
the \b is to find word boundary.
the positive look ahead (?=\w) is here to avoid spaces.
the negative look ahead over the original regex is to prevent matches of it.
and finally the (\w*) is to catch all the words that are left.
the group that will hold the words is group 3.
the simple (?!pattern) will not work as any sub-string will match
the simple ^(?!(?:m{2}|t)$).*$ will not work as it's granularity is full lines

get number of columns of a particular row in given excel using Java

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

How do you log all events fired by an element in jQuery?

I have no idea why no-one uses this... (maybe because it's only a webkit thing)

Open console:

monitorEvents(document.body); // logs all events on the body

monitorEvents(document.body, 'mouse'); // logs mouse events on the body

monitorEvents(document.body.querySelectorAll('input')); // logs all events on inputs

How can I define colors as variables in CSS?

dicejs.com (formally cssobjs) is a client-side version of SASS. You can set variables in your CSS (stored in json formatted CSS) and re-use your color variables.

//create the CSS JSON object with variables and styles
var myCSSObjs = {
  cssVariables : {
    primaryColor:'#FF0000',
    padSmall:'5px',
    padLarge:'$expr($padSmall * 2)'
  }
  'body' : {padding:'$padLarge'},
  'h1' : {margin:'0', padding:'0 0 $padSmall 0'},
  '.pretty' : {padding:'$padSmall', margin:'$padSmall', color:'$primaryColor'}
};

//give your css objects a name and inject them
$.cssObjs('myStyles',myCSSObjs).injectStyles();

And here is a link to a complete downloadable demo which is a little more helpful then their documentation : dicejs demo

Bad operand type for unary +: 'str'

The code works for me. (after adding missing except clause / import statements)

Did you put \ in the original code?

urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
              + stock + '/chartdata;type=quote;range=5d/csv'

If you omit it, it could be a cause of the exception:

>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

BTW, string(e) should be str(e).

Compute mean and standard deviation by group for multiple variables in a data.frame

Here is probably the simplest way to go about it (with a reproducible example):

library(plyr)
df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))
ddply(df, .(ID), summarize, Obs_1_mean=mean(Obs_1), Obs_1_std_dev=sd(Obs_1),
  Obs_2_mean=mean(Obs_2), Obs_2_std_dev=sd(Obs_2))

   ID  Obs_1_mean Obs_1_std_dev  Obs_2_mean Obs_2_std_dev
1  1 -0.13994642     0.8258445 -0.15186380     0.4251405
2  2  1.49982393     0.2282299  0.50816036     0.5812907
3  3 -0.09269806     0.6115075 -0.01943867     1.3348792

EDIT: The following approach saves you a lot of typing when dealing with many columns.

ddply(df, .(ID), colwise(mean))

  ID      Obs_1      Obs_2      Obs_3
1  1 -0.3748831  0.1787371  1.0749142
2  2 -1.0363973  0.0157575 -0.8826969
3  3  1.0721708 -1.1339571 -0.5983944

ddply(df, .(ID), colwise(sd))

  ID     Obs_1     Obs_2     Obs_3
1  1 0.8732498 0.4853133 0.5945867
2  2 0.2978193 1.0451626 0.5235572
3  3 0.4796820 0.7563216 1.4404602

Google Maps API v3: How to remove all markers?

It seems that there is no such function in V3 yet.

People suggest to keep references to all markers you have on the map in an array. And then when you want to delete em all, just loop trough the array and call .setMap(null) method on each of the references.

See this question for more info/code.

My version:

google.maps.Map.prototype.markers = new Array();

google.maps.Map.prototype.getMarkers = function() {
    return this.markers
};

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i<this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};

google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;

google.maps.Marker.prototype.setMap = function(map) {
    if (map) {
        map.markers[map.markers.length] = this;
    }
    this._setMap(map);
}

The code is edited version of this code http://www.lootogo.com/googlemapsapi3/markerPlugin.html I removed the need to call addMarker manually.

Pros

  • Doing this way you keep the code compact and in one place (doesn't pollute the namespace).
  • You don't have to keep track of the markers yourself anymore you can always find all the markers on the map by calling map.getMarkers()

Cons

  • Using prototypes and wrappers like I did now makes my code dependent on Google code, if they make a mayor change in their source this will break.
  • If you don't understand it then you won't be able to fix it if does break. The chances are low that they're going to change anything which will break this, but still..
  • If you remove one marker manually, it's reference will still be in markers array. (You could edit my setMap method to fix it, but at the cost of looping trough markers array and removing the reference)

Datatable select with multiple conditions

Do you have to use DataTable.Select()? I prefer to write a linq query for this kind of thing.

var dValue=  from row in myDataTable.AsEnumerable()
             where row.Field<int>("A") == 1 
                   && row.Field<int>("B") == 2 
                   && row.Field<int>("C") == 3
             select row.Field<string>("D");

how to loop through each row of dataFrame in pyspark

If you want to do something to each row in a DataFrame object, use map. This will allow you to perform further calculations on each row. It's the equivalent of looping across the entire dataset from 0 to len(dataset)-1.

Note that this will return a PipelinedRDD, not a DataFrame.

how to implement a pop up dialog box in iOS

Different people who come to this question mean different things by a popup box. I highly recommend reading the Temporary Views documentation. My answer is largely a summary of this and other related documentation.

Alert (show me an example)

enter image description here

Alerts display a title and an optional message. The user must acknowledge it (a one-button alert) or make a simple choice (a two-button alert) before going on. You create an alert with a UIAlertController.

It is worth quoting the documentation's warning and advice about creating unnecessary alerts.

enter image description here

Notes:

Action Sheet (show me an example)

enter image description here

Action Sheets give the user a list of choices. They appear either at the bottom of the screen or in a popover depending on the size and orientation of the device. As with alerts, a UIAlertController is used to make an action sheet. Before iOS 8, UIActionSheet was used, but now the documentation says:

Important: UIActionSheet is deprecated in iOS 8. (Note that UIActionSheetDelegate is also deprecated.) To create and manage action sheets in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleActionSheet.

Modal View (show me an example)

enter image description here

A modal view is a self-contained view that has everything it needs to complete a task. It may or may not take up the full screen. To create a modal view, use a UIPresentationController with one of the Modal Presentation Styles.

See also

Popover (show me an example)

enter image description here

A Popover is a view that appears when a user taps on something and disappears when tapping off it. It has an arrow showing the control or location from where the tap was made. The content can be just about anything you can put in a View Controller. You make a popover with a UIPopoverPresentationController. (Before iOS 8, UIPopoverController was the recommended method.)

In the past popovers were only available on the iPad, but starting with iOS 8 you can also get them on an iPhone (see here, here, and here).

See also

Notifications

enter image description here

Notifications are sounds/vibrations, alerts/banners, or badges that notify the user of something even when the app is not running in the foreground.

enter image description here

See also

A note about Android Toasts

enter image description here

In Android, a Toast is a short message that displays on the screen for a short amount of time and then disappears automatically without disrupting user interaction with the app.

People coming from an Android background want to know what the iOS version of a Toast is. Some examples of these questions can he found here, here, here, and here. The answer is that there is no equivalent to a Toast in iOS. Various workarounds that have been presented include:

  • Make your own with a subclassed UIView
  • Import a third party project that mimics a Toast
  • Use a buttonless Alert with a timer

However, my advice is to stick with the standard UI options that already come with iOS. Don't try to make your app look and behave exactly the same as the Android version. Think about how to repackage it so that it looks and feels like an iOS app.

How to style UITextview to like Rounded Rect text field?

I wanted the real deal, so I add UIImageView as a subview of the UITextView. This matches the native border on a UITextField, including the gradient from top to bottom:

textView.backgroundColor = [UIColor clearColor];
UIImageView *borderView = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, textView.frame.size.width, textView.frame.size.height)];
borderView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
UIImage *textFieldImage = [[UIImage imageNamed:@"TextField.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 8, 15, 8)];
borderView.image = textFieldImage;
[textField addSubview: borderView];
[textField sendSubviewToBack: borderView];

These are the images I use:

enter image description here enter image description here

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

A similar dex issue resolved method

gradle.build was containing:

compile files('libs/httpclient-4.2.1.jar')
compile 'org.apache.httpcomponents:httpclient:4.5'
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'

The issue was resolved when i removed

compile files('libs/httpclient-4.2.1.jar') 

My gradle now looks like:

apply plugin: 'com.android.application'

android {

compileSdkVersion 24
buildToolsVersion "24.0.3"

defaultConfig {
    applicationId "com.mmm.ll"
    minSdkVersion 16
    targetSdkVersion 24
    useLibrary  'org.apache.http.legacy'
}

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {

compile 'com.google.android.gms:play-services:6.1.+'
compile files('libs/PayPalAndroidSDK.jar')
compile files('libs/ksoap2-android-assembly-3.0.0-RC.4-jar-with-dependencies.jar')
compile files('libs/picasso-2.1.1.jar')
compile files('libs/gcm.jar')
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}

There was a redundancy in the JAR file and the compiled gradle project

So keenly look for dependency and jar files having same classes.

And remove redundancy.
This worked for me.

Fastest way to write huge data in text file Java

For these bulky reads from DB you may want to tune your Statement's fetch size. It might save a lot of roundtrips to DB.

http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Statement.html#setFetchSize%28int%29

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

jQuery Version

_x000D_
_x000D_
$(function() {_x000D_
  $('#bookmarkme').click(function() {_x000D_
    if (window.sidebar && window.sidebar.addPanel) { // Mozilla Firefox Bookmark_x000D_
      window.sidebar.addPanel(document.title, window.location.href, '');_x000D_
    } else if (window.external && ('AddFavorite' in window.external)) { // IE Favorite_x000D_
      window.external.AddFavorite(location.href, document.title);_x000D_
    } else if (window.opera && window.print) { // Opera Hotlist_x000D_
      this.title = document.title;_x000D_
      return true;_x000D_
    } else { // webkit - safari/chrome_x000D_
      alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
_x000D_
_x000D_
_x000D_

How to enable php7 module in apache?

First, disable the php5 module:

a2dismod php5

then, enable the php7 module:

a2enmod php7.0

Next, reload/restart the Apache service:

service apache2 restart

Update 2018-09-04

wrt the comment, you need to specify exact installed version.

Bash: infinite sleep (infinite blocking)

Maybe this seems ugly, but why not just run cat and let it wait for input forever?

Is it possible to open developer tools console in Chrome on Android phone?

I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:

http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/

The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML

Colouring plot by factor in R

There are two ways that I know of to color plot points by factor and then also have a corresponding legend automatically generated. I'll give examples of both:

  1. Using ggplot2 (generally easier)
  2. Using R's built in plotting functionality in combination with the colorRampPallete function (trickier, but many people prefer/need R's built-in plotting facilities)

For both examples, I will use the ggplot2 diamonds dataset. We'll be using the numeric columns diamond$carat and diamond$price, and the factor/categorical column diamond$color. You can load the dataset with the following code if you have ggplot2 installed:

library(ggplot2)
data(diamonds)

Using ggplot2 and qplot

It's a one liner. Key item here is to give qplot the factor you want to color by as the color argument. qplot will make a legend for you by default.

qplot(
  x = carat,
  y = price,
  data = diamonds,
  color = diamonds$color # color by factor color (I know, confusing)
)

Your output should look like this: qplot output colored by factor "diamond$color"

Using R's built in plot functionality

Using R's built in plot functionality to get a plot colored by a factor and an associated legend is a 4-step process, and it's a little more technical than using ggplot2.

First, we will make a colorRampPallete function. colorRampPallete() returns a new function that will generate a list of colors. In the snippet below, calling color_pallet_function(5) would return a list of 5 colors on a scale from red to orange to blue:

color_pallete_function <- colorRampPalette(
  colors = c("red", "orange", "blue"),
  space = "Lab" # Option used when colors do not represent a quantitative scale
  )

Second, we need to make a list of colors, with exactly one color per diamond color. This is the mapping we will use both to assign colors to individual plot points, and to create our legend.

num_colors <- nlevels(diamonds$color)
diamond_color_colors <- color_pallet_function(num_colors)

Third, we create our plot. This is done just like any other plot you've likely done, except we refer to the list of colors we made as our col argument. As long as we always use this same list, our mapping between colors and diamond$colors will be consistent across our R script.

plot(
  x = diamonds$carat,
  y = diamonds$price,
  xlab = "Carat",
  ylab = "Price",
  pch = 20, # solid dots increase the readability of this data plot
  col = diamond_color_colors[diamonds$color]
)

Fourth and finally, we add our legend so that someone reading our graph can clearly see the mapping between the plot point colors and the actual diamond colors.

legend(
  x ="topleft",
  legend = paste("Color", levels(diamonds$color)), # for readability of legend
  col = diamond_color_colors,
  pch = 19, # same as pch=20, just smaller
  cex = .7 # scale the legend to look attractively sized
)

Your output should look like this: standard R plot output colored by factor "diamond$color"

Nifty, right?

Excel VBA Run Time Error '424' object required

You have two options,

-If you want the value:

Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value

-if you want the cell object:

Dim oCell as Range  ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")

Forcing Internet Explorer 9 to use standards document mode

I have faced issue like my main page index.jsp contains the below line but eventhough rendering was not proper in IE. Found the issue and I have added the code in all the files which I included in index.jsp. Hurray! it worked.

So You need to add below code in all the files which you include into the page otherwise it wont work.

    <!doctype html>
    <head>
      <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    </head>

Consider defining a bean of type 'service' in your configuration [Spring boot]

Consider defining a bean of type 'moviecruser.repository.MovieRepository' in your configuration.

This type of issue will generate if you did not add correct dependency. Its the same issue I faced but after I found my JPA dependency is not working correctly, so make sure that first dependency is correct or not.

For example:-

The dependency I used:

    <dependency>
       <groupId>org.springframework.data</groupId>      
       <artifactId>spring-data-jpa</artifactId>
    </dependency>

Description (got this exception):-

Parameter 0 of constructor in moviecruser.serviceImple.MovieServiceImpl required a bean of type 'moviecruser.repository.MovieRepository' that could not be found.

Action:

After change dependency:-

    <!-- 
    <dependency>
       <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

Response:-

2019-09-06 23:08:23.202 INFO 7780 -
[main]moviecruser.MovieCruserApplication]:Started MovieCruserApplication in 10.585 seconds (JVM running for 11.357)

How can I set the default timezone in node.js?

Unfortunately, setting process.env.TZ doesn't work really well - basically it's indeterminate when the change will be effective).

So setting the system's timezone before starting node is your only proper option.

However, if you can't do that, it should be possible to use node-time as a workaround: get your times in local or UTC time, and convert them to the desired timezone. See How to use timezone offset in Nodejs? for details.

How to include another XHTML in XHTML using JSF 2.0 Facelets?

Included page:

<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>

Including page:

<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
  • You start your included xhtml file with ui:composition as shown above.
  • You include that file with ui:include in the including xhtml file as also shown above.

How can I make a Python script standalone executable to run without ANY dependency?

You might wish to investigate Nuitka. It takes Python source code and converts it in to C++ API calls. Then it compiles into an executable binary (ELF on Linux). It has been around for a few years now and supports a wide range of Python versions.

You will probably also get a performance improvement if you use it. It is recommended.

How to uninstall downloaded Xcode simulator?

You can remove them from /Library/Developer/CoreSimulator/Profiles/Runtimes (Not ~/Library!):

screenshot

How to update specific key's value in an associative array in PHP?

Change your foreach to something like this, You are not assigning data back to your return variable $data after performing operation on that.

foreach($data as $key => $value)
{
  $data[$key]['transaction_date'] = date('d/m/Y',$value['transaction_date']);
}

Codepad DEMO.

How to clear an ImageView in Android?

As kwasi wrote and golu edited, you can use transparent, instead of white:

File drawable/transparent.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/transparent"/>
</shape>

Inside an activity, view, etc:

view.setImageResource(R.drawable.transparent);

How to set the maxAllowedContentLength to 500MB while running on IIS7?

According to MSDN maxAllowedContentLength has type uint, its maximum value is 4,294,967,295 bytes = 3,99 gb

So it should work fine.

See also Request Limits article. Does IIS return one of these errors when the appropriate section is not configured at all?

See also: Maximum request length exceeded

How to get a complete list of object's methods and attributes?

Here is a practical addition to the answers of PierreBdR and Moe:

  • For Python >= 2.6 and new-style classes, dir() seems to be enough.
  • For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir(), look for __class__, and then to go for its __bases__:

    # code borrowed from the rlcompleter module
    # tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' )
    
    # or: from rlcompleter import get_class_members
    def get_class_members(klass):
        ret = dir(klass)
        if hasattr(klass,'__bases__'):
            for base in klass.__bases__:
                ret = ret + get_class_members(base)
        return ret
    
    
    def uniq( seq ): 
        """ the 'set()' way ( use dict when there's no set ) """
        return list(set(seq))
    
    
    def get_object_attrs( obj ):
        # code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )
        ret = dir( obj )
        ## if "__builtins__" in ret:
        ##    ret.remove("__builtins__")
    
        if hasattr( obj, '__class__'):
            ret.append('__class__')
            ret.extend( get_class_members(obj.__class__) )
    
            ret = uniq( ret )
    
        return ret
    

(Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for get_object_attrs() as for dir(), and for old-style classes the main addition to the dir() output seem to be the __class__ attribute.)

How do I lock the orientation to portrait mode in a iPhone Web Application?

This is a pretty hacky solution, but it's at least something(?). The idea is to use a CSS transform to rotate the contents of your page to quasi-portrait mode. Here's JavaScript (expressed in jQuery) code to get you started:

$(document).ready(function () {
  function reorient(e) {
    var portrait = (window.orientation % 180 == 0);
    $("body > div").css("-webkit-transform", !portrait ? "rotate(-90deg)" : "");
  }
  window.onorientationchange = reorient;
  window.setTimeout(reorient, 0);
});

The code expects the entire contents of your page to live inside a div just inside the body element. It rotates that div 90 degrees in landscape mode - back to portrait.

Left as an exercise to the reader: the div rotates around its centerpoint, so its position will probably need to be adjusted unless it's perfectly square.

Also, there's an unappealing visual problem. When you change orientation, Safari rotates slowly, then the top-level div snaps to 90degrees different. For even more fun, add

body > div { -webkit-transition: all 1s ease-in-out; }

to your CSS. When the device rotates, then Safari does, then the content of your page does. Beguiling!

Spring Could not Resolve placeholder

My solution was to add a space between the $ and the {.

For example:

@Value("${appclient.port:}")

becomes

@Value("$ {appclient.port:}")

Mail not sending with PHPMailer over SSL using SMTP

I got a similar failure with SMTP whenever my client machine changes network connection (e.g., home vs. office network) and somehow restarting network service (or rebooting the machine) resolves the issue for me. Not sure if this would apply to your case, but just in case.

sudo /etc/init.d/networking restart   # for ubuntu

Python's time.clock() vs. time.time() accuracy?

The short answer is: most of the time time.clock() will be better. However, if you're timing some hardware (for example some algorithm you put in the GPU), then time.clock() will get rid of this time and time.time() is the only solution left.

Note: whatever the method used, the timing will depend on factors you cannot control (when will the process switch, how often, ...), this is worse with time.time() but exists also with time.clock(), so you should never run one timing test only, but always run a series of test and look at mean/variance of the times.

Why does my Eclipse keep not responding?

Very likely your filesystem is out of sync with your Eclipse... Resource is out of sync with the file system. Using SVN? If you "Refresh" all of your projects in explorer, speed returns to normal.

"Fatal error: Unable to find local grunt." when running "grunt" command

You have to install grunt in your project folder

  1. create your package.json

    $ npm init
    
  2. install grunt for this project, this will be installed under node_modules/. --save-dev will add this module to devDependency in your package.json

    $ npm install grunt --save-dev
    
  3. then create gruntfile.js and run

    $ grunt 
    

How do I calculate the normal vector of a line segment?

If we define dx = x2 - x1 and dy = y2 - y1, then the normals are (-dy, dx) and (dy, -dx).

Note that no division is required, and so you're not risking dividing by zero.

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

How can I listen to the form submit event in javascript?

This is the simplest way you can have your own javascript function be called when an onSubmit occurs.

HTML

<form>
    <input type="text" name="name">
    <input type="submit" name="submit">
</form>

JavaScript

window.onload = function() {
    var form = document.querySelector("form");
    form.onsubmit = submitted.bind(form);
}

function submitted(event) {
    event.preventDefault();
}

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

Angular 4 img src is not found

@Annk you can make a variable in the __component.ts file

myImage : string = "http://example.com/path/image.png";

and inside the __.component.html file you can use one of those 3 methods :

1 .

<div> <img src="{{myImage}}"> </div>

2 .

<div> <img [src]="myImage"/> </div>

3 .

<div> <img bind-src="myImage"/> </div>

How to repeat a string a variable number of times in C++?

Here's an example of the string "abc" repeated 3 times:

#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <iterator>

using namespace std;

int main() {
    ostringstream repeated;
    fill_n(ostream_iterator<string>(repeated), 3, string("abc"));
    cout << "repeated: " << repeated.str() << endl;  // repeated: abcabcabc
    return 0;
}

Connecting to remote URL which requires authentication using Java

Use this code for basic authentication.

_x000D_
_x000D_
URL url = new URL(path);_x000D_
String userPass = "username:password";_x000D_
String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);//or_x000D_
//String basicAuth = "Basic " + new String(Base64.encode(userPass.getBytes(), Base64.No_WRAP));_x000D_
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();_x000D_
urlConnection.setRequestProperty("Authorization", basicAuth);_x000D_
urlConnection.connect();
_x000D_
_x000D_
_x000D_

Close Current Tab

You can only close windows/tabs that you create yourself. That is, you cannot programmatically close a window/tab that the user creates.

For example, if you create a window with window.open() you can close it with window.close().

What characters are valid for JavaScript variable names?

Basically, in regular expression form: [a-zA-Z_$][0-9a-zA-Z_$]*. In other words, the first character can be a letter or _ or $, and the other characters can be letters or _ or $ or numbers.

Note: While other answers have pointed out that you can use Unicode characters in JavaScript identifiers, the actual question was "What characters should I use for the name of an extension library like jQuery?" This is an answer to that question. You can use Unicode characters in identifiers, but don't do it. Encodings get screwed up all the time. Keep your public identifiers in the 32-126 ASCII range where it's safe.

Toggle button using two image on different state

You can try something like this. Here on click of image button I toggle the imageview.

holder.imgitem.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!onclick){
            mSparseBooleanArray.put((Integer) view.getTag(), true);
            holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
            onclick=true;}
            else if(onclick)
            {
                 mSparseBooleanArray.put((Integer) view.getTag(), false);
                  holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);

            onclick=false;
            }
        }
    });

Using multiple parameters in URL in express

For what you want I would've used

    app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
       const name = request.params.fruitName 
       const color = request.params.fruitColor 
    });

or better yet

    app.get('/fruit/:fruit', function(request, response) {
       const fruit = request.params.fruit
       console.log(fruit)
    });

where fruit is a object. So in the client app you just call

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}

and as a response you should see:

    //  client side response
    // { name: My fruit name, color:The color of the fruit}

node.js: cannot find module 'request'

I was running into the same problem, here is how I got it working..

open terminal:

mkdir testExpress
cd testExpress
npm install request

or

sudo npm install -g request // If you would like to globally install.

now don't use

node app.js or node test.js, you will run into this problem doing so. You can also print the problem that is being cause by using this command.. "node -p app.js"

The above command to start nodeJs has been deprecated. Instead use

npm start

You should see this..

[email protected] start /Users/{username}/testExpress
node ./bin/www

Open your web browser and check for localhost:3000

You should see Express install (Welcome to Express)

Jquery Ajax Loading image

Try something like this:

<div id="LoadingImage" style="display: none">
  <img src="" />
</div>

<script>
  function ajaxCall(){
    $("#LoadingImage").show();
      $.ajax({ 
        type: "GET", 
        url: surl, 
        dataType: "jsonp", 
        cache : false, 
        jsonp : "onJSONPLoad", 
        jsonpCallback: "newarticlescallback", 
        crossDomain: "true", 
        success: function(response) { 
          $("#LoadingImage").hide();
          alert("Success"); 
        }, 
        error: function (xhr, status) {  
          $("#LoadingImage").hide();
          alert('Unknown error ' + status); 
        }    
      });  
    }
</script>

Append column to pandas dataframe

Just as a matter of fact:

data_joined = dat1.join(dat2)
print(data_joined)

Vlookup referring to table data in a different sheet

I have faced similar problem and it was returning #N/A. That means matching data is present but you might having extra space in the M3 column record, that may prevent it from getting exact value. Because you have set last parameter as FALSE, it is looking for "exact match". This formula is correct: =VLOOKUP(M3,Sheet1!$A$2:$Q$47,13,FALSE)

VBA equivalent to Excel's mod function

But if you just want to tell the difference between an odd iteration and an even iteration, this works just fine:

If i Mod 2 > 0 then 'this is an odd 
   'Do Something
Else 'it is even
   'Do Something Else
End If

How do you clear a slice in Go?

It all depends on what is your definition of 'clear'. One of the valid ones certainly is:

slice = slice[:0]

But there's a catch. If slice elements are of type T:

var slice []T

then enforcing len(slice) to be zero, by the above "trick", doesn't make any element of

slice[:cap(slice)]

eligible for garbage collection. This might be the optimal approach in some scenarios. But it might also be a cause of "memory leaks" - memory not used, but potentially reachable (after re-slicing of 'slice') and thus not garbage "collectable".

Converting int to bytes in Python 3

That's the way it was designed - and it makes sense because usually, you would call bytes on an iterable instead of a single integer:

>>> bytes([3])
b'\x03'

The docs state this, as well as the docstring for bytes:

 >>> help(bytes)
 ...
 bytes(int) -> bytes object of size given by the parameter initialized with null bytes

A simple explanation of Naive Bayes Classification

Naive Bayes: Naive Bayes comes under supervising machine learning which used to make classifications of data sets. It is used to predict things based on its prior knowledge and independence assumptions.

They call it naive because it’s assumptions (it assumes that all of the features in the dataset are equally important and independent) are really optimistic and rarely true in most real-world applications.

It is classification algorithm which makes the decision for the unknown data set. It is based on Bayes Theorem which describe the probability of an event based on its prior knowledge.

Below diagram shows how naive Bayes works

enter image description here

Formula to predict NB:

enter image description here

How to use Naive Bayes Algorithm ?

Let's take an example of how N.B woks

Step 1: First we find out Likelihood of table which shows the probability of yes or no in below diagram. Step 2: Find the posterior probability of each class.

enter image description here

Problem: Find out the possibility of whether the player plays in Rainy condition?

P(Yes|Rainy) = P(Rainy|Yes) * P(Yes) / P(Rainy)

P(Rainy|Yes) = 2/9 = 0.222
P(Yes) = 9/14 = 0.64
P(Rainy) = 5/14 = 0.36

Now, P(Yes|Rainy) = 0.222*0.64/0.36 = 0.39 which is lower probability which means chances of the match played is low.

For more reference refer these blog.

Refer GitHub Repository Naive-Bayes-Examples

XMLHttpRequest cannot load an URL with jQuery

In new jQuery 1.5 you can use:

$.ajax({
    type: "GET",
    url: "http://localhost:99000/Services.svc/ReturnPersons",
    dataType: "jsonp",
    success: readData(data),
    error: function (xhr, ajaxOptions, thrownError) {
      alert(xhr.status);
      alert(thrownError);
    }
})

How to undo a git pull?

Or to make it more explicit than the other answer:

git pull 

whoops?

git reset --keep HEAD@{1}

Versions of git older than 1.7.1 do not have --keep. If you use such version, you could use --hard - but that is a dangerous operation because it loses any local changes.


To the commenter

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation)

How to overlay image with color in CSS?

You can also add an additional class with such settings. Overlay will not overlap content and no additional tag is needed

.overlay {
  position: relative;
  z-index: 0;
}

.overlay::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: red;
    opacity: .6;
    /* !!! */
    z-index: -1;
}

https://codepen.io/zeroox003/pen/yLYbpOB

What is the App_Data folder used for in Visual Studio?

The intended use of App_data is to store application data for the web process to acess. It should not be viewable by the web and is a place for the web app to store and read data from.

Python Unicode Encode Error

You can use something of the form

s.decode('utf-8')

which will convert a UTF-8 encoded bytestring into a Python Unicode string. But the exact procedure to use depends on exactly how you load and parse the XML file, e.g. if you don't ever access the XML string directly, you might have to use a decoder object from the codecs module.

Why can't I use switch statement on a String?

The following is a complete example based on JeeBee's post, using java enum's instead of using a custom method.

Note that in Java SE 7 and later you can use a String object in the switch statement's expression instead.

public class Main {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {

      String current = args[0];
      Days currentDay = Days.valueOf(current.toUpperCase());

      switch (currentDay) {
          case MONDAY:
          case TUESDAY:
          case WEDNESDAY:
              System.out.println("boring");
              break;
          case THURSDAY:
              System.out.println("getting better");
          case FRIDAY:
          case SATURDAY:
          case SUNDAY:
              System.out.println("much better");
              break;

      }
  }

  public enum Days {

    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
  }
}

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

#!/usr/bin/python

# encoding=utf8

Try This to starting of python file

How to make an inline-block element fill the remainder of the line?

See: http://jsfiddle.net/qx32C/36/

_x000D_
_x000D_
.lineContainer {_x000D_
    overflow: hidden; /* clear the float */_x000D_
    border: 1px solid #000_x000D_
}_x000D_
.lineContainer div {_x000D_
    height: 20px_x000D_
} _x000D_
.left {_x000D_
    width: 100px;_x000D_
    float: left;_x000D_
    border-right: 1px solid #000_x000D_
}_x000D_
.right {_x000D_
    overflow: hidden;_x000D_
    background: #ccc_x000D_
}
_x000D_
<div class="lineContainer">_x000D_
    <div class="left">left</div>_x000D_
    <div class="right">right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Why did I replace margin-left: 100px with overflow: hidden on .right?

EDIT: Here are two mirrors for the above (dead) link:

How to get the class of the clicked element?

Here's a quick jQuery example that adds a click event to each "li" tag, and then retrieves the class attribute for the clicked element. Hope it helps.

$("li").click(function() {
   var myClass = $(this).attr("class");
   alert(myClass);
});

Equally, you don't have to wrap the object in jQuery:

$("li").click(function() {
   var myClass = this.className;
   alert(myClass);
});

And in newer browsers you can get the full list of class names:

$("li").click(function() {
   var myClasses = this.classList;
   alert(myClasses.length + " " + myClasses[0]);
});

You can emulate classList in older browsers using myClass.split(/\s+/);

Write string to output stream

You can create a PrintStream wrapping around your OutputStream and then just call it's print(String):

final OutputStream os = new FileOutputStream("/tmp/out");
final PrintStream printStream = new PrintStream(os);
printStream.print("String");
printStream.close();

How do DATETIME values work in SQLite?

For practically all date and time matters I prefer to simplify things, very, very simple... Down to seconds stored in integers.

Integers will always be supported as integers in databases, flat files, etc. You do a little math and cast it into another type and you can format the date anyway you want.

Doing it this way, you don't have to worry when [insert current favorite database here] is replaced with [future favorite database] which coincidentally didn't use the date format you chose today.

It's just a little math overhead (eg. methods--takes two seconds, I'll post a gist if necessary) and simplifies things for a lot of operations regarding date/time later.

How can I disable notices and warnings in PHP within the .htaccess file?

Fortes is right, thank you.

When you have a shared hosting it is usual to obtain an 500 server error.

I have a website with Joomla and I added to the index.php:

ini_set('display_errors','off');

The error line showed in my website disappeared.

How to make a loop in x86 assembly language?

You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:

gcd_alg:
    subl    %ecx, %eax      /* a = a - c */
    cmpl    $0, %eax        /* if a == 0 */
    je      gcd_done        /* jump to end */
    cmpl    %ecx, %eax      /* if a < c */
    jl      gcd_preswap     /* swap and start over */
    jmp     gcd_alg         /* keep subtracting */

Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.

As for clearing the screen, that depends on the system you're using.

How to replace all occurrences of a string in Javascript?

Say you want to replace all the 'abc' with 'x':

let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def

I was trying to think about something more simple than modifying the string prototype.

How to loop through a directory recursively to delete files with certain extensions

The following function would recursively iterate through all the directories in the \home\ubuntu directory( whole directory structure under ubuntu ) and apply the necessary checks in else block.

function check {
        for file in $1/*      
        do
        if [ -d "$file" ]
        then
                check $file                          
        else
               ##check for the file
               if [ $(head -c 4 "$file") = "%PDF" ]; then
                         rm -r $file
               fi
        fi
        done     
}
domain=/home/ubuntu
check $domain

How to use relative/absolute paths in css URLs?

The URL is relative to the location of the CSS file, so this should work for you:

url('../../images/image.jpg')

The relative URL goes two folders back, and then to the images folder - it should work for both cases, as long as the structure is the same.

From https://www.w3.org/TR/CSS1/#url:

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document

How do I set a fixed background image for a PHP file?

I found my answer.

<?php
$profpic = "bg.jpg";
?>

<html>
<head>
<style type="text/css">

body {
background-image: url('<?php echo $profpic;?>');
}
</style>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>

Sending POST data in Android

Note (Oct 2020): AsyncTask used in the following answer has been deprecated in Android API level 30. Please refer to Official documentation or this blog post for a more updated example

Updated (June 2017) Answer which works on Android 6.0+. Thanks to @Rohit Suthar, @Tamis Bolvari and @sudhiskr for the comments.

    public class CallAPI extends AsyncTask<String, String, String> {
    
        public CallAPI(){
            //set context variables if required
        }
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    
         @Override
         protected String doInBackground(String... params) {
            String urlString = params[0]; // URL to call
            String data = params[1]; //data to post
            OutputStream out = null;

            try {
                URL url = new URL(urlString);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                out = new BufferedOutputStream(urlConnection.getOutputStream());

                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                writer.write(data);
                writer.flush();
                writer.close();
                out.close();

                urlConnection.connect();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

References:

Original Answer (May 2010)

Note: This solution is outdated. It only works on Android devices up to 5.1. Android 6.0 and above do not include the Apache http client used in this answer.

Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

Make sure you have all dependencies solved

I run into this problem in my first attempt at AOP, following a spring tutorial. My problem was not having spring-aop.jar in my classpath. The tutorial listed all other dependencies I had to add, namely:

  • aspectjrt.jar
  • aspectjweaver.jar
  • aspectj.jar
  • aopalliance.jar

But the one was missing. Just one more problem that can contribute to that symptom in the original question.

I am using Eclipse (neon), Java SE 8, beans 3.0, spring AOP 3.0, Spring 4.3.4. The problem showed in the Java view --not JEE--, and while trying to just run the application with Right button menu -> Run As -> Java Application.

Double precision floating values in Python?

May be you need Decimal

>>> from decimal import Decimal    
>>> Decimal(2.675)
Decimal('2.67499999999999982236431605997495353221893310546875')

Floating Point Arithmetic

Retrieving a property of a JSON object by index?

Objects in JavaScript are collections of unordered properties. Objects are hashtables.

If you want your properties to be in alphabetical order, one possible solution would be to create an index for your properties in a separate array. Just a few hours ago, I answered a question on Stack Overflow which you may want to check out:

Here's a quick adaptation for your object1:

var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};

var index = [];

// build the index
for (var x in obj) {
   index.push(x);
}

// sort the index
index.sort(function (a, b) {    
   return a == b ? 0 : (a > b ? 1 : -1); 
}); 

Then you would be able to do the following:

console.log(obj[index[1]]);

The answer I cited earlier proposes a reusable solution to iterate over such an object. That is unless you can change your JSON to as @Jacob Relkin suggested in the other answer, which could be easier.


1 You may want to use the hasOwnProperty() method to ensure that the properties belong to your object and are not inherited from Object.prototype.

Software Design vs. Software Architecture

Architecture is the resulting collection of design patterns to build a system.

I guess Design is the creativity used to put all this together?

When and why do I need to use cin.ignore() in C++?

As pointed right by many other users. It's because there may be whitespace or a newline character.

Consider the following code, it removes all the duplicate characters from a given string.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int t;
    cin>>t;
    cin.ignore(); //Notice that this cin.ignore() is really crucial for any extra whitespace or newline character
    while(t--){
        vector<int> v(256,0);
        string s;
        getline(cin,s);
        string s2;
        for(int i=0;i<s.size();i++){
            if (v[s[i]]) continue;
            else{
                s2.push_back(s[i]);
                v[s[i]]++;
            }
        }
        cout<<s2<<endl;
    }
    return 0;
}

So, You get the point that it will ignore those unwanted inputs and will get the job done.

WHERE statement after a UNION in SQL?

select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''

How to detect string which contains only spaces?

You can Trim your String value by creating a trim function for your Strings.

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

now it will be available for your every String and you can use it as

str.trim().length// Result will be 0

You can also use this method to remove the white spaces at the start and end of the String i.e

"  hello  ".trim(); // Result will be "hello"

Returning JSON object as response in Spring Boot

use ResponseEntity<ResponseBean>

Here you can use ResponseBean or Any java bean as you like to return your api response and it is the best practice. I have used Enum for response. it will return status code and status message of API.

@GetMapping(path = "/login")
public ResponseEntity<ServiceStatus> restApiExample(HttpServletRequest request,
            HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        loginService.login(username, password, request);
        return new ResponseEntity<ServiceStatus>(ServiceStatus.LOGIN_SUCCESS,
                HttpStatus.ACCEPTED);
    }

for response ServiceStatus or(ResponseBody)

    public enum ServiceStatus {

    LOGIN_SUCCESS(0, "Login success"),

    private final int id;
    private final String message;

    //Enum constructor
    ServiceStatus(int id, String message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

Spring REST API should have below key in response

  1. Status Code
  2. Message

you will get final response below

{

   "StatusCode" : "0",

   "Message":"Login success"

}

you can use ResponseBody(java POJO, ENUM,etc..) as per your requirement.

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

how i solve it in Eclipse

  1. go to the properties of the project enter image description here

  2. go to Java compiler enter image description here

  3. change in the Compiler complicated level to java that my project work with (java 11 in my project) you can see that it your java that you work when the last message disappear

  4. Apply enter image description here

How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also use formatDate

let formattedDt = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ssZZZZZ', 'en_US')

for or while loop to do something n times

The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).

It is worth noting that in Python a for or while statement can have break, continue and else statements where:

  • break - terminates the loop
  • continue - moves on to the next time around the loop without executing following code this time around
  • else - is executed if the loop completed without any break statements being executed.

N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.

So the answer to your question is 'it all depends on what you are trying to do'!

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

This might not work for everyone, but I updated node and it fixed the issue for me when none of the above did

Bootstrap 4: Multilevel Dropdown Inside Navigation

The following is MultiLevel dropdown based on bootstrap4. I tried it was according to the bootstrap4 basic dropdown.

_x000D_
_x000D_
.dropdown-submenu{_x000D_
    position: relative;_x000D_
}_x000D_
.dropdown-submenu a::after{_x000D_
    transform: rotate(-90deg);_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 40%;_x000D_
}_x000D_
.dropdown-submenu:hover .dropdown-menu, .dropdown-submenu:focus .dropdown-menu{_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    position: absolute !important;_x000D_
    margin-top: -30px;_x000D_
    left: 100%;_x000D_
}_x000D_
@media (max-width: 992px) {_x000D_
    .dropdown-menu{_x000D_
        width: 50%;_x000D_
    }_x000D_
    .dropdown-menu .dropdown-submenu{_x000D_
        width: auto;_x000D_
    }_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link 1</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown link_x000D_
        </a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
          <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
          <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
          <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" data-toggle="dropdown" href="#">Something else here</a>_x000D_
            <ul class="dropdown-menu">_x000D_
              <a class="dropdown-item" href="#">A</a>_x000D_
              <a class="dropdown-item" href="#">b</a>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to install Android SDK Build Tools on the command line?

I just had this problem, so I finally wrote a 1 line bash dirty solution by reading and parsing the list of aviable tools :

 tools/android update sdk -u -t $(android list sdk | grep 'Android SDK Build-tools' | sed 's/ *\([0-9]\+\)\-.*/\1/')

Vertical (rotated) text in HTML table

Alternate Solution?

Instead of rotating the text, would it work to have it written "top to bottom?"

Like this:

S  
O  
M  
E  

T  
E  
X  
T  

I think that would be a lot easier - you can pick a string of text apart and insert a line break after each character.

This could be done via JavaScript in the browser like this:

"SOME TEXT".split("").join("\n")

... or you could do it server-side, so it wouldn't depend on the client's JS capabilities. (I assume that's what you mean by "portable?")

Also the user doesn't have to turn his/her head sideways to read it. :)

Update

This thread is about doing this with jQuery.

Bash write to file without echo?

I've a solution for bash purists.

The function 'define' helps us to assign a multiline value to a variable. This one takes one positional parameter: the variable name to assign the value.

In the heredoc, optionally there're parameter expansions too!

#!/bin/bash

define ()
{
  IFS=$'\n' read -r -d '' $1
}

BUCH="Matthäus 1"

define TEXT<<EOT
Aus dem Buch: ${BUCH}

1 Buch des Geschlechts Jesu Christi, des Sohnes Davids, des Sohnes Abrahams.
2 Abraham zeugte Isaak; Isaak aber zeugte Jakob, Jakob aber zeugte Juda und seine Brüder;
3 Juda aber zeugte Phares und Zara von der Thamar; Phares aber zeugte Esrom, Esrom aber zeugte Aram,

4 Aram aber zeugte Aminadab, Aminadab aber zeugte Nahasson, Nahasson aber zeugte Salmon,
5 Salmon aber zeugte Boas von der Rahab; Boas aber zeugte Obed von der Ruth; Obed aber zeugte Isai,
6 Isai aber zeugte David, den König. David aber zeugte Salomon von der, die Urias Weib gewesen; 

EOT

define TEXTNOEXPAND<<"EOT" # or define TEXTNOEXPAND<<'EOT'
Aus dem Buch: ${BUCH}

1 Buch des Geschlechts Jesu Christi, des Sohnes Davids, des Sohnes Abrahams.
2 Abraham zeugte Isaak; Isaak aber zeugte Jakob, Jakob aber zeugte Juda und seine Brüder;
3 Juda aber zeugte Phares und Zara von der Thamar; Phares aber zeugte Esrom, Esrom aber zeugte Aram,


4 Aram aber zeugte Aminadab, Aminadab aber zeugte Nahasson, Nahasson aber zeugte Salmon,
5 Salmon aber zeugte Boas von der Rahab; Boas aber zeugte Obed von der Ruth; Obed aber zeugte Isai,
6 Isai aber zeugte David, den König. David aber zeugte Salomon von der, die Urias Weib gewesen; 

EOT

OUTFILE="/tmp/matthäus_eins"

# Create file
>"$OUTFILE"

# Write contents
{
   printf "%s\n" "$TEXT"
   printf "%s\n" "$TEXTNOEXPAND"
} >>"$OUTFILE" 

Be lucky!

inline conditionals in angular.js

Works even in exotic Situations:

<br ng-show="myCondition == true" />

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

How do I create and access the global variables in Groovy?

I think you are talking about class level variables. As mentioned above using global variable/class level variables are not a good practice.

If you really want to use it. and if you are sure that there will not be impact...

Declare any variable out side the method. at the class level with out the variable type

eg:

{
   method()
   {
      a=10
      print(a)
   }

// def a or int a wont work

a=0

}

Using an array from Observable Object with ngFor and Async Pipe Angular 2

I think what u r looking for is this

<article *ngFor="let news of (news$ | async)?.articles">
<h4 class="head">{{news.title}}</h4>
<div class="desc"> {{news.description}}</div>
<footer>
    {{news.author}}
</footer>

github: server certificate verification failed

Make sure first that you have certificates installed on your Debian in /etc/ssl/certs.

If not, reinstall them:

sudo apt-get install --reinstall ca-certificates

Since that package does not include root certificates, add:

sudo mkdir /usr/local/share/ca-certificates/cacert.org
sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
sudo update-ca-certificates

Make sure your git does reference those CA:

git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt

Jason C mentions another potential cause (in the comments):

It was the clock. The NTP server was down, the system clock wasn't set properly, I didn't notice or think to check initially, and the incorrect time was causing verification to fail.

Certificates are time sensitive.

CSS Image size, how to fill, but not stretch?

As far as I know, there is a plugin to make this simple.

jQuery Plugin: Auto transform <img> into background style

<img class="fill" src="image.jpg" alt="Fill Image"></img>

<script>
    $("img.fill").img2bg();
</script>

Besides, this way also fulfills the accessibility needs. As this plugin will NOT remove your <img> tag from your codes, the screen reader still tells you the ALT text instead of skipping it.

jQuery - on change input text

I recently was wondering why my code doesn't work, then I realized, I need to setup the event handlers as soon as the document is loaded, otherwise when browser loads the code line by line, it loads the JavaScript, but it does not yet have the element to assign the event handler to it. with your example, it should be like this:

$(document).ready(function(){
     $("#kat").change(function(){ 
         alert("Hello");
     });
});

How do I kill a VMware virtual machine that won't die?

see the following from VMware's webpage

Powering off a virtual machine on an ESXi host (1014165) Symptoms

You are experiencing these issues:

You cannot power off an ESXi hosted virtual machine.
A virtual machine is not responsive and cannot be stopped or killed.

http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1014165

"Using the ESXi 5.x esxcli command to power off a virtual machine

The esxcli command can be used locally or remotely to power off a virtual machine running on ESXi 5.x. For more information, see the esxcli vm Commands section of the vSphere Command-Line Interface Reference.

Open a console session where the esxcli tool is available, either in the ESXi Shell, the vSphere Management Assistant (vMA), or the location where the vSphere Command-Line Interface (vCLI) is installed.

Get a list of running virtual machines, identified by World ID, UUID, Display Name, and path to the .vmx configuration file, using this command:

esxcli vm process list

Power off one of the virtual machines from the list using this command:

esxcli vm process kill --type=[soft,hard,force] --world-id=WorldNumber

Notes:
Three power-off methods are available. Soft is the most graceful, hard performs an immediate shutdown, and force should be used as a last resort.
Alternate power off command syntax is: esxcli vm process kill -t [soft,hard,force] -w WorldNumber

Repeat Step 2 and validate that the virtual machine is no longer running.

For ESXi 4.1:

Get a list of running virtual machines, identified by World ID, UUID, Display Name, and path to the .vmx configuration file, using this command:

esxcli vms vm list

Power off one of the virtual machines from the list using this command:

esxcli vms vm kill --type=[soft,hard,force] --world-id=WorldNumber"

PHP: maximum execution time when importing .SQL data file

After trying many things with no success, I've managed to get SSH access to the server, and import my 80Mb database with a command line, instead of phpMyAdmin. Here is the command:

mysql -u root -p -D mydatabase -o < mydatabase.sql

It's much easier to import big databases, if you are running xammp on windows, the path for mysql.exe is C:\xampp\mysql\bin\mysql.exe

Do something if screen width is less than 960 px

Use jQuery to get the width of the window.

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

That solved my problem on Ubuntu 14.04:

apt-get install libcurl4-gnutls-dev

Rails: Using greater than/less than with a where statement

Arel is your friend:

User.where(User.arel_table[:id].gt(200))

What integer hash function are good that accepts an integer hash key?

There's a nice overview over some hash algorithms at Eternally Confuzzled. I'd recommend Bob Jenkins' one-at-a-time hash which quickly reaches avalanche and therefore can be used for efficient hash table lookup.

Free XML Formatting tool

If you use Notepad++, I would suggest installing the XML Tools plugin. You can beautify any XML content (indentation and line breaks) or linarize it. Also you can (auto-)validate your file and apply XSL transformation to it.

Download the latest zip and copy the extracted DLL to the plugins directory of your Notepad++ installation. Also, download the External libs and copy them to your %SystemRoot%\system32\ directory.

Error: "Could Not Find Installable ISAM"

I used this to update a excel 12 xlsx file

        System.Data.OleDb.OleDbConnection MyConnection;
        System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
        MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='D:\\Programming\\Spreadsheet-Current.xlsx';Extended Properties='Excel 12.0;HDR=YES;';");
        MyConnection.Open();
        myCommand.Connection = MyConnection;
        string sql = "Update [ArticlesV2$] set [ID]='Test' where [ActualPageId]=114";// 
        myCommand.CommandText = sql;
        myCommand.ExecuteNonQuery();
        MyConnection.Close();

PHP Warning: Division by zero

Try using

$var = @($val1 / $val2);

How to INNER JOIN 3 tables using CodeIgniter

function fetch_comments($ticket_id){
    $this->db->select('tbl_tickets_replies.comments, 
           tbl_users.username,tbl_roles.role_name');
    $this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
    $this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
    $this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
    return $this->db->get('tbl_tickets_replies');
}

Is java.sql.Timestamp timezone specific?

It is specific from your driver. You need to supply a parameter in your Java program to tell it the time zone you want to use.

java -Duser.timezone="America/New_York" GetCurrentDateTimeZone

Further this:

to_char(new_time(sched_start_time, 'CURRENT_TIMEZONE', 'NEW_TIMEZONE'), 'MM/DD/YY HH:MI AM')

May also be of value in handling the conversion properly. Taken from here

Android Closing Activity Programmatically

you can use this.finish() if you want to close current activity.

this.finish()

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

Border Radius of Table is not working

To use border radius I have a border radius of 20px in the table, and then put the border radius on the first child of the table header (th) and the last child of the table header.

table {
  border-collapse: collapse;
  border-radius:20px;
  padding: 10px;
}

table th:first-child {
  /* border-radius = top left, top right, bottom right, bottom left */
    border-radius: 20px 0 0 0; /* curves the top left */
    padding-left: 15px;
}

table th:last-child {
    border-radius: 0 20px 0 0; /* curves the top right */
}

This however will not work if this is done with table data (td) because it will add a curve onto each table row. This is not a problem if you only have 2 rows in your table but any additional ones will add curves onto the inner rows too. You only want these curves on the outside of the table. So for this, add an id to your last row. Then you can apply the curves to them.

/* curves the first tableData in the last row */

#lastRow td:first-child {
    border-radius: 0 0 0 20px; /* bottom left curve */
}

/* curves the last tableData in the last row */

#lastRow td:last-child {
    border-radius: 0 0 20px 0; /* bottom right curve */
}

How can I append a query parameter to an existing URL?

Use the URI class.

Create a new URI with your existing String to "break it up" to parts, and instantiate another one to assemble the modified url:

URI u = new URI("http://[email protected]&name=John#fragment");

// Modify the query: append your new parameter
StringBuilder sb = new StringBuilder(u.getQuery() == null ? "" : u.getQuery());
if (sb.length() > 0)
    sb.append('&');
sb.append(URLEncoder.encode("paramName", "UTF-8"));
sb.append('=');
sb.append(URLEncoder.encode("paramValue", "UTF-8"));

// Build the new url with the modified query:
URI u2 = new URI(u.getScheme(), u.getAuthority(), u.getPath(),
    sb.toString(), u.getFragment());

Converting unix timestamp string to readable date

quick and dirty one liner:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

'2013-5-5-1-9-43'

Manually Triggering Form Validation using jQuery

When there is a very complex (especially asynchronous) validation process, there is a simple workaround:

<form id="form1">
<input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" />
<input type="submit" id="form1_submit_hidden" style="display:none" />
</form>
...
<script>
function submitIfVeryComplexValidationIsOk() {
    var form1 = document.forms['form1']
    if (!form1.checkValidity()) {
        $("#form1_submit_hidden").click()
        return
    }

    if (checkForVeryComplexValidation() === 'Ok') {
         form1.submit()
    } else {
         alert('form is invalid')
    }
}
</script>

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

How to fix height of TR?

That is because the words are wrapping and are going on new lines hence stretching the TR. This should fix your problem:

overflow:hidden;

Put that in the TR styles Although it should work, why not just let it stretch o0

PS. i aint tested it so dont hate XD

spring data jpa @query and pageable

Please reference :Spring Data JPA @Query, if you are using Spring Data JPA version 2.0.4 and later. Sample like below:

@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

Reordering Chart Data Series

FYI, if you are using two y-axis, the order numbers will only make a difference within the set of series of that y-axis. I believe secondary -y-axis by default are on top of the primary. If you want the series in the primary axis to be on top, you'll need to make it secondary instead.

Git for beginners: The definitive practical guide

I found this post to be very useful to get me started. I still need to read the book and other resources but the post was helpful in, as the title says, "understanding git conceptually". I also recommend taking the Git & GitHub course offered at RubyLearning.

Close Bootstrap modal on form submit

If you do not want to use jQuery, make the button type a normal button and add a click listener pointing to the function you would like to execute, and send the form in as a parameter. The button would be as follows:

<button (click)="yourSubmitFunction(yourForm)" [disabled]="!yourForm.valid" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>

Remember to remove: (ngSubmit)="yourSubmitFunction(yourForm)" from the form div if you use this method.

How do I find the duplicates in a list and create another list with them?

When using toolz:

from toolz import frequencies, valfilter

a = [1,2,2,3,4,5,4]
>>> list(valfilter(lambda count: count > 1, frequencies(a)).keys())
[2,4] 

Sorting arraylist in alphabetical order (case insensitive)

The simplest thing to do is:

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

How to get all registered routes in Express?

route details are listing route for "express": "4.x.x",

import {
  Router
} from 'express';
var router = Router();

router.get("/routes", (req, res, next) => {
  var routes = [];
  var i = 0;
  router.stack.forEach(function (r) {
    if (r.route && r.route.path) {
      r.route.stack.forEach(function (type) {
        var method = type.method.toUpperCase();
        routes[i++] = {
          no:i,
          method: method.toUpperCase(),
          path: r.route.path
        };
      })
    }
  })

  res.send('<h1>List of routes.</h1>' + JSON.stringify(routes));
});

SIMPLE OUTPUT OF CODE

List of routes.

[
{"no":1,"method":"POST","path":"/admin"},
{"no":2,"method":"GET","path":"/"},
{"no":3,"method":"GET","path":"/routes"},
{"no":4,"method":"POST","path":"/student/:studentId/course/:courseId/topic/:topicId/task/:taskId/item"},
{"no":5,"method":"GET","path":"/student/:studentId/course/:courseId/topic/:topicId/task/:taskId/item"},
{"no":6,"method":"PUT","path":"/student/:studentId/course/:courseId/topic/:topicId/task/:taskId/item/:itemId"},
{"no":7,"method":"DELETE","path":"/student/:studentId/course/:courseId/topic/:topicId/task/:taskId/item/:itemId"}
]

DB2 Date format

select to_char(current date, 'yyyymmdd') from sysibm.sysdummy1

result: 20160510

Illegal Escape Character "\"

Use "\\" to escape the \ character.

Find index of last occurrence of a sub-string using T-SQL

Old but still valid question, so heres what I created based on the info provided by others here.

create function fnLastIndexOf(@text varChar(max),@char varchar(1))
returns int
as
begin
return len(@text) - charindex(@char, reverse(@text)) -1
end

How to remove outliers from a dataset

Use outline = FALSE as an option when you do the boxplot (read the help!).

> m <- c(rnorm(10),5,10)
> bp <- boxplot(m, outline = FALSE)

enter image description here

How to do multiline shell script in Ansible

Adding a space before the EOF delimiter allows to avoid cmd:

- shell: |
    cat <<' EOF'
    This is a test.
    EOF

Convert timestamp to readable date/time PHP

strtotime makes a date string into a timestamp. You want to do the opposite, which is date. The typical mysql date format is date('Y-m-d H:i:s'); Check the manual page for what other letters represent.

If you have a timestamp that you want to use (apparently you do), it is the second argument of date().

Pass Multiple Parameters to jQuery ajax call

    var valueOfTextBox=$("#result").val();
    var valueOfSelectedCheckbox=$("#radio:checked").val();

    $.ajax({
    url: 'result.php',
    type: 'POST',
    data: { forValue: valueOfTextBox, check : valueOfSelectedCheckbox } ,
    beforeSend: function() {

          $("#loader").show();
       },
    success: function (response) {
       $("#loader").hide();
       $("#answer").text(response);
    },
    error: function () {
        //$("#loader").show();
        alert("error occured");
    }
    }); 

Changing background color of selected cell?

// animate between regular and selected state
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    if (selected) {
        self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
    }
    else {
        self.backgroundColor = [UIColor clearColor];
    }
}

Visual Studio: How to break on handled exceptions?

From Visual Studio 2015 and onward, you need to go to the "Exception Settings" dialog (Ctrl+Alt+E) and check off the "Common Language Runtime Exceptions" (or a specific one you want i.e. ArgumentNullException) to make it break on handled exceptions.

Step 1 Step 1 Step 2 Step 2

Accessing MP3 metadata with Python

What you're after is the ID3 module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:

from ID3 import *
try:
  id3info = ID3('file.mp3')
  print id3info
  # Change the tags
  id3info['TITLE'] = "Green Eggs and Ham"
  id3info['ARTIST'] = "Dr. Seuss"
  for k, v in id3info.items():
    print k, ":", v
except InvalidTagError, message:
  print "Invalid ID3 tag:", message

Tesseract running error

You can grab eng.traineddata Github:

wget https://github.com/tesseract-ocr/tessdata/raw/master/eng.traineddata

Check https://github.com/tesseract-ocr/tessdata for a full list of trained language data.

When you grab the file(s), move them to the /usr/local/share/tessdata folder. Warning: some Linux distributions (such as openSUSE and Ubuntu) may be expecting it in /usr/share/tessdata instead.

# If you got the data from Google, unzip it first!
gunzip eng.traineddata.gz 
# Move the data
sudo mv -v eng.traineddata /usr/local/share/tessdata/

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

#include <stdio.h>
int main () 
{
    printf("Hello ");
    goto Cleanup;
Cleanup: ; //This is an empty statement.
    char *str = "World\n";
    printf("%s\n", str);
}

How to set image to UIImage

UIImage *img = [UIImage imageNamed@"aImageName"];

Using Environment Variables with Vue.js

In vue-cli version 3:

There are the three options for .env files: Either you can use .env or:

  • .env.test
  • .env.development
  • .env.production

You can use custom .env variables by using the prefix regex as /^/ instead of /^VUE_APP_/ in /node_modules/@vue/cli-service/lib/util/resolveClientEnv.js:prefixRE

This is certainly not recommended for the sake of developing an open source app in different modes like test, development, and production of .env files. Because every time you npm install .. , it will be overridden.

How do I get the APK of an installed app without root access?

On Nougat(7.0) Android version run adb shell pm list packages to list the packages installed on the device. Then run adb shell pm path your-package-name to show the path of the apk. After use adb to copy the package to Downloads adb shell cp /data/app/com.test-1/base.apk /storage/emulated/0/Download. Then pull the apk from Downloads to your machine by running adb pull /storage/emulated/0/Download/base.apk.

Does 'position: absolute' conflict with Flexbox?

In my case, the issue was that I had another element in the center of the div with a conflicting z-index.

_x000D_
_x000D_
.wrapper {_x000D_
  color: white;_x000D_
  width: 320px;_x000D_
  position: relative;_x000D_
  border: 1px dashed gray;_x000D_
  height: 40px_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  position: absolute;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  top: 20px;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  /* This z-index override is needed to display on top of the other_x000D_
     div. Or, just swap the order of the HTML tags. */_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  background: green;_x000D_
}_x000D_
_x000D_
.conflicting {_x000D_
  position: absolute;_x000D_
  left: 120px;_x000D_
  height: 40px;_x000D_
  background: red;_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="parent">_x000D_
    <div class="child">_x000D_
       Centered_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="conflicting">_x000D_
    Conflicting_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Case Insensitive String comp in C

Additional pitfalls to watch out for when doing case insensitive compares:


Comparing as lower or as upper case? (common enough issue)

Both below will return 0 with strcicmpL("A", "a") and strcicmpU("A", "a").
Yet strcicmpL("A", "_") and strcicmpU("A", "_") can return different signed results as '_' is often between the upper and lower case letters.

This affects the sort order when used with qsort(..., ..., ..., strcicmp). Non-standard library C functions like the commonly available stricmp() or strcasecmp() tend to be well defined and favor comparing via lowercase. Yet variations exist.

int strcicmpL(char const *a, char const *b) {
  while (*b) {
    int d = tolower(*a) - tolower(*b);
    if (d) {
        return d;
    } 
    a++;
    b++;
  } 
  return tolower(*a);
}

int strcicmpU(char const *a, char const *b) {
  while (*b) {
    int d = toupper(*a) - toupper(*b);
    if (d) {
        return d;
    } 
    a++;
    b++;
  } 
  return toupper(*a);
}

char can have a negative value. (not rare)

touppper(int) and tolower(int) are specified for unsigned char values and the negative EOF. Further, strcmp() returns results as if each char was converted to unsigned char, regardless if char is signed or unsigned.

tolower(*a); // Potential UB
tolower((unsigned char) *a); // Correct (Almost - see following)

char can have a negative value and not 2's complement. (rare)

The above does not handle -0 nor other negative values properly as the bit pattern should be interpreted as unsigned char. To properly handle all integer encodings, change the pointer type first.

// tolower((unsigned char) *a);
tolower(*(const unsigned char *)a); // Correct

Locale (less common)

Although character sets using ASCII code (0-127) are ubiquitous, the remainder codes tend to have locale specific issues. So strcasecmp("\xE4", "a") might return a 0 on one system and non-zero on another.


Unicode (the way of the future)

If a solution needs to handle more than ASCII consider a unicode_strcicmp(). As C lib does not provide such a function, a pre-coded function from some alternate library is recommended. Writing your own unicode_strcicmp() is a daunting task.


Do all letters map one lower to one upper? (pedantic)

[A-Z] maps one-to-one with [a-z], yet various locales map various lower case chracters to one upper and visa-versa. Further, some uppercase characters may lack a lower case equivalent and again, visa-versa.

This obliges code to covert through both tolower() and tolower().

int d = tolower(toupper(*a)) - tolower(toupper(*b));

Again, potential different results for sorting if code did tolower(toupper(*a)) vs. toupper(tolower(*a)).


Portability

@B. Nadolson recommends to avoid rolling your own strcicmp() and this is reasonable, except when code needs high equivalent portable functionality.

Below is an approach that even performed faster than some system provided functions. It does a single compare per loop rather than two by using 2 different tables that differ with '\0'. Your results may vary.

static unsigned char low1[UCHAR_MAX + 1] = {
  0, 1, 2, 3, ...
  '@', 'a', 'b', 'c', ... 'z', `[`, ...  // @ABC... Z[...
  '`', 'a', 'b', 'c', ... 'z', `{`, ...  // `abc... z{...
}
static unsigned char low2[UCHAR_MAX + 1] = {
// v--- Not zero, but A which matches none in `low1[]`
  'A', 1, 2, 3, ...
  '@', 'a', 'b', 'c', ... 'z', `[`, ...
  '`', 'a', 'b', 'c', ... 'z', `{`, ...
}

int strcicmp_ch(char const *a, char const *b) {
  // compare using tables that differ slightly.
  while (low1[*(const unsigned char *)a] == low2[*(const unsigned char *)b]) {
    a++;
    b++;
  }
  // Either strings differ or null character detected.
  // Perform subtraction using same table.
  return (low1[*(const unsigned char *)a] - low1[*(const unsigned char *)b]);
}

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

OK, there are two ways of doing that:

// GLOBAL_CONCURRENT_QUEUE


- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE 
{
    dispatch_queue_t globalConcurrentQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalConcurrentQ, ^{

       // DATA PROCESSING 1
       sleep(1);
       NSLog(@"Hello world chekpoint 1");
       dispatch_sync(dispatch_get_main_queue(), ^{
           // UI UPDATION 1
           sleep(1);
           NSLog(@"Hello world chekpoint 2");
       });

        /* the control to come here after UI UPDATION 1 */
        sleep(1);
        NSLog(@"Hello world chekpoint 3");
        // DATA PROCESSING 2

        dispatch_sync(dispatch_get_main_queue(), ^{
            // UI UPDATION 2
            sleep(1);
            NSLog(@"Hello world chekpoint 4");
        });

        /* the control to come here after UI UPDATION 2 */
        sleep(1);
        NSLog(@"Hello world chekpoint 5");
        // DATA PROCESSING 3

        dispatch_sync(dispatch_get_main_queue(), ^{
            // UI UPDATION 3
            sleep(1);
            NSLog(@"Hello world chekpoint 6");
        });
   });
}



// SERIAL QUEUE
- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE 
{

    dispatch_queue_t serialQ = dispatch_queue_create("com.example.MyQueue", NULL);
    dispatch_async(serialQ, ^{

       // DATA PROCESSING 1
       sleep(1);
       NSLog(@"Hello world chekpoint 1");

       dispatch_sync(dispatch_get_main_queue(), ^{
           // UI UPDATION 1
           sleep(1);
           NSLog(@"Hello world chekpoint 2");
       });


       sleep(1);
       NSLog(@"Hello world chekpoint 3");
       // DATA PROCESSING 2

       dispatch_sync(dispatch_get_main_queue(), ^{
           // UI UPDATION 2
           sleep(1);
           NSLog(@"Hello world chekpoint 4");
       });  
   });
}

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.