Programs & Examples On #Fields for

In Ruby on Rails this creates a scope around a specific model object like #form_for, but doesn’t create the form tags themselves. This makes #fields_for suitable for specifying additional model objects in the same form.

How do I escape spaces in path for scp copy in Linux?

Sorry for using this Linux question to put this tip for Powershell on Windows 10: the space char escaping with backslashes or surrounding with quotes didn't work for me in this case. Not efficient, but I solved it using the "?" char instead:

for the file "tasks.txt Jun-22.bkp" I downloaded it using "tasks.txt?Jun-22.bkp"

Need to combine lots of files in a directory

There is a convenient third party tool named FileMenu Tools, that gives several right-click tools as a windows explorer extension.

One of them is Split file / Join Parts, that does and undoes exactly what you are looking for.

Check it at http://www.lopesoft.com/en/filemenutools. Of course, it is windows only, as Unixes environments already have lots of tools for that.

Python: Split a list into sub-lists based on index ranges

If you already know the indices:

list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]

Note that we're adding +1 to the end to make the range inclusive...

How to create a md5 hash of a string in C?

To be honest, the comments accompanying the prototypes seem clear enough. Something like this should do the trick:

void compute_md5(char *str, unsigned char digest[16]) {
    MD5Context ctx;
    MD5Init(&ctx);
    MD5Update(&ctx, str, strlen(str));
    MD5Final(digest, &ctx);
}

where str is a C string you want the hash of, and digest is the resulting MD5 digest.

In Unix, how do you remove everything in the current directory and below it?

I believe this answer is better:

https://unix.stackexchange.com/questions/12593/how-to-remove-all-the-files-in-a-directory

If your top-level directory is called images, then run rm -r images/*. This uses the shell glob operator * to run rm -r on every file or directory within images.

basically you go up one level, and then say delete everything inside X directory. This way you are still specifying what folder should have its content deleted, which is safer than just saying 'delete everything here", while preserving the original folder, (which sometimes you want to because you aren't allowed or just don't want to modify the folder's existing permissions)

CSS media query to target iPad and iPad only?

Finally found a solution from : Detect different device platforms using CSS

<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />

To reduce HTTP call, this can also be used inside you existing common CSS file:

@media all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait) {
  .ipad-portrait { color: red; } /* your css rules for ipad portrait */
}
@media all and (device-width: 1024px) and (device-height: 768px) and (orientation:landscape) {
  .ipad-landscape { color: blue; } /* your css rules for ipad landscape */
}

Hope this helps.

Other references:

C# code to validate email address

There is culture problem in regex in C# rather then js. So we need to use regex in US mode for email check. If you don't use ECMAScript mode, your language special characters are imply in A-Z with regex.

Regex.IsMatch(email, @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9_\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", RegexOptions.ECMAScript)

How do I make a Docker container start automatically on system boot?

I have a similar issue running Linux systems. After the system was booted, a container with a restart policy of "unless-stopped" would not restart automatically unless I typed a command that used docker in some way such as "docker ps". I was surprised as I expected that command to just report some status information. Next I tried the command "systemctl status docker". On a system where no docker commands had been run, this command reported the following:

? docker.service - Docker Application Container Engine

   Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)

     Active: inactive (dead)    TriggeredBy: ? docker.socket
       Docs: https://docs.docker.com

On a system where "docker ps" had been run with no other Docker commands, I got the following:

? docker.service - Docker Application Container Engine
    Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)

    Active: active (running) since Sun 2020-11-22 08:33:23 PST; 1h 25min ago

TriggeredBy: ? docker.socket
       Docs: https://docs.docker.com

   Main PID: 3135 (dockerd)
      Tasks: 13

    Memory: 116.9M
     CGroup: /system.slice/docker.service
             +-3135 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
 ... [various messages not shown ]

The most likely explanation is that Docker waits for some docker command before fully initializing and starting containers. You could presumably run "docker ps" in a systemd unit file at a point after all the services your containers need have been initialized. I've tested this by putting a file named docker-onboot.service in the directory /lib/systemd/system with the following contents:

[Unit]
# This service is provided to force Docker containers
# that should automatically restart to restart when the system
# is booted. While the Docker daemon will start automatically,
# it will not be fully initialized until some Docker command
# is actually run.  This unit merely runs "docker ps": any
# Docker command will result in the Docker daemon completing
# its initialization, at which point all containers that can be
# automatically restarted after booting will be restarted.
#
Description=Docker-Container Startup on Boot
Requires=docker.socket
After=docker.socket network-online.target containerd.service

[Service]
Type=oneshot
ExecStart=/usr/bin/docker ps

[Install]

WantedBy=multi-user.target

So far (one test, with this service enabled), the container started when the computer was booted. I did not try a dependency on docker.service because docker.service won't start until a docker command is run. The next test will be with the docker-onboot disabled (to see if the WantedBy dependency will automatically start it).

How to use C++ in Go

There's talk about interoperability between C and Go when using the gcc Go compiler, gccgo. There are limitations both to the interoperability and the implemented feature set of Go when using gccgo, however (e.g., limited goroutines, no garbage collection).

How to get root directory in yii2

If you want to get the root directory of your yii2 project use, assuming that the name of your project is project_app you'll need to use:

echo Yii::getAlias('@app');

on windows you'd see "C:\dir\to\project_app"

on linux you'll get "/var/www/dir/to/your/project_app"

I was formally using:

echo Yii::getAlias('@webroot').'/..';

I hope this helps someone

How do I get the value of a textbox using jQuery?

By Using

$("#txtEmail").val()

you get the actual value of the element

Can't find SDK folder inside Android studio path, and SDK manager not opening

SDK folder by defalut is in C:\Users\<user-name>\AppData\Local\Android. And the AppData folder is hidden in windows. Enable show hidden files in folder option, and give a look inside that.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

you are mixing mysql and mysqli

use this mysql_real_escape_string like

$username = mysql_real_escape_string($_POST['username']);

NOTE : mysql_* is deprecated use mysqli_* or PDO

Force Java timezone as GMT/UTC

Wow. I know this is an ancient thread but all I can say is do not call TimeZone.setDefault() in any user-level code. This always sets the Timezone for the whole JVM and is nearly always a very bad idea. Learn to use the joda.time library or the new DateTime class in Java 8 which is very similar to the joda.time library.

Base64 String throwing invalid character error

One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.

Limit Decimal Places in Android EditText

This works fine for me. It allows value to be entered even after focus changed and retrieved back. For example: 123.00, 12.12, 0.01, etc..

1.Integer.parseInt(getString(R.string.valuelength)) Specifies the length of the input digits.Values accessed from string.xml file.It is quiet easy to change values. 2.Integer.parseInt(getString(R.string.valuedecimal)), this is for decimal places max limit.

private InputFilter[] valDecimalPlaces;
private ArrayList<EditText> edittextArray;

valDecimalPlaces = new InputFilter[] { new DecimalDigitsInputFilterNew(
    Integer.parseInt(getString(R.string.valuelength)),
    Integer.parseInt(getString(R.string.valuedecimal))) 
};

Array of EditText values that allows to perform action.

for (EditText etDecimalPlace : edittextArray) {
            etDecimalPlace.setFilters(valDecimalPlaces);

I just used array of values that contain multiple edittext Next DecimalDigitsInputFilterNew.class file.

import android.text.InputFilter;
import android.text.Spanned;

public class DecimalDigitsInputFilterNew implements InputFilter {

    private final int decimalDigits;
    private final int before;

    public DecimalDigitsInputFilterNew(int before ,int decimalDigits) {
        this.decimalDigits = decimalDigits;
        this.before = before;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end,
        Spanned dest, int dstart, int dend) {
        StringBuilder builder = new StringBuilder(dest);
        builder.replace(dstart, dend, source
              .subSequence(start, end).toString());
        if (!builder.toString().matches("(([0-9]{1})([0-9]{0,"+(before-1)+"})?)?(\\.[0-9]{0,"+decimalDigits+"})?")) {
             if(source.length()==0)
                  return dest.subSequence(dstart, dend);
             return "";
        }
        return null;
    }
}

JavaScript: Alert.Show(message) From ASP.NET Code-behind

This message show the alert message directly

ScriptManager.RegisterStartupScript(this,GetType(),"showalert","alert('Only alert Message');",true);

This message show alert message from JavaScript function

ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);

These are two ways to display alert messages in c# code behind

How to completely uninstall python 2.7.13 on Ubuntu 16.04

try following to see all instances of python

whereis python
which python

Then remove all instances using:

sudo apt autoremove python

repeat sudo apt autoremove python(for all versions) that should do it, then install Anaconda and manage Pythons however you like if you need to reinstall it.

Directory.GetFiles: how to get only filename, not full path?

Try,

  string[] files =  new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray();

Above line may throw UnauthorizedAccessException. To handle this check out below link

C# Handle System.UnauthorizedAccessException in LINQ

How to identify unused CSS definitions from multiple CSS files in a project

Google Chrome Developer Tools has (a currently experimental) feature called CSS Overview which will allow you to find unused CSS rules.

To enable it follow these steps:

  1. Open up DevTools (Command+Option+I on Mac; Control+Shift+I on Windows)
  2. Head over to DevTool Settings (Function+F1 on Mac; F1 on Windows)
  3. Click open the Experiments section
  4. Enable the CSS Overview option

enter image description here

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

You could try Conditional Formatting available in the tool menu "Format -> Conditional Formatting".

How to force the input date format to dd/mm/yyyy?

To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow

<input id="txtDay" type="text" placeholder="DD" />

<input id="txtMonth" type="text" placeholder="MM" />

<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>


  function validateDate() {
    var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);

    if (date == "Invalid Date") {
        alert("jnvalid date");

    }
}

Renaming Columns in an SQL SELECT Statement

you have to rename each column

SELECT col1 as MyCol1,
       col2 as MyCol2,
 .......
 FROM `foobar`

Can't find @Nullable inside javax.annotation.*

I am using Guava which has annotation included:

(Gradle code )

compile 'com.google.guava:guava:23.4-jre'

Laravel - Forbidden You don't have permission to access / on this server

I met the same issue, then I do same as the solution of @lubat and my project work well. :D My virtualhost configuration:

<VirtualHost *:80>
     ServerName laravelht.vn
     DocumentRoot D:/Lavarel/HTPortal/public
     SetEnv APPLICATION_ENV "development"
     <Directory D:/Lavarel/HTPortal/public>
         DirectoryIndex index.php
         AllowOverride All
         Require all granted
         Order allow,deny
         Allow from all
     </Directory>
 </VirtualHost>

Why is January month 0 in Java Calendar?

Personally, I took the strangeness of the Java calendar API as an indication that I needed to divorce myself from the Gregorian-centric mindset and try to program more agnostically in that respect. Specifically, I learned once again to avoid hardcoded constants for things like months.

Which of the following is more likely to be correct?

if (date.getMonth() == 3) out.print("March");

if (date.getMonth() == Calendar.MARCH) out.print("March");

This illustrates one thing that irks me a little about Joda Time - it may encourage programmers to think in terms of hardcoded constants. (Only a little, though. It's not as if Joda is forcing programmers to program badly.)

Typescript ReferenceError: exports is not defined

for me, removing "esModuleInterop": true from tsconfig.json did the trick.

Cannot find module cv2 when using OpenCV

If want to install opencv in virtual environment. Run command in terminal for getting virtual environment list.

conda env list

or jupyter notebook command is

!conda env list

Then update your anaconda.

conda update anaconda-navigator
conda update navigator-updater

Install opencv in your selected environment path.

conda install -c ['environment path'] opencv

Juypter notebook

!conda install --yes --prefix ['environment path'] opencv

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

Preferred Java way to ping an HTTP URL for availability

here the writer suggests this:

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) { e.printStackTrace(); }
    return false;
}

Possible Questions

  • Is this really fast enough?Yes, very fast!
  • Couldn’t I just ping my own page, which I want to request anyways? Sure! You could even check both, if you want to differentiate between “internet connection available” and your own servers beeing reachable What if the DNS is down? Google DNS (e.g. 8.8.8.8) is the largest public DNS service in the world. As of 2013 it serves 130 billion requests a day. Let ‘s just say, your app not responding would probably not be the talk of the day.

read the link. its seems very good

EDIT: in my exp of using it, it's not as fast as this method:

public boolean isOnline() {
    NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

they are a bit different but in the functionality for just checking the connection to internet the first method may become slow due to the connection variables.

What is declarative programming?

Declarative programming is "the act of programming in languages that conform to the mental model of the developer rather than the operational model of the machine".

The difference between declarative and imperative programming is well illustrated by the problem of parsing structured data.

An imperative program would use mutually recursive functions to consume input and generate data. A declarative program would express a grammar that defines the structure of the data so that it can then be parsed.

The difference between these two approaches is that the declarative program creates a new language that is more closely mapped to the mental model of the problem than is its host language.

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

For the love of all that is holy...

In my case, I had to set the openssl.cafile PHP config variable to the PEM file path.

I trust it is very true that there are many systems where setting curl.cainfo in PHP's config is exactly what is needed, but in the environment I'm working with, which is the eboraas/laravel docker container, which uses Debian 8 (jessie) and PHP 5.6, setting that variable did not do the trick.

I noticed that the output of php -i did not mention anything about that particular config setting, but it did have a few lines about openssl. There is both an openssl.capath and openssl.cafile option, but just setting the second one allowed curl via PHP to finally be okay with HTTPS URLs.

How to change the type of a field?

all answers so far use some version of forEach, iterating over all collection elements client-side.

However, you could use MongoDB's server-side processing by using aggregate pipeline and $out stage as :

the $out stage atomically replaces the existing collection with the new results collection.

example:

db.documents.aggregate([
         {
            $project: {
               _id: 1,
               numberField: { $substr: ['$numberField', 0, -1] },
               otherField: 1,
               differentField: 1,
               anotherfield: 1,
               needolistAllFieldsHere: 1
            },
         },
         {
            $out: 'documents',
         },
      ]);

How do I get a list of installed CPAN modules?

This works for me

perl -e 'print join("\n",@INC,"")'

How to open a txt file and read numbers in Java

Good news in Java 8 we can do it in one line:

List<Integer> ints = Files.lines(Paths.get(fileName))
                          .map(Integer::parseInt)
                          .collect(Collectors.toList());

127 Return code from $?

If you're trying to run a program using a scripting language, you may need to include the full path of the scripting language and the file to execute. For example:

exec('/usr/local/bin/node /usr/local/lib/node_modules/uglifycss/uglifycss in.css > out.css');

What is the easiest way to encrypt a password when I save it to the registry?

Please also consider "salting" your hash (not a culinary concept!). Basically, that means appending some random text to the password before you hash it.

"The salt value helps to slow an attacker perform a dictionary attack should your credential store be compromised, giving you additional time to detect and react to the compromise."

To store password hashes:

a) Generate a random salt value:

byte[] salt = new byte[32];
System.Security.Cryptography.RNGCryptoServiceProvider.Create().GetBytes(salt);

b) Append the salt to the password.

// Convert the plain string pwd into bytes
byte[] plainTextBytes = System.Text UnicodeEncoding.Unicode.GetBytes(plainText);
// Append salt to pwd before hashing
byte[] combinedBytes = new byte[plainTextBytes.Length + salt.Length];
System.Buffer.BlockCopy(plainTextBytes, 0, combinedBytes, 0, plainTextBytes.Length);
System.Buffer.BlockCopy(salt, 0, combinedBytes, plainTextBytes.Length, salt.Length);

c) Hash the combined password & salt:

// Create hash for the pwd+salt
System.Security.Cryptography.HashAlgorithm hashAlgo = new System.Security.Cryptography.SHA256Managed();
byte[] hash = hashAlgo.ComputeHash(combinedBytes);

d) Append the salt to the resultant hash.

// Append the salt to the hash
byte[] hashPlusSalt = new byte[hash.Length + salt.Length];
System.Buffer.BlockCopy(hash, 0, hashPlusSalt, 0, hash.Length);
System.Buffer.BlockCopy(salt, 0, hashPlusSalt, hash.Length, salt.Length);

e) Store the result in your user store database.

This approach means you don't need to store the salt separately and then recompute the hash using the salt value and the plaintext password value obtained from the user.

Edit: As raw computing power becomes cheaper and faster, the value of hashing -- or salting hashes -- has declined. Jeff Atwood has an excellent 2012 update too lengthy to repeat in its entirety here which states:

This (using salted hashes) will provide the illusion of security more than any actual security. Since you need both the salt and the choice of hash algorithm to generate the hash, and to check the hash, it's unlikely an attacker would have one but not the other. If you've been compromised to the point that an attacker has your password database, it's reasonable to assume they either have or can get your secret, hidden salt.

The first rule of security is to always assume and plan for the worst. Should you use a salt, ideally a random salt for each user? Sure, it's definitely a good practice, and at the very least it lets you disambiguate two users who have the same password. But these days, salts alone can no longer save you from a person willing to spend a few thousand dollars on video card hardware, and if you think they can, you're in trouble.

javascript getting my textbox to display a variable

You're on the right track with using document.getElementById() as you have done for your first two text boxes. Use something like document.getElementById("textbox3") to retrieve the element. Then you can just set its value property: document.getElementById("textbox3").value = answer;

For the "Your answer is: --", I'd recommend wrapping the "--" in a <span/> (e.g. <span id="answerDisplay">--</span>). Then use document.getElementById("answerDisplay").textContent = answer; to display it.

proper name for python * operator?

I call *args "star args" or "varargs" and **kwargs "keyword args".

Oracle error : ORA-00905: Missing keyword

Late answer, but I just came on this list today!

CREATE TABLE assignment_20101120 AS SELECT * FROM assignment;

Does the same.

type object 'datetime.datetime' has no attribute 'datetime'

Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that datetime is both a top-level module as well as being a type within that module. This is confusing.

Your error is probably based on the confusing naming of the module, and what either you or a module you're using has already imported.

>>> import datetime
>>> datetime
<module 'datetime' from '/usr/lib/python2.6/lib-dynload/datetime.so'>
>>> datetime.datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)

But, if you import datetime.datetime:

>>> from datetime import datetime
>>> datetime
<type 'datetime.datetime'>
>>> datetime.datetime(2001,5,1) # You shouldn't expect this to work 
                                # as you imported the type, not the module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
>>> datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)

I suspect you or one of the modules you're using has imported like this: from datetime import datetime.

Using the "animated circle" in an ImageView while loading stuff

You can do this by using the following xml

<RelativeLayout
    style="@style/GenericProgressBackground"
    android:id="@+id/loadingPanel"
    >
    <ProgressBar
        style="@style/GenericProgressIndicator"/>
</RelativeLayout>

With this style

<style name="GenericProgressBackground" parent="android:Theme">
    <item name="android:layout_width">fill_parent</item>    
    <item name="android:layout_height">fill_parent</item>
    <item name="android:background">#DD111111</item>    
    <item name="android:gravity">center</item>  
</style>
<style name="GenericProgressIndicator" parent="@android:style/Widget.ProgressBar.Small">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:indeterminate">true</item> 
</style>

To use this, you must hide your UI elements by setting the visibility value to GONE and whenever the data is loaded, call setVisibility(View.VISIBLE) on all your views to restore them. Don't forget to call findViewById(R.id.loadingPanel).setVisiblity(View.GONE) to hide the loading animation.

If you dont have a loading event/function but just want the loading panel to disappear after x seconds use a Handle to trigger the hiding/showing.

How to merge rows in a column into one cell in excel?

I present to you my ConcatenateRange VBA function (thanks Jean for the naming advice!) . It will take a range of cells (any dimension, any direction, etc.) and merge them together into a single string. As an optional third parameter, you can add a seperator (like a space, or commas sererated).

In this case, you'd write this to use it:

=ConcatenateRange(A1:A4)

Function ConcatenateRange(ByVal cell_range As range, _
                    Optional ByVal separator As String) As String

Dim newString As String
Dim cell As Variant

For Each cell in cell_range
    If Len(cell) <> 0 Then
        newString = newString & (separator & cell)
    End if
Next

If Len(newString) <> 0 Then
    newString = Right$(newString, (Len(newString) - Len(separator)))
End If

ConcatenateRange = newString

End Function

PHP XML how to output nice format

<?php

$xml = $argv[1];

$dom = new DOMDocument();

// Initial block (must before load xml string)
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
// End initial block

$dom->loadXML($xml);
$out = $dom->saveXML();

print_R($out);

Golang append an item to a slice

Go takes a more lean and lazy approach in doing this. It keeps modifying the same underlying array until the capacity of a slice is reached.

Ref: http://criticalindirection.com/2016/02/17/slice-with-a-pinch-of-salt/

Output of the example from the link explains the behavior of slices in Go.

Creating slice a.

Slice a len=7 cap=7 [0 0 0 0 0 0 0]

Slice b refers to the 2, 3, 4 indices in slice a. Hence, the capacity is 5 (= 7-2).

b := a[2:5]
Slice b len=3 cap=5 [0 0 0]

Modifying slice b, also modifies a, since they are pointing to the same underlying array.

b[0] = 9
Slice a len=7 cap=7 [0 0 9 0 0 0 0]
Slice b len=3 cap=5 [9 0 0]

Appending 1 to slice b. Overwrites a.

Slice a len=7 cap=7 [0 0 9 0 0 1 0]
Slice b len=4 cap=5 [9 0 0 1]

Appending 2 to slice b. Overwrites a.

Slice a len=7 cap=7 [0 0 9 0 0 1 2]
Slice b len=5 cap=5 [9 0 0 1 2]

Appending 3 to slice b. Here, a new copy is made as the capacity is overloaded.

Slice a len=7 cap=7 [0 0 9 0 0 1 2]
Slice b len=6 cap=12 [9 0 0 1 2 3]

Verifying slices a and b point to different underlying arrays after the capacity-overload in the previous step.

b[1] = 8
Slice a len=7 cap=7 [0 0 9 0 0 1 2]
Slice b len=6 cap=12 [9 8 0 1 2 3]

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

Google's new Maven repo is required for the latest support library that is compatible with Android 8.0. Just update your Google's Maven repository like below:

To add them to your build, add maven.google.com to the Maven repositories in your module-level build.gradle file:

repositories {
    maven {
        url 'https://maven.google.com'
        // Alternative URL is 'https://dl.google.com/dl/android/maven2/'
    }
}

Alternative you can update build.gradle file like this:

    repositories {
        jcenter()
        google()
    }

Then add the desired library to your dependencies block. For example, the cardview library looks like this:

dependencies {
    compile 'com.android.support:cardview-v7:26.1.0'
}

CSS text-align: center; is not centering things

I assume you want all the items next to each other, and the whole thing to be centered horizontally.

li elements are display: block by default, taking up all the horizontal space.

Add

div#footer ul li { display: inline }

once you've done that, you probably want to get rid of the list's bullets:

div#footer ul { list-style-type: none; padding: 0px; margin: 0px }

How can I get Docker Linux container information from within the container itself?

As an aside, if you have the pid of the container and want to get the docker id of that container, a good way is to use nsenter in combination with the sed magic above:

nsenter -n -m -t pid -- cat /proc/1/cgroup | grep -o -e "docker-.*.scope" | head -n 1 | sed "s/docker-\(.*\).scope/\\1/"

Oracle: Import CSV file

An alternative solution is using an external table: http://www.orafaq.com/node/848

Use this when you have to do this import very often and very fast.

PHP append one array to another (not array_push or +)

Why not use

$appended = array_merge($a,$b); 

Why don't you want to use this, the correct, built-in method.

How do I escape a single quote ( ' ) in JavaScript?

    document.getElementById("something").innerHTML = "<img src=\"something\" onmouseover=\"change('ex1')\" />";

OR

    document.getElementById("something").innerHTML = '<img src="something" onmouseover="change(\'ex1\')" />';

It should be working...

How to return JSON with ASP.NET & jQuery

Just return object: it will be parser to JSON.

public Object Get(string id)
{
    return new { id = 1234 };
}

Simulating Slow Internet Connection

Also, for simulating a slow connection on some *nixes, you can try using ipfw. More information is provided by Ben Newman's answer on this Quora question

com.sun.jdi.InvocationException occurred invoking method

I also had a similar exception when debugging in Eclipse. When I moused-over an object, the pop up box displayed an com.sun.jdi.InvocationException message. The root cause for me was not the toString() method of my class, but rather the hashCode() method. It was causing a NullPointerException, which caused the com.sun.jdi.InvocationException to appear during debugging. Once I took care of the null pointer, everything worked as expected.

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How to create an 2D ArrayList in java?

ArrayList<String>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add("test");

Tomcat 8 Maven Plugin for Java 8

Yes you can,

In your pom.xml, add the tomcat plugin. (You can use this for both Tomcat 7 and 8):

pom.xml

<!-- Tomcat plugin -->  
<plugin>  
 <groupId>org.apache.tomcat.maven</groupId>  
 <artifactId>tomcat7-maven-plugin</artifactId>  
 <version>2.2</version>  
 <configuration>  
  <url>http:// localhost:8080/manager/text</url>  
  <server>TomcatServer</server>    *(From maven > settings.xml)*
  <username>*yourtomcatusername*</username>  
  <password>*yourtomcatpassword*</password>   
 </configuration>   
</plugin>   

tomcat-users.xml

<tomcat-users>
    <role rolename="manager-gui"/>  
        <role rolename="manager-script"/>   
        <user username="admin" password="password" roles="manager-gui,manager-script" />  
</tomcat-users>

settings.xml (maven > conf)

<servers>  
    <server>
       <id>TomcatServer</id>
       <username>admin</username>
       <password>password</password>
    </server>
</servers>  

* deploy/re-deploy

mvn tomcat7:deploy OR mvn tomcat7:redeploy

Tried this on (Both Ubuntu and Windows 8/10):
* Jdk 7 & Tomcat 7
* Jdk 7 & Tomcat 8
* Jdk 8 & Tomcat 7
* Jdk 8 & Tomcat 8
* Jdk 8 & Tomcat 9

Tested on Both Jdk 7/8 & Tomcat 7/8. (Works with Tomcat 8.5 and 9)

Note:
Tomcat manager should be running or properly setup, before you can use it with maven.

Good Luck!

How do I check to see if my array includes an object?

Why not do it simply by picking eight different numbers from 0 to Horse.count and use that to get your horses?

offsets = (0...Horse.count).to_a.sample(8)
@suggested_horses = offsets.map{|i| Horse.first(:offset => i) }

This has the added advantage that it won't cause an infinite loop if you happen to have less than 8 horses in your database.

Note: Array#sample is new to 1.9 (and coming in 1.8.8), so either upgrade your Ruby, require 'backports' or use something like shuffle.first(n).

how to implement Interfaces in C++?

There is no concept of interface in C++,
You can simulate the behavior using an Abstract class.
Abstract class is a class which has atleast one pure virtual function, One cannot create any instances of an abstract class but You could create pointers and references to it. Also each class inheriting from the abstract class must implement the pure virtual functions in order that it's instances can be created.

How do I remove all non alphanumeric characters from a string except dash?

I use a variation of one of the answers here. I want to replace spaces with "-" so its SEO friendly and also make lower case. Also not reference system.web from my services layer.

private string MakeUrlString(string input)
{
    var array = input.ToCharArray();

    array = Array.FindAll<char>(array, c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-');

    var newString = new string(array).Replace(" ", "-").ToLower();
    return newString;
}

Blur effect on a div element

I got blur working with SVG blur filter:

CSS

-webkit-filter: url(#svg-blur);
        filter: url(#svg-blur);

SVG

<svg id="svg-filter">
    <filter id="svg-blur">
        <feGaussianBlur in="SourceGraphic" stdDeviation="4"></feGaussianBlur>
    </filter>
</svg>

Working example:

https://jsfiddle.net/1k5x6dgm/

Please note - this will not work in IE versions

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

I suspect GCC (mingw) has custom code to disable the checks for the wide printf functions on Windows. This is because Microsoft's own implementation (MSVCRT) is badly wrong and has %s and %ls backwards for the wide printf functions; since GCC can't be sure whether you will be linking with MS's broken implementation or some corrected one, the least-obtrusive thing it can do is just shut off the warning.

SQL Server - find nth occurrence in a string

DECLARE @x VARCHAR(32) = 'MS-SQL-Server';

SELECT 
SUBSTRING(@x,0,CHARINDEX('-',LTRIM(RTRIM(@x)))) A,
SUBSTRING(@x,CHARINDEX('-',LTRIM(RTRIM(@x)))+1,CHARINDEX('-' 
,LTRIM(RTRIM(@x)))) B,
SUBSTRING(@x,CHARINDEX('-',REVERSE(LTRIM(RTRIM(@x))))+1,LEN(@x)-1) C


A   B   C
MS  SQL Server

SQL Server AS statement aliased column within WHERE statement

SQL Server is tuned to apply the filters before it applies aliases (because that usually produces faster results). You could do a nested select statement. Example:

SELECT Latitude FROM 
(
    SELECT Lat AS Latitude FROM poi_table
) A
WHERE Latitude < 500

I realize this may not be what you are looking for, because it makes your queries much more wordy. A more succinct approach would be to make a view that wraps your underlying table:

CREATE VIEW vPoi_Table AS 
SELECT Lat AS Latitude FROM poi_table

Then you could say:

SELECT Latitude FROM vPoi_Table WHERE Latitude < 500

if checkbox is checked, do this

$('#checkbox').change(function(){
   (this.checked)?$('p').css('color','#0099ff'):$('p').css('color','another_color');
});

How to disable javax.swing.JButton in java?

The code is very long so I can't paste all the code.

There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.

You need to create a SSCCE to post on the forum.

So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.

Learn how the basice work first before writing a 200 line program.

Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.

Does Notepad++ show all hidden characters?

Yes, it does. The way to enable this depends on your version of Notepad++. On newer versions you can use:

Menu View ? Show Symbol ? *Show All Characters`

or

Menu View ? Show Symbol ? Show White Space and TAB

(Thanks to bers' comment and bkaid's answers below for these updated locations.)


On older versions you can look for:

Menu View ? Show all characters

or

Menu View ? Show White Space and TAB

Using %f with strftime() in Python to get microseconds

You can also get microsecond precision from the time module using its time() function.
(time.time() returns the time in seconds since epoch. Its fractional part is the time in microseconds, which is what you want.)

>>> from time import time
>>> time()
... 1310554308.287459   # the fractional part is what you want.


# comparision with strftime -
>>> from datetime import datetime
>>> from time import time
>>> datetime.now().strftime("%f"), time()
... ('287389', 1310554310.287459)

How do I compare a value to a backslash?

If message.value[] is string:

if message.value[0] in ('/', '\'):
    do_stuff()

If it not str

Setting selected option in laravel form

To echo some other answers here, the code I just used with 5.6 is this

{{ Form::select('status', ['Draft' => 'Draft', 'Sent' => 'Sent', 'Paid' => 'Paid'], $model->status, ['id' => 'status']) }}

In order to be able to use the Form Helper from LaravelCollective I took a look at https://laravelcollective.com/docs/master/html#drop-down-lists

I also had to composer require the dependency also so that I could use it in my projects

composer require "laravelcollective/html":"^5"

Lastly I altered my config/app.php and added the following in the $aliases array

    'Form' => Collective\Html\FormFacade::class,

https://laravelcollective.com/docs/master/html should be consulted if any of the above ceases to work.

How to set the holo dark theme in a Android app?

By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.

So just set it to:

<style name="AppTheme" parent="android:Theme.Holo" />

Set a default font for whole iOS app?

Am using like this type of font class in swift. Using font extension class.

enum FontName: String {

  case regular      = "Roboto-Regular"

}

//MARK: - Set Font Size
enum FontSize: CGFloat {
    case size = 10

}
extension UIFont {

    //MARK: - Bold Font
  class var regularFont10: UIFont {
        return UIFont(name: FontName.regular.rawValue, size:FontSize.size.rawValue )!
    }
}

How do I add a auto_increment primary key in SQL Server database?

You can also perform this action via SQL Server Management Studio.

Right click on your selected table -> Modify

Right click on the field you want to set as PK --> Set Primary Key

Under Column Properties set "Identity Specification" to Yes, then specify the starting value and increment value.

Then in the future if you want to be able to just script this kind of thing out you can right click on the table you just modified and select

"SCRIPT TABLE AS" --> CREATE TO

so that you can see for yourself the correct syntax to perform this action.

Is there an easy way to add a border to the top and bottom of an Android View?

Simplest way to add borders to inset the borders using InsetDrawable,following will show top border only :

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetBottom="-2dp"
    android:insetLeft="-2dp"
    android:insetRight="-2dp">
    <shape android:shape="rectangle">

        <solid android:color="@color/light_gray" />
        <stroke
            android:width=".5dp"
            android:color="@color/dark_gray" />
    </shape>
</inset>

"register" keyword in C?

Actually, register tells the compiler that the variable does not alias with anything else in the program (not even char's).

That can be exploited by modern compilers in a variety of situations, and can help the compiler quite a bit in complex code - in simple code the compilers can figure this out on their own.

Otherwise, it serves no purpose and is not used for register allocation. It does not usually incur performance degradation to specify it, as long as your compiler is modern enough.

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Just use these command lines:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

If needed, you can also follow this Ubuntu tutorial.

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

Android Camera Preview Stretched

I gave up the calculations and simply get the size of the view where I want the camera preview displayed and set the camera's preview size the same (just flipped width/height due to rotation) in my custom SurfaceView implementation:

@Override // CameraPreview extends SurfaceView implements SurfaceHolder.Callback { 
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    Display display = ((WindowManager) getContext().getSystemService(
            Context.WINDOW_SERVICE)).getDefaultDisplay();

    if (display.getRotation() == Surface.ROTATION_0) {
        final Camera.Parameters params = camera.getParameters();
        // viewParams is from the view where the preview is displayed
        params.setPreviewSize(viewParams.height, viewParams.width);
        camera.setDisplayOrientation(90);
        requestLayout();
        camera.setParameters(params);
    }
    // I do not enable rotation, so this can otherwise stay as is
}

Is there a naming convention for MySQL?

I would say that first and foremost: be consistent.

I reckon you are almost there with the conventions that you have outlined in your question. A couple of comments though:

Points 1 and 2 are good I reckon.

Point 3 - sadly this is not always possible. Think about how you would cope with a single table foo_bar that has columns foo_id and another_foo_id both of which reference the foo table foo_id column. You might want to consider how to deal with this. This is a bit of a corner case though!

Point 4 - Similar to Point 3. You may want to introduce a number at the end of the foreign key name to cater for having more than one referencing column.

Point 5 - I would avoid this. It provides you with little and will become a headache when you want to add or remove columns from a table at a later date.

Some other points are:

Index Naming Conventions

You may wish to introduce a naming convention for indexes - this will be a great help for any database metadata work that you might want to carry out. For example you might just want to call an index foo_bar_idx1 or foo_idx1 - totally up to you but worth considering.

Singular vs Plural Column Names

It might be a good idea to address the thorny issue of plural vs single in your column names as well as your table name(s). This subject often causes big debates in the DB community. I would stick with singular forms for both table names and columns. There. I've said it.

The main thing here is of course consistency!

Class constants in python

Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:

def module_register_class_constants(klass, attr_prefix):
    globals().update(
        (name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
    )

class Animal(object):
    SIZE_HUGE = "Huge"
    SIZE_BIG = "Big"

module_register_class_constants(Animal, "SIZE_")

class Horse(Animal):
    def printSize(self):
        print SIZE_BIG

Abstract class in Java

It's a class that cannot be instantiated, and forces implementing classes to, possibly, implement abstract methods that it outlines.

Groovy String to Date

Try this:

def date = Date.parse("E MMM dd H:m:s z yyyy", dateStr)

Here are the patterns to format the dates

Smooth GPS data

You should not calculate speed from position change per time. GPS may have inaccurate positions, but it has accurate speed (above 5km/h). So use the speed from GPS location stamp. And further you should not do that with course, although it works most of the times.

GPS positions, as delivered, are already Kalman filtered, you probably cannot improve, in postprocessing usually you have not the same information like the GPS chip.

You can smooth it, but this also introduces errors.

Just make sure that your remove the positions when the device stands still, this removes jumping positions, that some devices/Configurations do not remove.

Oracle 10g: Extract data (select) from XML (CLOB Type)

Try using xmltype.createxml(xml).

As in,

select extract(xmltype.createxml(xml), '//fax').getStringVal() from mytab;

It worked for me.

If you want to improve or manipulate even further.

Try something like this.

Select *
from xmltable(xmlnamespaces('some-name-space' as "ns", 
                                  'another-name-space' as "ns1",
                           ), 
                    '/ns/ns1/foo/bar'
                    passing xmltype.createxml(xml) 
                    columns id varchar2(10) path '//ns//ns1/id',
                            idboss varchar2(500) path '//ns0//ns1/idboss',
                            etc....

                    ) nice_xml_table

Hope it helps someone.

Enable 'xp_cmdshell' SQL Server

Right click server -->Facets-->Surface Area Configuration -->XPCmshellEnbled -->true enter image description here

Get the filePath from Filename using Java

Correct solution with "File" class to get the directory - the "path" of the file:

String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();

which will return:

path = "C:\\Temp\\your directory"

How to implement authenticated routes in React Router 4?

It seems your hesitation is in creating your own component and then dispatching in the render method? Well you can avoid both by just using the render method of the <Route> component. No need to create a <AuthenticatedRoute> component unless you really want to. It can be as simple as below. Note the {...routeProps} spread making sure you continue to send the properties of the <Route> component down to the child component (<MyComponent> in this case).

<Route path='/someprivatepath' render={routeProps => {

   if (!this.props.isLoggedIn) {
      this.props.redirectToLogin()
      return null
    }
    return <MyComponent {...routeProps} anotherProp={somevalue} />

} />

See the React Router V4 render documentation

If you did want to create a dedicated component, then it looks like you are on the right track. Since React Router V4 is purely declarative routing (it says so right in the description) I do not think you will get away with putting your redirect code outside of the normal component lifecycle. Looking at the code for React Router itself, they perform the redirect in either componentWillMount or componentDidMount depending on whether or not it is server side rendering. Here is the code below, which is pretty simple and might help you feel more comfortable with where to put your redirect logic.

import React, { PropTypes } from 'react'

/**
 * The public API for updating the location programatically
 * with a component.
 */
class Redirect extends React.Component {
  static propTypes = {
    push: PropTypes.bool,
    from: PropTypes.string,
    to: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object
    ])
  }

  static defaultProps = {
    push: false
  }

  static contextTypes = {
    router: PropTypes.shape({
      history: PropTypes.shape({
        push: PropTypes.func.isRequired,
        replace: PropTypes.func.isRequired
      }).isRequired,
      staticContext: PropTypes.object
    }).isRequired
  }

  isStatic() {
    return this.context.router && this.context.router.staticContext
  }

  componentWillMount() {
    if (this.isStatic())
      this.perform()
  }

  componentDidMount() {
    if (!this.isStatic())
      this.perform()
  }

  perform() {
    const { history } = this.context.router
    const { push, to } = this.props

    if (push) {
      history.push(to)
    } else {
      history.replace(to)
    }
  }

  render() {
    return null
  }
}

export default Redirect

how to remove css property using javascript?

This should do the trick - setting the inline style to normal for zoom:

$('div').attr("style", "zoom:normal;");

React: Expected an assignment or function call and instead saw an expression

Possible way is (sure you can change array declaration to getting from db or another external resource):

const MyPosts = () => {

  let postsRawData = [
    { id: 1, text: 'Post 1', likesCount: '1' },
    { id: 2, text: 'Post 2', likesCount: '231' },
    { id: 3, text: 'Post 3', likesCount: '547' }
  ];

  const postsItems = []
  for (const [key, value] of postsRawData.entries()) {
    postsItems.push(<Post text={value.text} likesCount={value.likesCount} />)
  }

  return (
      <div className={css.posts}>Posts:
          {postsItems}
      </div>
  )
}

What does "TypeError 'xxx' object is not callable" means?

The action occurs when you attempt to call an object which is not a function, as with (). For instance, this will produce the error:

>>> a = 5
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Class instances can also be called if they define a method __call__

One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0) instead of [0]

Use PHP composer to clone git repo

That package in fact is available through packagist. You don't need a custom repository definition in this case. Just make sure you add a require (which is always needed) with a matching version constraint.

In general, if a package is available on packagist, do not add a VCS repo. It will just slow things down.


For packages that are not available via packagist, use a VCS (or git) repository, as shown in your question. When you do, make sure that:

  • The "repositories" field is specified in the root composer.json (it's a root-only field, repository definitions from required packages are ignored)
  • The repositories definition points to a valid VCS repo
  • If the type is "git" instead of "vcs" (as in your question), make sure it is in fact a git repo
  • You have a require for the package in question
  • The constraint in the require matches the versions provided by the VCS repo. You can use composer show <packagename> to find the available versions. In this case ~2.3 would be a good option.
  • The name in the require matches the name in the remote composer.json. In this case, it is gedmo/doctrine-extensions.

Here is a sample composer.json that installs the same package via a VCS repo:

{
    "repositories": [
        {
            "url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
            "type": "git"
        }
    ],
    "require": {
        "gedmo/doctrine-extensions": "~2.3"
    }
}

The VCS repo docs explain all of this quite well.


If there is a git (or other VCS) repository with a composer.json available, do not use a "package" repo. Package repos require you to provide all of the metadata in the definition and will completely ignore any composer.json present in the provided dist and source. They also have additional limitations, such as not allowing for proper updates in most cases.

Avoid package repos (see also the docs).

Constant pointer vs Pointer to constant

Referncing from This Thread

Constant Pointers

Lets first understand what a constant pointer is. A constant pointer is a pointer that cannot change the address its holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable.

A constant pointer is declared as follows :
<type of pointer> * const <name of pointer>
An example declaration would look like :
int * const ptr;
Lets take a small code to illustrate these type of pointers :

#include<stdio.h>

int main(void)
{
    int var1 = 0, var2 = 0;
    int *const ptr = &var1;
    ptr = &var2;
    printf("%d\n", *ptr);

    return 0;
} 

In the above example :

  • We declared two variables var1 and var2
  • A constant pointer ‘ptr’ was declared and made to point var1
  • Next, ptr is made to point var2.
  • Finally, we try to print the value ptr is pointing to.

Pointer to Constant

As evident from the name, a pointer through which one cannot change the value of variable it points is known as a pointer to constant. These type of pointers can change the address they point to but cannot change the value kept at those address.

A pointer to constant is defined as : const <type of pointer>* <name of pointer> An example of definition could be : const int* ptr; Lets take a small code to illustrate a pointer to a constant :

 #include<stdio.h>

int main(void)
{
    int var1 = 0;
    const int* ptr = &var1;
    *ptr = 1;
    printf("%d\n", *ptr);

    return 0;
} 

In the code above :

  • We defined a variable var1 with value 0
  • we defined a pointer to a constant which points to variable var1
  • Now, through this pointer we tried to change the value of var1
  • Used printf to print the new value.

How to write std::string to file?

You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.

If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.

The following example reads one string from stdin, and then writes this string to the file output.txt.

#include <fstream>
#include <string>
#include <iostream>

int main()
{
    std::string input;
    std::cin >> input;
    std::ofstream out("output.txt");
    out << input;
    out.close();
    return 0;
}

Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.

For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/

Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:

write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

PHP cURL GET request and request's body

you have done it the correct way using

curl_setopt($ch, CURLOPT_POSTFIELDS,$body);

but i notice your missing

curl_setopt($ch, CURLOPT_POST,1);

Download a file by jQuery.Ajax

I have created little function as workaround solution (inspired by @JohnCulviner plugin):

// creates iframe and form in it with hidden field,
// then submit form with provided data
// url - form url
// data - data to form field
// input_name - form hidden input name

function ajax_download(url, data, input_name) {
    var $iframe,
        iframe_doc,
        iframe_html;

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                    " style='display: none' src='about:blank'></iframe>"
                   ).appendTo("body");
    }

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;
    }

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url +"'>" +
                  "<input type=hidden name='" + input_name + "' value='" +
                  JSON.stringify(data) +"'/></form>" +
                  "</body></html>";

    iframe_doc.open();
    iframe_doc.write(iframe_html);
    $(iframe_doc).find('form').submit();
}

Demo with click event:

$('#someid').on('click', function() {
    ajax_download('/download.action', {'para1': 1, 'para2': 2}, 'dataname');
});

Java method to sum any number of ints

public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
    int sum = 0; //start with 0
    for(int n : nums) { //this won't execute if no argument is passed
        sum += n; // this will repeat for all the arguments
    }
    return sum; //return the sum
} 

How to combine paths in Java?

I know its a long time since Jon's original answer, but I had a similar requirement to the OP.

By way of extending Jon's solution I came up with the following, which will take one or more path segments takes as many path segments that you can throw at it.

Usage

Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });

Code here for others with a similar problem

public class Path {
    public static String combine(String... paths)
    {
        File file = new File(paths[0]);

        for (int i = 1; i < paths.length ; i++) {
            file = new File(file, paths[i]);
        }

        return file.getPath();
    }
}

This compilation unit is not on the build path of a Java project

Add this to .project file

 <?xml version="1.0" encoding="UTF-8"?>
        <projectDescription>
            <name>framework</name>
            <comment></comment>
            <projects>
            </projects>
            <buildSpec>
                <buildCommand>
                    <name>org.eclipse.wst.common.project.facet.core.builder</name>
                    <arguments>
                    </arguments>
                </buildCommand>
                <buildCommand>
                    <name>org.eclipse.jdt.core.javabuilder</name>
                    <arguments>
                    </arguments>
                </buildCommand>
                <buildCommand>
                    <name>org.eclipse.m2e.core.maven2Builder</name>
                    <arguments>
                    </arguments>
                </buildCommand>
                <buildCommand>
                    <name>org.eclipse.wst.validation.validationbuilder</name>
                    <arguments>
                    </arguments>
                </buildCommand>
            </buildSpec>
            <natures>
                <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
                <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
                <nature>org.eclipse.jdt.core.javanature</nature>
                <nature>org.eclipse.m2e.core.maven2Nature</nature>
                <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
            </natures>
        </projectDescription>

How do I change Android Studio editor's background color?

You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

enter image description here

Android Studio 2.1

Preference -> Search for Appearance -> UI options , Click on DropDown Theme

enter image description here

Android 2.2

Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options

EDIT :

Import External Themes

You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

How can I merge two commits into one if I already started rebase?

If there are multiple commits, you can use git rebase -i to squash two commits into one.

If there are only two commits you want to merge, and they are the "most recent two", the following commands can be used to combine the two commits into one:

git reset --soft "HEAD^"
git commit --amend

Change the Bootstrap Modal effect

If you take a look at the bootstraps fade class used with the modal window you will find, that all it does, is to set the opacity value to 0 and adds a transition for the opacity rule.

Whenever you launch a modal the in class is added and will change the opacity to a value of 1.

Knowing that you can easily build your own fade-scale class.

Here is an example.

_x000D_
_x000D_
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");_x000D_
_x000D_
.fade-scale {_x000D_
  transform: scale(0);_x000D_
  opacity: 0;_x000D_
  -webkit-transition: all .25s linear;_x000D_
  -o-transition: all .25s linear;_x000D_
  transition: all .25s linear;_x000D_
}_x000D_
_x000D_
.fade-scale.in {_x000D_
  opacity: 1;_x000D_
  transform: scale(1);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- Button trigger modal -->_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
  Launch demo modal_x000D_
</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade-scale" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        ..._x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

-- UPDATE --

This answer is getting more up votes lately so i figured i add an update to show how easy it is to customize the BS modal in and out animations with the help of the great Animate.css library by
Daniel Eden.

All that needs to be done is to include the stylesheet to your <head></head> section. Now you simply need to add the animated class, plus one of the entrance classes of the library to the modal element.

<div class="modal animated fadeIn" id="myModal" tabindex="-1" role="dialog" ...>
  ...
</div>

But there is also a way to add an out animation to the modal window and since the library has a bunch of cool animations that will make an element disappear, why not use them. :)

To use them you will need to toggle the classes on the modal element, so it is actually better to call the modal window via JavaScript, which is described here.

You will also need to listen for some of the modal events to know when it's time to add or remove the classes from the modal element. The events being fired are described here.

To trigger a custom out animation you can't use the data-dismiss="modal" attribute on a button inside the modal window that's suppose to close the modal. You can simply add your own attribute like data-custom-dismiss="modal" and use that to call the $('selector').modal.('hide') method on it.

Here is an example that shows all the different possibilities.

_x000D_
_x000D_
/* -------------------------------------------------------_x000D_
| This first part can be ignored, it is just getting_x000D_
| all the different entrance and exit classes of the_x000D_
| animate-config.json file from the github repo._x000D_
--------------------------------------------------------- */_x000D_
_x000D_
var animCssConfURL = 'https://api.github.com/repos/daneden/animate.css/contents/animate-config.json';_x000D_
var selectIn = $('#animation-in-types');_x000D_
var selectOut = $('#animation-out-types');_x000D_
var getAnimCSSConfig = function ( url ) { return $.ajax( { url: url, type: 'get', dataType: 'json' } ) };_x000D_
var decode = function ( data ) {_x000D_
  var bin = Uint8Array.from( atob( data['content'] ), function( char ) { return char.charCodeAt( 0 ) } );_x000D_
  var bin2Str = String.fromCharCode.apply( null, bin );_x000D_
  return JSON.parse( bin2Str )_x000D_
}_x000D_
var buildSelect = function ( which, name, animGrp ) {_x000D_
  var grp = $('<optgroup></optgroup>');_x000D_
  grp.attr('label', name);_x000D_
  $.each(animGrp, function ( idx, animType ) {_x000D_
    var opt = $('<option></option>')_x000D_
    opt.attr('value', idx)_x000D_
    opt.text(idx)_x000D_
    grp.append(opt);_x000D_
  })_x000D_
  which.append(grp) _x000D_
}_x000D_
getAnimCSSConfig( animCssConfURL )_x000D_
  .done (function ( data ) {_x000D_
  var animCssConf = decode ( data );_x000D_
  $.each(animCssConf, function(name, animGrp) {_x000D_
    if ( /_entrances/.test(name) ) {_x000D_
      buildSelect(selectIn, name, animGrp);_x000D_
    }_x000D_
    if ( /_exits/.test(name) ) {_x000D_
      buildSelect(selectOut, name, animGrp);_x000D_
    }_x000D_
  })_x000D_
})_x000D_
_x000D_
_x000D_
/* -------------------------------------------------------_x000D_
| Here is were the fun begins._x000D_
--------------------------------------------------------- */_x000D_
_x000D_
var modalBtn = $('button');_x000D_
var modal = $('#myModal');_x000D_
var animInClass = "";_x000D_
var animOutClass = "";_x000D_
_x000D_
modalBtn.on('click', function() {_x000D_
  animInClass = selectIn.find('option:selected').val();_x000D_
  animOutClass = selectOut.find('option:selected').val();_x000D_
  if ( animInClass == '' || animOutClass == '' ) {_x000D_
    alert("Please select an in and out animation type.");_x000D_
  } else {_x000D_
    modal.addClass(animInClass);_x000D_
    modal.modal({backdrop: false});_x000D_
  }_x000D_
})_x000D_
_x000D_
modal.on('show.bs.modal', function () {_x000D_
  var closeModalBtns = modal.find('button[data-custom-dismiss="modal"]');_x000D_
  closeModalBtns.one('click', function() {_x000D_
    modal.on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function( evt ) {_x000D_
      modal.modal('hide')_x000D_
    });_x000D_
    modal.removeClass(animInClass).addClass(animOutClass);_x000D_
  })_x000D_
})_x000D_
_x000D_
modal.on('hidden.bs.modal', function ( evt ) {_x000D_
  var closeModalBtns = modal.find('button[data-custom-dismiss="modal"]');_x000D_
  modal.removeClass(animOutClass)_x000D_
  modal.off('webkitAnimationEnd oanimationend msAnimationEnd animationend')_x000D_
  closeModalBtns.off('click')_x000D_
})
_x000D_
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');_x000D_
@import url('https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css');_x000D_
_x000D_
select, button:not([data-custom-dismiss="modal"]) {_x000D_
  margin: 10px 0;_x000D_
  width: 220px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
      <select id="animation-in-types">_x000D_
        <option value="" selected>Choose animation-in type</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
      <select id="animation-out-types">_x000D_
        <option value="" selected>Choose animation-out type</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
      <button class="btn btn-default">Open Modal</button>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal animated" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-custom-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        ..._x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-custom-dismiss="modal">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

How to write a stored procedure using phpmyadmin and how to use it through php?

/*what is wrong with the following?*/
DELIMITER $$

CREATE PROCEDURE GetStatusDescr(
    in  pStatus char(1), 
    out pStatusDescr  char(10))
BEGIN 
    IF (pStatus == 'Y THEN
 SET pStatusDescr = 'Active';
    ELSEIF (pStatus == 'N') THEN
        SET pStatusDescr = 'In-Active';
    ELSE
        SET pStatusDescr = 'Unknown';
    END IF;

END$$

How to increment a pointer address and pointer's value?

First, the ++ operator takes precedence over the * operator, and the () operators take precedence over everything else.

Second, the ++number operator is the same as the number++ operator if you're not assigning them to anything. The difference is number++ returns number and then increments number, and ++number increments first and then returns it.

Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array.

So, to sum it all up:

ptr++;    // Pointer moves to the next int position (as if it was an array)
++ptr;    // Pointer moves to the next int position (as if it was an array)
++*ptr;   // The value of ptr is incremented
++(*ptr); // The value of ptr is incremented
++*(ptr); // The value of ptr is incremented
*ptr++;   // Pointer moves to the next int position (as if it was an array). But returns the old content
(*ptr)++; // The value of ptr is incremented
*(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content
*++ptr;   // Pointer moves to the next int position, and then get's accessed, with your code, segfault
*(++ptr); // Pointer moves to the next int position, and then get's accessed, with your code, segfault

As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.

EDIT:

So I was wrong, the precedence is a little more complicated than what I wrote, view it here: http://en.cppreference.com/w/cpp/language/operator_precedence

How can I find my php.ini on wordpress?

I used this, very cool tool

https://wordpress.org/plugins/php-settings/

This plugin provides a simple user interface with a code editor to edit your local .ini settings.

This can be used to change settings like upload_max_filesize or max_execution_time which are often set to very low values by the hosting companies.

Disable eslint rules for folder

To ignore some folder from eslint rules we could create the file .eslintignore in root directory and add there the path to the folder we want omit (the same way as for .gitignore).

Here is the example from the ESLint docs on Ignoring Files and Directories:

# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default

# Ignore built files except build/index.js
build/*
!build/index.js

Parsing JSON in Java without knowing JSON format

If a different library is fine for you, you could try org.json:

JSONObject object = new JSONObject(myJSONString);
String[] keys = JSONObject.getNames(object);

for (String key : keys)
{
    Object value = object.get(key);
    // Determine type of value and do something with it...
}

Correct set of dependencies for using Jackson mapper

I spent few hours on this.

Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project

Angular 2 TypeScript how to find element in Array

from TypeScript you can use native JS array filter() method:

let filteredElements=array.filter(element => element.field == filterValue);

it returns an array with only matching elements from the original array (0, 1 or more)

Reference: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Advantage of switch over if-else statement

Compiler will optimise it anyway - go for the switch as it's the most readable.

How to check for an active Internet connection on iOS or macOS?

If you're using AFNetworking you can use its own implementation for internet reachability status.

The best way to use AFNetworking is to subclass the AFHTTPClient class and use this class to do your network connections.

One of the advantages of using this approach is that you can use blocks to set the desired behavior when the reachability status changes. Supposing that I've created a singleton subclass of AFHTTPClient (as said on the "Subclassing notes" on AFNetworking docs) named BKHTTPClient, I'd do something like:

BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
    if (status == AFNetworkReachabilityStatusNotReachable) 
    {
    // Not reachable
    }
    else
    {
        // Reachable
    }
}];

You could also check for Wi-Fi or WLAN connections specifically using the AFNetworkReachabilityStatusReachableViaWWAN and AFNetworkReachabilityStatusReachableViaWiFi enums (more here).

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

var app = angular.module('modx', []);

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

How to auto adjust table td width from the content

Remove all widths set using CSS and set white-space to nowrap like so:

.content-loader tr td {
    white-space: nowrap;
}

I would also remove the fixed width from the container (or add overflow-x: scroll to the container) if you want the fields to display in their entirety without it looking odd...

See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp

Change select box option background color

Yes, you can set this by the opposite way:

select { /* desired background */ }
option:not(:checked) { background: #fff; }

Check it working bellow:

_x000D_
_x000D_
select {
  margin: 50px;
  width: 300px;
  background: #ff0;
  color: #000;
}

option:not(:checked) {
  background-color: #fff;
}
_x000D_
<select>
  <option val="">Select Option</option>
  <option val="1">Option 1</option>
  <option val="2">Option 2</option>
  <option val="3">Option 3</option>
  <option val="4">Option 4</option>
</select>
_x000D_
_x000D_
_x000D_

How do I parse a string to a float or int?

Pass your string to this function:

def string_to_number(str):
  if("." in str):
    try:
      res = float(str)
    except:
      res = str  
  elif(str.isdigit()):
    res = int(str)
  else:
    res = str
  return(res)

It will return int, float or string depending on what was passed.

string that is an int

print(type(string_to_number("124")))
<class 'int'>

string that is a float

print(type(string_to_number("12.4")))
<class 'float'>

string that is a string

print(type(string_to_number("hello")))
<class 'str'>

string that looks like a float

print(type(string_to_number("hel.lo")))
<class 'str'>

Extract code country from phone number [libphonenumber]

In here you can save the phone number as international formatted phone number

internationalFormatPhoneNumber = phoneUtil.format(givenPhoneNumber, PhoneNumberFormat.INTERNATIONAL);

it return the phone number as International format +94 71 560 4888

so now I have get country code as this

String countryCode = internationalFormatPhoneNumber.substring(0,internationalFormatPhoneNumber.indexOf('')).replace('+', ' ').trim();

Hope this will help you

MySql server startup error 'The server quit without updating PID file '

For me the solution was to override/correct the data directory in /etc/my/cnf.

I built MySQL 5.5.27 from source with the directions provided in the readme file:


# Preconfiguration setup
shell> groupadd mysql
shell> useradd -r -g mysql mysql
# Beginning of source-build specific instructions
shell> tar zxvf mysql-VERSION.tar.gz
shell> cd mysql-VERSION
shell> cmake .
shell> make
shell> make install
# End of source-build specific instructions

# Postinstallation setup
shell> cd /usr/local/mysql
shell> chown -R mysql .
shell> chgrp -R mysql .
shell> scripts/mysql_install_db --user=mysql
shell> chown -R root .
shell> chown -R mysql data

# Next command is optional
shell> cp support-files/my-medium.cnf /etc/my.cnf
shell> bin/mysqld_safe --user=mysql &

# Next command is optional
shell> cp support-files/mysql.server /etc/init.d/mysql.server

mysqld_safe terminated itself without explanation. running /etc/init.d/mysql.server start resulted in the error:

"The server quit without updating PID file"

I noticed something odd in the installation instructions though. It has ownership changed to mysql for the directory "data", but not to "var"; this is unusual because for years I have had to ensure that var directory was mysql writable. So I manually ran chown -R mysql /usr/local/mysql/var and then attempted to start it again. Still no luck. But worse, no .err file in the var dir - it was in the "data" dir! so scripts/mysql_install_db sets up camp in /usr/local/mysql/var, but the rest of the application seems to want to do its work in /usr/local/mysql/data!

So I just edited /etc/my.cnf and under the section [mysqld] I added a directive to explicitly point mysql's data directory to var (as I normally expect it to be any how), and after doing so, mysqld starts up just fine. The directive to add looks like this:

datadir = /usr/local/mysql/var

Worked for me. Hope it helps for you.

Drawing circles with System.Drawing

     private void DrawEllipseRectangle(PaintEventArgs e)
        {
            Pen p = new Pen(Color.Black, 3);
            Rectangle r = new Rectangle(100, 100, 100, 100);
            e.Graphics.DrawEllipse(p, r);
        }
     private void Form1_Paint(object sender, PaintEventArgs e)
        {
            DrawEllipseRectangle(e);
        }

How to connect to Oracle 11g database remotely

Its quite easy on computer a you don't need to do anything just make sure both system are on same network if its not internet access(for this you need static ip). Okay now on computer b go to start menu find configuration under oracle folder click Net Configuration Assistant under that folder when window pop up click Local net configuration option it must be third option.

Now click add and click next in next screen it will ask service name here you need to add oracle global database name of computer A(Normally I use oracle86 for my installation) now click next next screen choose protocol normally its tcp click next in host name enter computer A's name you can found that in my computer properties. Click next don't change port untill you have changed that in Computer A click next and choose test connection now here you can check your connection working or not if the error is username and password not correct then click login credential button and fill correct username and password. If its saying unable to reach computer ot target not found than you must add exception in firewall for 1521 port or just disable firewall on computer A.

Javascript: How to loop through ALL DOM elements on a page?

Use *

var allElem = document.getElementsByTagName("*");
for (var i = 0; i < allElem.length; i++) {
    // Do something with all element here
}

How to run mysql command on bash?

I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.

#!/bin/bash
    PROPERTY_FILE=filename.properties

    function getProperty {
       PROP_KEY=$1
       PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
       echo $PROP_VALUE
    }

    echo "# Reading property from $PROPERTY_FILE"
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    ROOT_LOC=$(getProperty "root.location")
    echo $DB_USER
    echo $DB_PASS
    echo $ROOT_LOC
    echo "Writing on DB ... "
    mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL

    update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
    EOFMYSQL
    echo "Writing root location($ROOT_LOC) is done ... "
    counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;

    if [ "$counter" = "1" ]
    then
    echo "ROOT location updated"
    fi

how to access iFrame parent page using jquery?

There are multiple ways to do these.

I) Get main parent directly.

for exa. i want to replace my child page to iframe then

var link = '<%=Page.ResolveUrl("~/Home/SubscribeReport")%>';
top.location.replace(link);

here top.location gets parent directly.

II) get parent one by one,

var element = $('.iframe:visible', window.parent.document);

here if you have more then one iframe, then specify active or visible one.

you also can do like these for getting further parents,

var masterParent = element.parent().parent().parent()

III) get parent by Identifier.

var myWindow = window.top.$("#Identifier")

What is the difference between Scrum and Agile Development?

At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".

In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.

So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.

href overrides ng-click in Angular.js

I don't think you need to remove "#" from href. Following works with Angularjs 1.2.10

<a href="#/" ng-click="logout()">Logout</a>

HTTP Basic Authentication - what's the expected web browser experience?

To help everyone avoid confusion, I will reformulate the question in two parts.

First : "how can make an authenticated HTTP request with a browser, using BASIC auth?".

In the browser you can do a http basic auth first by waiting the prompt to come, or by editing the URL if you follow this format: http://myusername:[email protected]

NB: the curl command mentionned in the question is perfectly fine, if you have a command-line and curl installed. ;)

References:

Also according to the CURL manual page https://curl.haxx.se/docs/manual.html

HTTP

  Curl also supports user and password in HTTP URLs, thus you can pick a file
  like:

      curl http://name:[email protected]/full/path/to/file

  or specify user and password separately like in

      curl -u name:passwd http://machine.domain/full/path/to/file

  HTTP offers many different methods of authentication and curl supports
  several: Basic, Digest, NTLM and Negotiate (SPNEGO). Without telling which
  method to use, curl defaults to Basic. You can also ask curl to pick the
  most secure ones out of the ones that the server accepts for the given URL,
  by using --anyauth.

  NOTE! According to the URL specification, HTTP URLs can not contain a user
  and password, so that style will not work when using curl via a proxy, even
  though curl allows it at other times. When using a proxy, you _must_ use
  the -u style for user and password.

The second and real question is "However, on somesite.com, I'm not getting an authorization prompt at all, just a page that says I'm not authorized. Did somesite not implement the Basic Auth workflow correctly, or is there something else I need to do?"

The curl documentation says the -u option supports many method of authentication, Basic being the default.

Observable Finally on Subscribe

I'm now using RxJS 5.5.7 in an Angular application and using finalize operator has a weird behavior for my use case since is fired before success or error callbacks.

Simple example:

// Simulate an AJAX callback...
of(null)
  .pipe(
    delay(2000),
    finalize(() => {
      // Do some work after complete...
      console.log('Finalize method executed before "Data available" (or error thrown)');
    })
  )
  .subscribe(
      response => {
        console.log('Data available.');
      },
      err => {
        console.error(err);
      }
  );

I have had to use the add medhod in the subscription to accomplish what I want. Basically a finally callback after the success or error callbacks are done. Like a try..catch..finally block or Promise.finally method.

Simple example:

// Simulate an AJAX callback...
of(null)
  .pipe(
    delay(2000)
  )
  .subscribe(
      response => {
        console.log('Data available.');
      },
      err => {
        console.error(err);
      }
  );
  .add(() => {
    // Do some work after complete...
    console.log('At this point the success or error callbacks has been completed.');
  });

Doctrine - How to print out the real sql, not just the prepared statement?

Doctrine is not sending a "real SQL query" to the database server : it is actually using prepared statements, which means :

  • Sending the statement, for it to be prepared (this is what is returned by $query->getSql())
  • And, then, sending the parameters (returned by $query->getParameters())
  • and executing the prepared statements

This means there is never a "real" SQL query on the PHP side — so, Doctrine cannot display it.

Android Studio: Gradle: error: cannot find symbol variable

Another alternative to @TouchBoarder's answer above is that you may also have two layout files with the same name but for different api versions. You should delete the older my_file.xml file

my_file.xml
my_file.xml(v21)

How do I get the App version and build number using Swift?

Swift 3:

Version Number

if let versionNumberString = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { // do something }

Build number

if let buildNumberString = Bundle.main.infoDictionary?["CFBundleVersion"] as? String { // do something }

How to get the size of a string in Python?

If you are talking about the length of the string, you can use len():

>>> s = 'please answer my question'
>>> len(s)  # number of characters in s
25

If you need the size of the string in bytes, you need sys.getsizeof():

>>> import sys
>>> sys.getsizeof(s)
58

Also, don't call your string variable str. It shadows the built-in str() function.

How do I find out my root MySQL password?

sudo mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YOUR_PASSWORD_HERE';
FLUSH PRIVILEGES;

mysql -u root -p # and it works

How to export specific request to file using postman?

  1. Click on the "Code" button upright of the request page.
  2. From the opened window select cURL.
  3. Copy and share the generated code.

enter image description here

You can use this curl request to import it into Postman.

Is there a difference between PhoneGap and Cordova commands?

This first choice might be a confusing one but it’s really very simple. PhoneGap is a product owned by Adobe which currently includes additional build services, and it may or may not eventually offer additional services and/or charge payments for use in the future. Cordova is owned and maintained by Apache, and will always be maintained as an open source project. Currently they both have a very similar API. I would recommend going with Cordova, unless you require the additional PhoneGap build services.

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

For me it was enough to use

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime StartDate { set; get; }

How do I disable log messages from the Requests library?

I found out how to configure requests's logging level, it's done via the standard logging module. I decided to configure it to not log messages unless they are at least warnings:

import logging

logging.getLogger("requests").setLevel(logging.WARNING)

If you wish to apply this setting for the urllib3 library (typically used by requests) too, add the following:

logging.getLogger("urllib3").setLevel(logging.WARNING)

Is the ternary operator faster than an "if" condition in Java

For the example given, I prefer the ternary or condition operator (?) for a specific reason: I can clearly see that assigning a is not optional. With a simple example, it's not too hard to scan the if-else block to see that a is assigned in each clause, but imagine several assignments in each clause:

if (i == 0)
{
    a = 10;
    b = 6;
    c = 3;
}
else
{
    a = 5;
    b = 4;
    d = 1;
}

a = (i == 0) ? 10 : 5;
b = (i == 0) ? 6  : 4;
c = (i == 0) ? 3  : 9;
d = (i == 0) ? 12 : 1;

I prefer the latter so that you know you haven't missed an assignment.

Class has no initializers Swift

My answer addresses the error in general and not the exact code of the OP. No answer mentioned this note so I just thought I add it.

The code below would also generate the same error:

class Actor {
    let agent : String? // BAD! // Its value is set to nil, and will always be nil and that's stupid so Xcode is saying not-accepted.  
    // Technically speaking you have a way around it, you can help the compiler and enforce your value as a constant. See Option3
}

Others mentioned that Either you create initializers or you make them optional types, using ! or ? which is correct. However if you have an optional member/property, that optional should be mutable ie var. If you make a let then it would never be able to get out of its nil state. That's bad!

So the correct way of writing it is:

Option1

class Actor {
    var agent : String? // It's defaulted to `nil`, but also has a chance so it later can be set to something different || GOOD!
}

Or you can write it as:

Option2

class Actor {
let agent : String? // It's value isn't set to nil, but has an initializer || GOOD!

init (agent: String?){
    self.agent = agent // it has a chance so its value can be set!
    }
}

or default it to any value (including nil which is kinda stupid)

Option3

class Actor {
let agent : String? = nil // very useless, but doable.
let company: String? = "Universal" 
}

If you are curious as to why let (contrary to var) isn't initialized to nil then read here and here

Assets file project.assets.json not found. Run a NuGet package restore

Select Tools > NuGet Package Manager > Package Manager Console

And then Run:

dotnet restore <project or solution name>

WSDL validator?

You can try using one of their tools: http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools

These will check both WSDL validity and Basic Profile 1.1 compliance.

How to implement LIMIT with SQL Server?

This is a multi step approach that will work in SQL2000.

-- Create a temp table to hold the data
CREATE TABLE #foo(rowID int identity(1, 1), myOtherColumns)

INSERT INTO #foo (myColumns) SELECT myData order By MyCriteria

Select * FROM #foo where rowID > 10

Eclipse executable launcher error: Unable to locate companion shared library

Problem happened when I unzipped using Cygwin. Used the Windows XP standard unzip program and it worked.

How to concatenate properties from multiple JavaScript objects

Simplest: spread operators

var obj1 = {a: 1}
var obj2 = {b: 2}
var concat = { ...obj1, ...obj2 } // { a: 1, b: 2 }

@Autowired - No qualifying bean of type found for dependency at least 1 bean

In your controller class, just add @ComponentScan("package") annotation. In my case the package name is com.shoppingcart.So i wrote the code as @ComponentScan("com.shoppingcart") and it worked for me.

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I had this problem for our FSharp targets (FSharpTargetsPath was empty).

Many of the paths are built with reference to the VS version.

For various reasons, our build runs with system privileges, and the environment variable "VisualStudioVersion" was only set (by the VS 2013 installer) at the "user" level - which is fair enough.

Ensure that the "VisualStudioVersion" environment variable is set to "12.0" at the level (System or User) that you are running at.

Understanding Linux /proc/id/maps

Each row in /proc/$PID/maps describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:

address           perms offset  dev   inode   pathname
08048000-08056000 r-xp 00000000 03:0c 64593   /usr/sbin/gpm
  • address - This is the starting and ending address of the region in the process's address space
  • permissions - This describes how pages in the region can be accessed. There are four different permissions: read, write, execute, and shared. If read/write/execute are disabled, a - will appear instead of the r/w/x. If a region is not shared, it is private, so a p will appear instead of an s. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect system call.
  • offset - If the region was mapped from a file (using mmap), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.
  • device - If the region was mapped from a file, this is the major and minor device number (in hex) where the file lives.
  • inode - If the region was mapped from a file, this is the file number.
  • pathname - If the region was mapped from a file, this is the name of the file. This field is blank for anonymous mapped regions. There are also special regions with names like [heap], [stack], or [vdso]. [vdso] stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"

You might notice a lot of anonymous regions. These are usually created by mmap but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.

C# string does not contain possible?

So you can utilize short-circuiting:

bool containsBoth = compareString.Contains(firstString) && 
                    compareString.Contains(secondString);

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

AngularJS Directive Restrict A vs E

2 problems with elements:

  1. Bad support with old browsers.
  2. SEO - Google's engine doesn't like them.

Use Attributes.

How do I set session timeout of greater than 30 minutes

Setting session timeout through the deployment descriptor should work - it sets the default session timeout for the web app. Calling session.setMaxInactiveInterval() sets the timeout for the particular session it is called on, and overrides the default. Be aware of the unit difference, too - the deployment descriptor version uses minutes, and session.setMaxInactiveInterval() uses seconds.

So

<session-config>
    <session-timeout>60</session-timeout>
</session-config>

sets the default session timeout to 60 minutes.

And

session.setMaxInactiveInterval(600);

sets the session timeout to 600 seconds - 10 minutes - for the specific session it's called on.

This should work in Tomcat or Glassfish or any other Java web server - it's part of the spec.

MySQL vs MySQLi when using PHP

There is a manual page dedicated to help choosing between mysql, mysqli and PDO at

The PHP team recommends mysqli or PDO_MySQL for new development:

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

The page also has a feature matrix comparing the extension APIs. The main differences between mysqli and mysql API are as follows:

                               mysqli     mysql
Development Status             Active     Maintenance only
Lifecycle                      Active     Long Term Deprecation Announced*
Recommended                    Yes        No
OOP API                        Yes        No
Asynchronous Queries           Yes        No
Server-Side Prep. Statements   Yes        No
Stored Procedures              Yes        No
Multiple Statements            Yes        No
Transactions                   Yes        No
MySQL 5.1+ functionality       Yes        No

* http://news.php.net/php.internals/53799

There is an additional feature matrix comparing the libraries (new mysqlnd versus libmysql) at

and a very thorough blog article at

How do I get a Cron like scheduler in Python?

Another trivial solution would be:

from aqcron import At
from time import sleep
from datetime import datetime

# Event scheduling
event_1 = At( second=5 )
event_2 = At( second=[0,20,40] )

while True:
    now = datetime.now()

    # Event check
    if now in event_1: print "event_1"
    if now in event_2: print "event_2"

    sleep(1)

And the class aqcron.At is:

# aqcron.py

class At(object):
    def __init__(self, year=None,    month=None,
                 day=None,     weekday=None,
                 hour=None,    minute=None,
                 second=None):
        loc = locals()
        loc.pop("self")
        self.at = dict((k, v) for k, v in loc.iteritems() if v != None)

    def __contains__(self, now):
        for k in self.at.keys():
            try:
                if not getattr(now, k) in self.at[k]: return False
            except TypeError:
                if self.at[k] != getattr(now, k): return False
        return True

Google API authentication: Not valid origin for the client

Credentials do not work if API is not enabled. In my case the next steps were needed:

  1. Go to https://console.developers.google.com/apis/library
  2. Enter 'People'
  3. From the result choose 'Google People API'
  4. Click 'Enable'

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

Html.Label gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression):

// Model
public string Test { get; set; }

// View
@Html.Label("Test")

// Output
<label for="Test">Test</label>

Html.LabelFor gives you a label for the property represented by the provided expression (typically a model property):

// Model
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

// View
@model MyModel
@Html.LabelFor(m => m.Test)

// Output
<label for="Test">A property</label>

Html.LabelForModel is a bit trickier. It returns a label whose for value is that of the parameter represented by the model object. This is useful, in particular, for custom editor templates. For example:

// Model
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

// Main view
@Html.EditorFor(m => m.Test)

// Inside editor template
@Html.LabelForModel()

// Output
<label for="Test">A property</label>

How do I create a ListView with rounded corners in Android?

Here is one way of doing it (Thanks to Android Documentation though!):

Add the following into a file (say customshape.xml) and then place it in (res/drawable/customshape.xml)

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
     <gradient 
         android:startColor="#SomeGradientBeginColor"
         android:endColor="#SomeGradientEndColor" 
         android:angle="270"/> 

    <corners 
         android:bottomRightRadius="7dp" 
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp" 
         android:topRightRadius="7dp"/> 
</shape> 

Once you are done with creating this file, just set the background in one of the following ways:

Through Code: listView.setBackgroundResource(R.drawable.customshape);

Through XML, just add the following attribute to the container (ex: LinearLayout or to any fields):

android:background="@drawable/customshape"

Hope someone finds it useful...

How do I get the current timezone name in Postgres 9.3?

It seems to work fine in Postgresql 9.5:

SELECT current_setting('TIMEZONE');

Combine [NgStyle] With Condition (if..else)

[ngStyle] with condition based if and else case.

<label for="file" [ngStyle]="isPreview ? {'cursor': 'default'} : {'cursor': 'pointer'}">Attachment

What does template <unsigned int N> mean?

Yes, it is a non-type parameter. You can have several kinds of template parameters

  • Type Parameters.
    • Types
    • Templates (only classes and alias templates, no functions or variable templates)
  • Non-type Parameters
    • Pointers
    • References
    • Integral constant expressions

What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:

Template type parameter:

template<typename T>
struct Container {
    T t;
};

// pass type "long" as argument.
Container<long> test;

Template integer parameter:

template<unsigned int S>
struct Vector {
    unsigned char bytes[S];
};

// pass 3 as argument.
Vector<3> test;

Template pointer parameter (passing a pointer to a function)

template<void (*F)()>
struct FunctionWrapper {
    static void call_it() { F(); }
};

// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;

Template reference parameter (passing an integer)

template<int &A>
struct SillyExample {
    static void do_it() { A = 10; }
};

// pass flag as argument
int flag;
SillyExample<flag> test;

Template template parameter.

template<template<typename T> class AllocatePolicy>
struct Pool {
    void allocate(size_t n) {
        int *p = AllocatePolicy<int>::allocate(n);
    }
};

// pass the template "allocator" as argument. 
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;

A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:

template<unsigned int SIZE = 3>
struct Vector {
    unsigned char buffer[SIZE];
};

Vector<> test;

Syntactically, template<> is reserved to mark an explicit template specialization, instead of a template without parameters:

template<>
struct Vector<3> {
    // alternative definition for SIZE == 3
};

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

The answer here is not clear, so I wanted to add more detail.

Using the link provided above, I performed the following step.

In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.

This information is available at the link the OP posted in the Answer.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

I was now able to find reason behind the error guys. It's on the webhosting site settings not on my app pool or what so ever. I changed the asp.net version from 2.0 to 4.0 but I forgot to click the update button. I feel so embarrased. :( I've been struggling for days to fix this error and only to found out its on the webhosting site settings. GgrrRR.. As of now I'm facing new error but has nothing to do with this question. Anyway thanks guys for your efforts to help me. :)

Javascript split regex question

Say your string is:

let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;

You want to split the string by the following delimiters:

  • Colon
  • Semicolon
  • New line

You could split the string like this:

let rawElements = str.split(new RegExp('[,;\n]', 'g'));

Finally, you may need to trim the elements in the array:

let elements = rawElements.map(element => element.trim());

How to setup Main class in manifest file in jar produced by NetBeans project

Adding manifest.file=manifest.mf into project.properties and creating manifest.mf file in the project directory works fine in NB 6.9 and should work also in NB 6.8.

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Make sure Anonymous access is enabled on IIS -> Authentication.

But also right click on it, then click on Edit, and choose a domain\username and password. (With access to the physical folder of the application).

How can I check whether an array is null / empty?

There's a key difference between a null array and an empty array. This is a test for null.

int arr[] = null;
if (arr == null) {
  System.out.println("array is null");
}

"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:

arr = new int[0];
if (arr.length == 0) {
  System.out.println("array is empty");
}

An alternative definition of "empty" is if all the elements are null:

Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
  if (arr[i] != null) {
    empty = false;
    break;
  }
}

or

Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
  if (ob != null) {
    empty = false;
    break;
  }
}

EnterKey to press button in VBA Userform

This one worked for me

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = 13 Then
             Button1_Click
        End If
End Sub

Alter MySQL table to add comments on columns

You can use MODIFY COLUMN to do this. Just do...

ALTER TABLE YourTable
MODIFY COLUMN your_column
your_previous_column_definition COMMENT "Your new comment"

substituting:

  • YourTable with the name of your table
  • your_column with the name of your comment
  • your_previous_column_definition with the column's column_definition, which I recommend getting via a SHOW CREATE TABLE YourTable command and copying verbatim to avoid any traps.*
  • Your new comment with the column comment you want.

For example...

mysql> CREATE TABLE `Example` (
    ->   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    ->   `some_col` varchar(255) DEFAULT NULL,
    ->   PRIMARY KEY (`id`)
    -> );
Query OK, 0 rows affected (0.18 sec)

mysql> ALTER TABLE Example
    -> MODIFY COLUMN `id`
    -> int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Look, I''m a comment!';
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE Example;
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                                                                                                                  |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Example | CREATE TABLE `Example` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Look, I''m a comment!',
  `some_col` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

* Whenever you use MODIFY or CHANGE clauses in an ALTER TABLE statement, I suggest you copy the column definition from the output of a SHOW CREATE TABLE statement. This protects you from accidentally losing an important part of your column definition by not realising that you need to include it in your MODIFY or CHANGE clause. For example, if you MODIFY an AUTO_INCREMENT column, you need to explicitly specify the AUTO_INCREMENT modifier again in the MODIFY clause, or the column will cease to be an AUTO_INCREMENT column. Similarly, if the column is defined as NOT NULL or has a DEFAULT value, these details need to be included when doing a MODIFY or CHANGE on the column or they will be lost.

Use CSS3 transitions with gradient backgrounds

Gradients don't support transitions yet (although the current spec says they should support like gradient to like gradient transitions via interpolation.).

If you want a fade-in effect with a background gradient, you have to set an opacity on a container element and 'transition` the opacity.

(There have been some browser releases that supported transitions on gradients (e.g IE10. I tested gradient transitions in 2016 in IE and they seemed to work at the time, but my test code no longer works.)

Update: October 2018 Gradient transitions with un-prefixed new syntax [e.g. radial-gradient(...)]now confirmed to work (again?) on Microsoft Edge 17.17134. I don't know when this was added. Still not working on latest Firefox & Chrome / Windows 10.

How do I check to see if a value is an integer in MySQL?

Match it against a regular expression.

c.f. http://forums.mysql.com/read.php?60,1907,38488#msg-38488 as quoted below:

Re: IsNumeric() clause in MySQL??
Posted by: kevinclark ()
Date: August 08, 2005 01:01PM


I agree. Here is a function I created for MySQL 5:

CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint
RETURN sIn REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';


This allows for an optional plus/minus sign at the beginning, one optional decimal point, and the rest numeric digits.

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

Another possible solution is to completely reset the settings. This is what fixed it for me:

Tools->Import and Export settings->Reset all settings.

How do I include a pipe | in my linux find -exec command?

You can also pipe to a while loop that can do multiple actions on the file which find locates. So here is one for looking in jar archives for a given java class file in folder with a large distro of jar files

find /usr/lib/eclipse/plugins -type f -name \*.jar | while read jar; do echo $jar; jar tf $jar | fgrep IObservableList ; done

the key point being that the while loop contains multiple commands referencing the passed in file name separated by semicolon and these commands can include pipes. So in that example I echo the name of the matching file then list what is in the archive filtering for a given class name. The output looks like:

/usr/lib/eclipse/plugins/org.eclipse.core.contenttype.source_3.4.1.R35x_v20090826-0451.jar /usr/lib/eclipse/plugins/org.eclipse.core.databinding.observable_1.2.0.M20090902-0800.jar org/eclipse/core/databinding/observable/list/IObservableList.class /usr/lib/eclipse/plugins/org.eclipse.search.source_3.5.1.r351_v20090708-0800.jar /usr/lib/eclipse/plugins/org.eclipse.jdt.apt.core.source_3.3.202.R35x_v20091130-2300.jar /usr/lib/eclipse/plugins/org.eclipse.cvs.source_1.0.400.v201002111343.jar /usr/lib/eclipse/plugins/org.eclipse.help.appserver_3.1.400.v20090429_1800.jar

in my bash shell (xubuntu10.04/xfce) it really does make the matched classname bold as the fgrep highlights the matched string; this makes it really easy to scan down the list of hundreds of jar files that were searched and easily see any matches.

on windows you can do the same thing with:

for /R %j in (*.jar) do @echo %j & @jar tf %j | findstr IObservableList

note that in that on windows the command separator is '&' not ';' and that the '@' suppresses the echo of the command to give a tidy output just like the linux find output above; although findstr is not make the matched string bold so you have to look a bit closer at the output to see the matched class name. It turns out that the windows 'for' command knows quite a few tricks such as looping through text files...

enjoy

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

%i or %d to print integer in C using printf()?

I am just adding example here because I think examples make it easier to understand.

In printf() they behave identically so you can use any either %d or %i. But they behave differently in scanf().

For example:

int main()
{
    int num,num2;
    scanf("%d%i",&num,&num2);// reading num using %d and num2 using %i

    printf("%d\t%d",num,num2);
    return 0;
}

Output:

enter image description here

You can see the different results for identical inputs.

num:

We are reading num using %d so when we enter 010 it ignores the first 0 and treats it as decimal 10.

num2:

We are reading num2 using %i.

That means it will treat decimals, octals, and hexadecimals differently.

When it give num2 010 it sees the leading 0 and parses it as octal.

When we print it using %d it prints the decimal equivalent of octal 010 which is 8.

ValueError: object too deep for desired array while using convolution

np.convolve needs a flattened array as one of it's inputs, you can use numpy.ndarray.flatten() which is quite fast, find it here.

How to pass integer from one Activity to another?

In Activity A

private void startSwitcher() {
    int yourInt = 200;
    Intent myIntent = new Intent(A.this, B.class);
    intent.putExtra("yourIntName", yourInt);
    startActivity(myIntent);
}

in Activity B

int score = getIntent().getIntExtra("yourIntName", 0);

How to find the Number of CPU Cores via .NET/C#?

From .NET Framework source

You can also get it with PInvoke on Kernel32.dll

The following code is coming more or less from SystemInfo.cs from System.Web source located here:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SYSTEM_INFO
{
  public ushort wProcessorArchitecture;
  public ushort wReserved;
  public uint dwPageSize;
  public IntPtr lpMinimumApplicationAddress;
  public IntPtr lpMaximumApplicationAddress;
  public IntPtr dwActiveProcessorMask;
  public uint dwNumberOfProcessors;
  public uint dwProcessorType;
  public uint dwAllocationGranularity;
  public ushort wProcessorLevel;
  public ushort wProcessorRevision;
}

internal static class SystemInfo 
{
    static int _trueNumberOfProcessors;
    internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);    

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    internal static extern void GetSystemInfo(out SYSTEM_INFO si);

    [DllImport("kernel32.dll")]
    internal static extern int GetProcessAffinityMask(IntPtr handle, out IntPtr processAffinityMask, out IntPtr systemAffinityMask);

    internal static int GetNumProcessCPUs()
    {
      if (SystemInfo._trueNumberOfProcessors == 0)
      {
        SYSTEM_INFO si;
        GetSystemInfo(out si);
        if ((int) si.dwNumberOfProcessors == 1)
        {
          SystemInfo._trueNumberOfProcessors = 1;
        }
        else
        {
          IntPtr processAffinityMask;
          IntPtr systemAffinityMask;
          if (GetProcessAffinityMask(INVALID_HANDLE_VALUE, out processAffinityMask, out systemAffinityMask) == 0)
          {
            SystemInfo._trueNumberOfProcessors = 1;
          }
          else
          {
            int num1 = 0;
            if (IntPtr.Size == 4)
            {
              uint num2 = (uint) (int) processAffinityMask;
              while ((int) num2 != 0)
              {
                if (((int) num2 & 1) == 1)
                  ++num1;
                num2 >>= 1;
              }
            }
            else
            {
              ulong num2 = (ulong) (long) processAffinityMask;
              while ((long) num2 != 0L)
              {
                if (((long) num2 & 1L) == 1L)
                  ++num1;
                num2 >>= 1;
              }
            }
            SystemInfo._trueNumberOfProcessors = num1;
          }
        }
      }
      return SystemInfo._trueNumberOfProcessors;
    }
}

Make WPF Application Fullscreen (Cover startmenu)

You can also do it at run time as follows :

  • Assign name to the window (x:Name = "HomePage")
  • In constructor just set WindowState property to Maximized as follows

HomePage.WindowState = WindowState.Maximized;

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Give Safe User Permission To Use Port 80

Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/

Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port - where port number > 1024.

A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``

Now, when you tell a Node application that you want it to run on port 80, it will not complain.

Check this reference link

htaccess redirect all pages to single page

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
RewriteRule ^(.*)$ "http://www.thenewdomain.com/" [R=301,L]

How can I simulate a click to an anchor tag?

Here is a complete test case that simulates the click event, calls all handlers attached (however they have been attached), maintains the "target" attribute ("srcElement" in IE), bubbles like a normal event would, and emulates IE's recursion-prevention. Tested in FF 2, Chrome 2.0, Opera 9.10 and of course IE (6):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function fakeClick(event, anchorObj) {
  if (anchorObj.click) {
    anchorObj.click()
  } else if(document.createEvent) {
    if(event.target !== anchorObj) {
      var evt = document.createEvent("MouseEvents"); 
      evt.initMouseEvent("click", true, true, window, 
          0, 0, 0, 0, 0, false, false, false, false, 0, null); 
      var allowDefault = anchorObj.dispatchEvent(evt);
      // you can check allowDefault for false to see if
      // any handler called evt.preventDefault().
      // Firefox will *not* redirect to anchorObj.href
      // for you. However every other browser will.
    }
  }
}
</script>
</head>
<body>

<div onclick="alert('Container clicked')">
  <a id="link" href="#" onclick="alert((event.target || event.srcElement).innerHTML)">Normal link</a>
</div>

<button type="button" onclick="fakeClick(event, document.getElementById('link'))">
  Fake Click on Normal Link
</button>

<br /><br />

<div onclick="alert('Container clicked')">
    <div onclick="fakeClick(event, this.getElementsByTagName('a')[0])"><a id="link2" href="#" onclick="alert('foo')">Embedded Link</a></div>
</div>

<button type="button" onclick="fakeClick(event, document.getElementById('link2'))">Fake Click on Embedded Link</button>

</body>
</html>

Demo here.

It avoids recursion in non-IE browsers by inspecting the event object that is initiating the simulated click, by inspecting the target attribute of the event (which remains unchanged during propagation).

Obviously IE does this internally holding a reference to its global event object. DOM level 2 defines no such global variable, so for that reason the simulator must pass in its local copy of event.

How to use code to open a modal in Angular 2?

I am using a variable to control show and hide and rely on the button the open the modal

ts code:

showModel(){
  this.showModal = true;
}

html:

<button type="button" data-toggle="modal" data-target="#myModal" (click)="showModel()>Open Modal</button>

<div *ngIf="showModal" >
  <div id="myModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <p>Some text in the modal.</p>
            </div>
        </div>
    </div>
</div>

How do I import a .bak file into Microsoft SQL Server 2012?

.bak is a backup file generated in SQL Server.

Backup files importing means restoring a database, you can restore on a database created in SQL Server 2012 but the backup file should be from SQL Server 2005, 2008, 2008 R2, 2012 database.

You restore database by using following command...

RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH Recovery

You want to learn about how to restore .bak file follow the below link:

http://msdn.microsoft.com/en-us/library/ms186858(v=sql.90).aspx

When should I use Memcache instead of Memcached?

This is 2013. Forget about the 2009 comments. Likewise, if you are running serious traffic loads, do not even contemplate how to make-do with a windows based memcache. When dealing with a very large scale (500+ front end web servers) and 20+ back end database servers and replicants (mysql & mssql mix), a farm of memcached servers (12 servers in group) supports multiple high volume OLTP applications answering 25K ~ 40K mc->get calls per-second. These calls are those that do NOT have to reach a database.

IMHO, this use of memcached provided SERIOUS $$$,$$$savings on CAPEX for new DB servers & licences as well as on support contracts for large commercial designs.

Multi-dimensional arrays in Bash

After a lot of trial and error i actually find the best, clearest and easiest multidimensional array on bash is to use a regular var. Yep.

Advantages: You don't have to loop through a big array, you can just echo "$var" and use grep/awk/sed. It's easy and clear and you can have as many columns as you like.

Example:

$ var=$(echo -e 'kris hansen oslo\nthomas jonson peru\nbibi abu johnsonville\njohnny lipp peru')

$ echo "$var"
kris hansen oslo
thomas johnson peru
bibi abu johnsonville
johnny lipp peru

If you want to find everyone in peru

$ echo "$var" | grep peru
thomas johnson peru
johnny lipp peru

Only grep(sed) in the third field

$ echo "$var" | sed -n -E '/(.+) (.+) peru/p'
thomas johnson peru
johnny lipp peru

If you only want x field

$ echo "$var" | awk '{print $2}'
hansen
johnson
abu
johnny

Everyone in peru that's called thomas and just return his lastname

$ echo "$var" |grep peru|grep thomas|awk '{print $2}'
johnson

Any query you can think of... supereasy.

To change an item:

$ var=$(echo "$var"|sed "s/thomas/pete/")

To delete a row that contains "x"

$ var=$(echo "$var"|sed "/thomas/d")

To change another field in the same row based on a value from another item

$ var=$(echo "$var"|sed -E "s/(thomas) (.+) (.+)/\1 test \3/")
$ echo "$var"
kris hansen oslo                                                                                                                                             
thomas test peru                                                                                                                                          
bibi abu johnsonville
johnny lipp peru

Of course looping works too if you want to do that

$ for i in "$var"; do echo "$i"; done
kris hansen oslo
thomas jonson peru
bibi abu johnsonville
johnny lipp peru

The only gotcha iv'e found with this is that you must always quote the var(in the example; both var and i) or things will look like this

$ for i in "$var"; do echo $i; done
kris hansen oslo thomas jonson peru bibi abu johnsonville johnny lipp peru

and someone will undoubtedly say it won't work if you have spaces in your input, however that can be fixed by using another delimeter in your input, eg(using an utf8 char now to emphasize that you can choose something your input won't contain, but you can choose whatever ofc):

$ var=$(echo -e 'field one?field two hello?field three yes moin\nfield 1?field 2?field 3 dsdds aq')

$ for i in "$var"; do echo "$i"; done
field one?field two hello?field three yes moin
field 1?field 2?field 3 dsdds aq

$ echo "$var" | awk -F '?' '{print $3}'
field three yes moin
field 3 dsdds aq

$ var=$(echo "$var"|sed -E "s/(field one)?(.+)?(.+)/\1?test?\3/")
$ echo "$var"
field one?test?field three yes moin
field 1?field 2?field 3 dsdds aq

If you want to store newlines in your input, you could convert the newline to something else before input and convert it back again on output(or don't use bash...). Enjoy!

How do I sort a Set to a List in Java?

I am using this code, which I find more practical than the accepted answer above:

List<Thing> thingList = new ArrayList<>(thingSet);
thingList.sort((thing1, thing2) -> thing1.getName().compareToIgnoreCase(thing2.getName()));

Working copy XXX locked and cleanup failed in SVN

I had this problem because external folders do not want to be linked into an existing folder. If you add an svn:externals property line where the destination is an existing (versioned or non-versioned) folder, you will get the SVN Woring Copy locked error. Here a cleanup will also tell you that everthing is all right but still updating won't work.

Solution: Delete the troubling folder from the repository and make an update in the root folder where the svn:externals property is set. This will create the folder and all will be fine again.

This problem arose for me because svn:externals for files requires the destination folder to be version controlled. After I noticed that this doesn't work across different repositories, I swaped from external files to external folder and got into this mess.

Getting last day of the month in a given string date

Java 8 and above.

By using convertedDate.getMonth().length(convertedDate.isLeapYear()) where convertedDate is an instance of LocalDate.

String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
                                convertedDate.getMonth().length(convertedDate.isLeapYear()));

Java 7 and below.

By using getActualMaximum method of java.util.Calendar:

String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));

'python3' is not recognized as an internal or external command, operable program or batch file

There is no python3.exe file, that is why it fails.

Try:

py

instead.

py is just a launcher for python.exe. If you have more than one python versions installed on your machine (2.x, 3.x) you can specify what version of python to launch by

py -2 or py -3

How to check if a service is running via batch file and start it, if it is not running?

That should do it:

FOR %%a IN (%Svcs%) DO (SC query %%a | FIND /i "RUNNING"
IF ERRORLEVEL 1 SC start %%a)

How to write to file in Ruby?

For those of us that learn by example...

Write text to a file like this:

IO.write('/tmp/msg.txt', 'hi')

BONUS INFO ...

Read it back like this

IO.read('/tmp/msg.txt')

Frequently, I want to read a file into my clipboard ***

Clipboard.copy IO.read('/tmp/msg.txt')

And other times, I want to write what's in my clipboard to a file ***

IO.write('/tmp/msg.txt', Clipboard.paste)

*** Assumes you have the clipboard gem installed

See: https://rubygems.org/gems/clipboard

CertificateException: No name matching ssl.someUrl.de found

I've found a good resolution here: http://www.mkyong.com/webservices/jax-ws/java-security-cert-certificateexception-no-name-matching-localhost-found/

But my problem was a little bit different and solved it differently.

The web service was on remote host. For example: https://some.remote.host/MyWebService?wsdl

But it was available only by IP for any clients, but certificate was created for domain: some.remote.host (CN=some.remote.host). And this domain can't be resolved by IP because it is not presented in DNS).

So the same problem appeared: if I use IP to connect to web service by ssl, it can't be reached becase certificate CN=some.remote.host and it is not equal to host name I've specified (i.e. host IP).

I've resolved it by matching this hostname with IP in /etc/hosts file. The problem was fixed.

But in case when the Web Service is hosted on localhost app server, it think, it should be solved like mkyong described in his article.

Batch file to copy directories recursively

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

Windows Batch File Looping Through Directories to Process Files?

How do I make a burn down chart in Excel?

Why not graph the percentage complete. If you include the last date as a 100% complete value you can force the chart to show the linear trend as well as the actual data. This should give you a reasonable idea of whether you are above or below the line.

I would include a screenshot but not enough rep. Here is a link to one I prepared earlier. Burn Down Chart.

Printing Batch file results to a text file

For Print Result to text file

we can follow

echo "test data" > test.txt

This will create test.txt file and written "test data"

If you want to append then

echo "test data" >> test.txt

Create a tar.xz in one command

Quick Solution

tarxz() { tar cf - "$1" | xz -4e > "$1".tar.xz ; }
tarxz name_of_directory

(Notice, not name_of_directory/)


Using xz compression options

If you want to use compression options for xz, or if you are using tar on MacOS, you probably want to avoid the tar -cJf syntax.

According to man xz, the way to do this is:

tar cf - filename | xz -4e > filename.tar.xz

Because I liked Wojciech Adam Koszek's format, but not information:

  1. c creates a new archive for the specified files.
  2. f reads from a directory (best to put this second because -cf != -fc)
  3. - outputs to Standard Output
  4. | pipes output to the next command
  5. xz -4e calls xz with the -4e compression option. (equal to -4 --extreme)
  6. > filename.tar.xz directs the tarred and compressed file to filename.tar.xz

where -4e is, use your own compression options. I often use -k to --keep the original file and -9 for really heavy compression. -z to manually set xz to zip, though it defaults to zipping if not otherwise directed.

To uncompress and untar

To echo Rafael van Horn, to uncompress & untar (see note below):

xz -dc filename.tar.xz | tar x

Note: unlike Rafael's answer, use xz -dc instead of catxz. The docs recommend this in case you are using this for scripting. Best to have a habit of using -d or --decompress instead of unxz as well. However, if you must, using those commands from the command line is fine.

What does %~d0 mean in a Windows batch file?

From Filename parsing in batch file and more idioms - Real's How-to:

The path (without drive) where the script is : ~p0

The drive where the script is : ~d0

How to use order by with union all in sql?

Select 'Shambhu' as ShambhuNewsFeed,Note as [News Fedd],NotificationId
from Notification with(nolock) where DesignationId=@Designation 
Union All 
Select 'Shambhu' as ShambhuNewsFeed,Note as [Notification],NotificationId
from Notification with(nolock) 
where DesignationId=@Designation 
order by NotificationId desc