Programs & Examples On #Frameset iframe

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Try the following

  1. download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

  2. Unzip the file and Run intelhaxm-android.exe.

  3. Run silent_install.bat.

In my computer Win10 x64 - VS2015 it worked

What's the main difference between Java SE and Java EE?

In Java SE you need software to run the program like if you have developed a desktop application and if you want to share the application with other machines all the machines have to install the software for running the application. But in Java EE there is no software needed to install in all the machines. Java EE has the forward capabilities. This is only one simple example. There are lots of differences.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

This error occur when you try to load a component dynamically and:

  1. The component you want to load is not routing module
  2. The component is no in module entryComponents.

in routingModule

const routes: Routes = [{ path: 'confirm-component', component: ConfirmComponent,data: {}}]

or in module

entryComponents: [
ConfirmComponent
} 

To fix this error you can add a router to the component or add it to entryComponents of module.

  1. Add a router to component.drawback of this approach is your component will be accessible with that url.
  2. Add it to entryComponents. in this case your component will not have any url attached to and it will not be accessible with url.

Difference between Git and GitHub

Simply put, Git is a version control system that lets you manage and keep track of your source code history. GitHub is a cloud-based hosting service that lets you manage Git repositories. If you have open-source projects that use Git, then GitHub is designed to help you better manage them.

curl_init() function not working

To fix this bug, I did:

  1. In php.ini file, uncomment this line: extension=php_curl.dll
  2. In php.ini file, uncomment this line: extension_dir = "ext"
  3. I restarted NETBEANS, as I was using Built-in server

Is Laravel really this slow?

I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync. I tried both cygwin and minGW. It seems like rsync is incompatible with git for windows's version of ssh.

Here is what worked for me: NFS.

Vagrant docs says:

NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.

This isn't true anymore. We can use vagrant-winnfsd plugin nowadays. It's really simple to install:

  1. Execute vagrant plugin install vagrant-winnfsd
  2. Change in your Vagrantfile: config.vm.synced_folder ".", "/vagrant", type: "nfs"
  3. Add to Vagrantfile: config.vm.network "private_network", type: "dhcp"

That's all I needed to make NFS work. Laravel response time decreased from 500ms to 100ms for me.

What's the regular expression that matches a square bracket?

If you're looking to find both variations of the square brackets at the same time, you can use the following pattern which defines a range of either the [ sign or the ] sign: /[\[\]]/

Are (non-void) self-closing tags valid in HTML5?

I would be very careful with self closing tags as this example demonstrates:

var a = '<span/><span/>';
var d = document.createElement('div');
d.innerHTML = a
console.log(d.innerHTML) // "<span><span></span></span>"

My gut feeling would have been <span></span><span></span> instead

Failed to find 'ANDROID_HOME' environment variable

These are the steps that you need to follow to successfully set up your Ionic Project to work with android emulator:

  1. Create an Ionic Project: ionic start appName tabs (for tab theme)
  2. cd appName
  3. ionic setup sass
  4. To start the app on web: ionic serve

To add android platform:

Priori Things

First you need to setup the environment variables. For this you need to consider 3 files:

1. ~/.profile (For setting up the variables every time terminal opens or computer boots up):

//Code that you need to append at the last

set PATH so it includes user's private bin directories
PATH="$HOME/bin:$HOME/.local/bin:$PATH"
export ANDROID_HOME='/home/<user_name>/Android/Sdk' <Path to android SDK>
export PATH=$PATH:$ANDROID_HOME/bin
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools

2. /etc/environment (to set the environment variables):

//All the content of the file

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
JAVA_HOME="/usr/lib/jvm/java-8-oracle"
ANDROID_HOME="/home/<user_name>/Android/Sdk" <Path to android SDK>

3. /etc/profile:

//Code that you need to add at the last

JAVA_HOME=/usr/lib/jvm/java-8-oracle <Path where Java is installed>
JRE_HOME=$JAVA_HOME/jre 
PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

For loading the above changes made to the file you need to run the following command:

source ~/.profile
source /etc/environment
source /etc/profile

Posteori Things

1. Add platform: ionic platform add android (Note that you need to run this command without sudo)

2. If you are still getting error in the above command then do the following: (here appName = helloWorld)

    cd ..
    sudo chmod -R 777 helloWorld
    cd helloWorld 
    ionic platform add android
    If you are still getting the error then remove ".cordova" folder from the home directory of your PC.

3. To run the app in your android emulator: ionic run android

Thanks!

How do you specify a byte literal in Java?

You cannot. A basic numeric constant is considered an integer (or long if followed by a "L"), so you must explicitly downcast it to a byte to pass it as a parameter. As far as I know there is no shortcut.

git ignore exception

Use:

*.dll    #Exclude all dlls
!foo.dll #Except for foo.dll

From gitignore:

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

How to dynamically create generic C# object using reflection?

It seems to me the last line of your example code should simply be:

Task<Item> itsMe = o as Task<Item>;

Or am I missing something?

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

for cordova developers having this issue

try to set

<preference name="deployment-target" value="8.0" />

in confix.xml

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

When you run the code on windows machine, firewall prompts it to allow network access, allow the network access and it will work, if it does not prompts, go to firewall settings > allow an app through firewall and select your python.exe and allow network access.

Linux delete file with size 0

You can use the command find to do this. We can match files with -type f, and match empty files using -size 0. Then we can delete the matches with -delete.

find . -type f -size 0 -delete

How to download the latest artifact from Artifactory repository?

I use Nexus and this code works for me—can retrive both release and last snaphsot, depending on repository type:

server="http://example.com/nexus/content/repositories"
repo="snapshots"
name="com.exmple.server"
artifact="com/example/$name"
path=$server/$repo/$artifact
mvnMetadata=$(curl -s "$path/maven-metadata.xml")
echo "Metadata: $mvnMetadata"
jar=""
version=$( echo "$mvnMetadata" | xpath -e "//versioning/release/text()" 2> /dev/null)
if [[ $version = *[!\ ]* ]]; then
  jar=$name-$version.jar
else
  version=$(echo "$mvnMetadata" | xpath -e "//versioning/versions/version[last()]/text()")
  snapshotMetadata=$(curl -s "$path/$version/maven-metadata.xml")
  timestamp=$(echo "$snapshotMetadata" | xpath -e "//snapshot/timestamp/text()")
  buildNumber=$(echo "$snapshotMetadata" | xpath -e "//snapshot/buildNumber/text()")
  snapshotVersion=$(echo "$version" | sed 's/\(-SNAPSHOT\)*$//g')
  jar=$name-$snapshotVersion-$timestamp-$buildNumber.jar
fi
jarUrl=$path/$version/$jar
echo $jarUrl
mkdir -p /opt/server/
wget -O /opt/server/server.jar -q -N $jarUrl

Javascript String to int conversion

JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:

var numberAsInt = parseInt(number, 10);  
// Second arg is radix, 10 is decimal.

If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.

C++ program converts fahrenheit to celsius

Fahrenheit to celsius would be (Fahrenheit - 32) * 5 / 9

How to query between two dates using Laravel and Eloquent?

The whereBetween method verifies that a column's value is between two values.

$from = date('2018-01-01');
$to = date('2018-05-02');

Reservation::whereBetween('reservation_from', [$from, $to])->get();

In some cases you need to add date range dynamically. Based on @Anovative's comment you can do this:

Reservation::all()->filter(function($item) {
  if (Carbon::now->between($item->from, $item->to) {
    return $item;
  }
});

If you would like to add more condition then you can use orWhereBetween. If you would like to exclude a date interval then you can use whereNotBetween.

Reservation::whereBetween('reservation_from', [$from1, $to1])
  ->orWhereBetween('reservation_to', [$from2, $to2])
  ->whereNotBetween('reservation_to', [$from3, $to3])
  ->get();

Other useful where clauses: whereIn, whereNotIn, whereNull, whereNotNull, whereDate, whereMonth, whereDay, whereYear, whereTime, whereColumn, whereExists, whereRaw.

Laravel docs about Where Clauses.

C# Form.Close vs Form.Dispose

If you use form.close() in your form and set the FormClosing Event of your form and either use form.close() in this Event ,you fall in unlimited loop and Argument out of range happened and the solution is that change the form.close() with form.dispose() in Event of FormClosing. I hope this little tip help you!!!

Why use pointers?

Here's my anwser, and I won't promse to be an expert, but I've found pointers to be great in one of my libraries I'm trying to write. In this library (It's a graphics API with OpenGL:-)) you can create a triangle with vertex objects passed into them. The draw method takes these triangle objects, and well.. draws them based on the vertex objects i created. Well, its ok.

But, what if i change a vertex coordinate? Move it or something with moveX() in the vertex class? Well, ok, now i have to update the triangle, adding more methods and performance is being wasted because i have to update the triangle every time a vertex moves. Still not a big deal, but it's not that great.

Now, what if i have a mesh with tons of vertices and tons of triangles, and the mesh is rotateing, and moveing, and such. I'll have to update every triangle that uses these vertices, and probably every triangle in the scene because i wouldn't know which ones use which vertices. That's hugely computer intensive, and if I have several meshes ontop of a landscape, oh god! I'm in trouble, because im updateing every triangle almost every frame because these vertices are changing al the time!

With pointers, you don't have to update the triangles.

If I had three *Vertex objects per triangle class, not only am i saving room because a zillion triangles don't have three vertex objects which are large themselves, but also these pointers will always point to the Vertices they are meant to, no matter how often the vertices change. Since the pointers still point to the same vertex, the triangles don't change, and the update process is easier to handle. If I confused you, I wouldn't doubt it, I don't pretend to be an expert, just throwing my two cents into the discussion.

Remove scrollbars from textarea

Hide scroll bar, but while still being able to scroll using CSS

To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:

    -webkit- (Chrome, Safari, newer versions of Opera):
    .element::-webkit-scrollbar { width: 0 !important }
    -moz- (Firefox):
    .element { overflow: -moz-scrollbars-none; }
    -ms- (Internet Explorer +10):
    .element { -ms-overflow-style: none; }

ref: https://www.geeksforgeeks.org/hide-scroll-bar-but-while-still-being-able-to-scroll-using-css/

how to implement Interfaces in C++?

Interface are nothing but a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data. For example:

class InterfaceA
{
public:
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}

Share data between html pages

why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.

To store values for a session:

sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')

or more permanently:

localStorage.getItem('label')
localStorage.setItem('label', 'value')

So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

Java - Change int to ascii

Do you want to convert ints to chars?:

int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
// Output:
// 33
// !

Or do you want to convert ints to Strings?

int yourInt = 33;
String str = String.valueOf(yourInt);

Or what is it that you mean?

How to handle iframe in Selenium WebDriver using java

In Webdriver, you should use driver.switchTo().defaultContent(); to get out of a frame. You need to get out of all the frames first, then switch into outer frame again.

// between step 4 and step 5
// remove selenium.selectFrame("relative=up");
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("cq-cf-frame");
// now continue step 6
driver.findElement(By.xpath("//button[text()='OK']")).click(); 

ValueError: max() arg is an empty sequence

Since you are always initialising self.listMyData to an empty list in clkFindMost your code will always lead to this error* because after that both unique_names and frequencies are empty iterables, so fix this.

Another thing is that since you're iterating over a set in that method then calculating frequency makes no sense as set contain only unique items, so frequency of each item is always going to be 1.

Lastly dict.get is a method not a list or dictionary so you can't use [] with it:

Correct way is:

if frequencies.get(name):

And Pythonic way is:

if name in frequencies:

The Pythonic way to get the frequency of items is to use collections.Counter:

from collections import Counter   #Add this at the top of file.

def clkFindMost(self, parent):

        #self.listMyData = []   
        if self.listMyData:
           frequencies = Counter(self.listMyData)
           self.txtResults.Value = max(frequencies, key=frequencies.get)
        else:
           self.txtResults.Value = '' 

max() and min() throw such error when an empty iterable is passed to them. You can check the length of v before calling max() on it.

>>> lst = []
>>> max(lst)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    max(lst)
ValueError: max() arg is an empty sequence
>>> if lst:
    mx = max(lst)
else:
    #Handle this here

If you are using it with an iterator then you need to consume the iterator first before calling max() on it because boolean value of iterator is always True, so we can't use if on them directly:

>>> it = iter([])
>>> bool(it)
True
>>> lst = list(it)
>>> if lst:
       mx = max(lst)
    else:
      #Handle this here   

Good news is starting from Python 3.4 you will be able to specify an optional return value for min() and max() in case of empty iterable.

Should composer.lock be committed to version control?

There's no exact answer to this.

Generally speaking, composer shouldn't be doing what the build system is meant to be doing and you shouldn't be putting composer.lock in VCS. Composer might strangely have it backwards. End users rather than produces shouldn't be using lock files. Usually your build system keeps snapshots, reusable dirs, etc rather than an empty dir each time. People checkout out a lib from composer might want that lib to use a lock so that the dependencies that lib loads have been tested against.

On the other hand that significantly increases the burden of version management, where you'd almost certainly want multiple versions of every library as dependencies will be strictly locked. If every library is likely to have a slightly different version then you need some multiple library version support and you can also quickly see the size of dependencies needed flair out, hence the advise to keep it on the leaf.

Taking that on board, I really don't find lock files to be useful either libraries or your own workdirs. It's only use for me is in my build/testing platform which persists any externally acquired assets only updating them when requested, providing repeatable builds for testing, build and deploy. While that can be kept in VCS it's not always kept with the source tree, the build trees will either be elsewhere in the VCS structure or managed by another system somewhere else. If it's stored in a VCS it's debatable whether or not to keep it in the same repo as source trees because otherwise every pull can bring in a mass of build assets. I quite like having things all in a well arranged repo with the exception of production/sensitive credentials and bloat.

SVN can do it better than git as it doesn't force you to acquire the entire repo (though I suspect that's not actually strictly needed for git either but support for that is limited and it's not commonly used). Simple build repos are usually just an overlay branch you merge/export the build tree into. Some people combine exernal resources in their source tree or separate further, external, build and source trees. It usually serves two purposes, build caching and repeatable builds but sometimes keeping it separate on at least some level also permits fresh/blank builds and multiple builds easily.

There are a number of strategies for this and none of them particularly work well with persisting the sources list unless you're keeping external source in your source tree.

They also have things like hashes in of the file, how do that merge when two people update packages? That alone should make you think maybe this is misconstrued.

The arguments people are putting forward for lock files are cases where they've taken a very specific and restrictive view of the problem. Want repeatable builds and consistent builds? Include the vendor folder in VCS. Then you also speed up fetching assets as well as not having to depend on potentially broken external resources during build. None of the build and deploy pipelines I create require external access unless absolutely necessary. If you do have to update an external resource it's once and only once. What composer is trying to achieve makes sense for a distributed system except as mentioned before it makes no sense because it would end up with library dependency hell for library updates with common clashes and updates being as slow as the slowest to update package.

Additionally I update ferociously. Every time I develop I update and test everything. There's a very very tiny window for significant version drift to sneak in. Realistically as well, when semantic versioning is upheld, which is tends to be for composer, you're not suppose to have that many compatibility issues or breakages.

In composer.json you put the packages you require and their versions. You can lock the versions there. However those packages also have dependencies with dynamic versions that wont be locked by composer.json (though I don't see why your couldn't also put them there yourself if you do want them to be version locked) so someone else running composer install gets something different without the lock. You might not care a great deal about that or you might care, it depends. Should you care? Probably at least a little, enough to ensure you're aware of it in any situation and potential impact, but it might not be a problem either if you always have the time to just DRY run first and fix anything that got updated.

The hassle composer is trying to avoid sometimes just isn't there and the hassle having composer lock files can make is significant. They have absolutely no right to tell users what they should or shouldn't do regarding build versus source assets (whether to join of separate in VCS) as that's none of their business, they're not the boss of you or me. "Composer says" isn't an authority, they're not your superior officer nor do they give anyone any superiority on this subject. Only you know your real situation and what's best for that. However, they might advise a default course of action for users that don't understand how things work in which case you might want to follow that but personally I don't think that's a real substitute for knowing how things work and being able to properly workout your requirements. Ultimately, their answer to that question is a best guess. The people who make composer do not know where you should keep your composer.lock nor should they. Their only responsibility is to tell you what it is and what it does. Outside of that you need to decide what's best for you.

Keeping the lock file in is problematic for usability because composer is very secretive about whether it uses lock or JSON and doesn't always to well to use both together. If you run install it only uses the lock file it would appear so if you add something to composer.json then it wont be installed because it's not in your lock. It's not intuitive at all what operations really do and what they're doing in regards to the json/lock file and sometimes don't appear to even make sense (help says install takes a package name but on trying to use it it says no).

To update the lock or basically apply changes from the json you have to use update and you might not want to update everything. The lock takes precedence for choosing what should be installed. If there's a lock file, it's what's used. You can restrict update somewhat but the system is still just a mess.

Updating takes an age, gigs of RAM. I suspect as well if you pick up a project that's not been touched for a while that it looked from the versions it has up, which there will be more of over time and it probably doesn't do that efficiently which just strangles it.

They're very very sneaky when it comes to having secret composite commands you couldn't expect to be composite. By default the composer remove command appears to maps to composer update and composer remove for example.

The question you really need to be asking is not if you should keep the lock in your source tree or alternatively whether you should persist it somewhere in some fashion or not but rather you should be asking what it actually does, then you can decide for yourself when you need to persist it and where.

I will point out that having the ability to have the lock is a great convenience when you have a robust external dependency persistence strategy as it keeps track of you the information useful for tracking that (the origins) and updating it but if you don't then it's neither here not there. It's not useful when it's forced down your throat as a mandatory option to have it polluting your source trees. It's a very common thing to find in legacy codebases where people have made lots of changes to composer.json which haven't really been applied and are broken when people try to use composer. No composer.lock, no desync problem.

Calling a Sub in VBA

For anyone still coming to this post, the other option is to simply omit the parentheses:

Sub SomeOtherSub(Stattyp As String)
    'Daty and the other variables are defined here

    CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2

End Sub

The Call keywords is only really in VBA for backwards compatibilty and isn't actually required.

If however, you decide to use the Call keyword, then you have to change your syntax to suit.

'// With Call
Call Foo(Bar)

'// Without Call
Foo Bar

Both will do exactly the same thing.


That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call keyword and the parentheses

No Main class found in NetBeans

Also, for others out there with a slightly different problem where Netbeans will not find the class when you want when doing a browse from "main classes dialog window".

It could be that your main method does have the proper signature. In my case I forgot the args.

example: public static void main(String[] args)

The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above.

Args: You can name the argument anything you want, but most programmers choose "args" or "argv".

Read more here: http://docs.oracle.com/javase/tutorial/getStarted/application/

How do I convert a javascript object array to a string array of the object attribute I want?

If your array of objects is items, you can do:

_x000D_
_x000D_
var items = [{_x000D_
  id: 1,_x000D_
  name: 'john'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'jane'_x000D_
}, {_x000D_
  id: 2000,_x000D_
  name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
  return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Documentation: map()

Bootstrap carousel multiple frames at once

All the above solutions are hacky and buggy. Don't even try. Use other libs. The best I have found - http://sachinchoolur.github.io/lightslider Works great with bootstrap, does not add junk html, highly-configurable, responsive, mobile-friendly etc...

$('.multi-item-carousel').lightSlider({
    item: 4,
    pager: false,
    autoWidth: false,
    slideMargin: 0
});

Mobile website "WhatsApp" button to send message to a specific number

On android, you can try

href="intent://send/[countrycode_without_plus][number]#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end

replace [countrycode_without_plus][number] with the number,

Is Java's assertEquals method reliable?

Yes, it is used all the time for testing. It is very likely that the testing framework uses .equals() for comparisons such as these.

Below is a link explaining the "string equality mistake". Essentially, strings in Java are objects, and when you compare object equality, typically they are compared based on memory address, and not by content. Because of this, two strings won't occupy the same address, even if their content is identical, so they won't match correctly, even though they look the same when printed.

http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

Remove quotes from String in Python

The easiest way is:

s = '"sajdkasjdsaasdasdasds"' 
import json
s = json.loads(s)

In Python, how do I loop through the dictionary and change the value if it equals something?

for k, v in mydict.iteritems():
    if v is None:
        mydict[k] = ''

In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems.

In Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems' error. Use items() instead of iteritems() here.

Refer to this post.

How to return a struct from a function in C++?

You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:

auto f()
{
    struct S
    {
      int a;
      double b;
    } s;
    s.a = 42;
    s.b = 42.0;
    return s;
}

auto x = f();
a = x.a;
b = x.b;

How do I concatenate strings?

Simple ways to concatenate strings in Rust

There are various methods available in Rust to concatenate strings

First method (Using concat!() ):

fn main() {
    println!("{}", concat!("a", "b"))
}

The output of the above code is :

ab


Second method (using push_str() and + operator):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = "c".to_string();

    _a.push_str(&_b);

    println!("{}", _a);

    println!("{}", _a + &_c);
}

The output of the above code is:

ab

abc


Third method (Using format!()):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = format!("{}{}", _a, _b);

    println!("{}", _c);
}

The output of the above code is :

ab

Check it out and experiment with Rust playground.

Multi-line strings in PHP

To put the strings "l" and "vv" on separate lines in the code alone:

$xml = "l";
$xml .= "vv"
echo $xml;

In this instance you're saying to append .= the string to the end of the previous version of that string variable. Remember that = is only an assignment operator so in your original code you're assigning the variable a new string value.

To put the strings "l" and "vv" on separate lines in the echo alone:

$xml = "l\nvv"
echo $xml;

You don't need multiple strings in this instance, as the new line character \n will take care of that for you.

To put the strings "l" and "vv" on separate lines in code and when echoing:

$xml = "l";
$xml .= "\nvv"
echo $xml;

Redirecting to previous page after login? PHP

I have created a function to store URL of previous page

//functions.php

function set_previous_page_url(){

    $current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; 
    $previous_url = $_SERVER['HTTP_REFERER'];
    if (!($current_url === $previous_url)){
        $_SESSION['redirect_url'] = $previous_url;
    }
    if(isset($_SESSION['redirect_url'])){
        $url = $_SESSION['redirect_url'];
        return $url;

    } else {
        $url = "index.php";
        return $url;
    }
}

And call this function in login.php

// login.php

<?php
// set previous page url to redirect after login
$url = set_previous_page_url();

if(ifItIsMethod('post')){
    if(isset($_POST['username']) && isset($_POST['password'])){
        if (login_user($_POST['username'], $_POST['password'])) {
            redirect($url);
            //unset session defined in set_previous_page_url() function
            if(isset($_SESSION['redirect_url'])){
                unset($_SESSION['redirect_url']);
            }

        } 
    }
}
?>

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

To make this work in Chrome and Safari, you would have to do it like this

window.onbeforeunload = function(e) {
    return "Sure you want to leave?";
};

Reference: https://developer.mozilla.org/en/DOM/window.onbeforeunload

Convert categorical data in pandas dataframe

@Quickbeam2k1 ,see below -

dataset=pd.read_csv('Data2.csv')
np.set_printoptions(threshold=np.nan)
X = dataset.iloc[:,:].values

Using sklearn enter image description here

from sklearn.preprocessing import LabelEncoder
labelencoder_X=LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Assuming you want to replace the newlines with something so that something like this:

the quick brown fox\r\n
jumped over the lazy dog\r\n

doesn't end up like this:

the quick brown foxjumped over the lazy dog

I'd do something like this:

string[] SplitIntoChunks(string text, int size)
{
    string[] chunk = new string[(text.Length / size) + 1];
    int chunkIdx = 0;
    for (int offset = 0; offset < text.Length; offset += size)
    {
        chunk[chunkIdx++] = text.Substring(offset, size);
    }
    return chunk;
}    

string[] GetComments()
{
    var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox; 
    if (cmtTb == null)
    {
        return new string[] {};
    }

    // I assume you don't want to run the text of the two lines together?
    var text = cmtTb.Text.Replace(Environment.Newline, " ");
    return SplitIntoChunks(text, 50);    
}

I apologize if the syntax isn't perfect; I'm not on a machine with C# available right now.

Updating an object with setState in React

The first case is indeed a syntax error.

Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:

this.state = {
  name: 'jasper',
  age: 28
}

That way, if you want to update the name, you can just call:

this.setState({
  name: 'Sean'
});

Will that achieve what you're aiming for?

For larger, more complex data stores, I would use something like Redux. But that's much more advanced.

The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)

Check out these references:

Query error with ambiguous column name in SQL

One of your tables has the same column name's which brings a confusion in the query as to which columns of the tables are you referring to. Copy this code and run it.

SELECT 
    v.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
FROM Vendors AS v
JOIN Invoices AS i ON (v.VendorID = .VendorID)
JOIN InvoiceLineItems AS iL ON (i.InvoiceID = iL.InvoiceID)
WHERE  
    I.InvoiceID IN
        (SELECT iL.InvoiceSequence 
         FROM InvoiceLineItems
         WHERE iL.InvoiceSequence > 1)
ORDER BY 
    V.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount

How can I verify a Google authentication API access token?

An arbitrary OAuth access token can't be used for authentication, because the meaning of the token is outside of the OAuth Core spec. It could be intended for a single use or narrow expiration window, or it could provide access which the user doesn't want to give. It's also opaque, and the OAuth consumer which obtained it might never have seen any type of user identifier.

An OAuth service provider and one or more consumers could easily use OAuth to provide a verifiable authentication token, and there are proposals and ideas to do this out there, but an arbitrary service provider speaking only OAuth Core can't provide this without other co-ordination with a consumer. The Google-specific AuthSubTokenInfo REST method, along with the user's identifier, is close, but it isn't suitable, either, since it could invalidate the token, or the token could be expired.

If your Google ID is an OpenId identifier, and your 'public interface' is either a web app or can call up the user's browser, then you should probably use Google's OpenID OP.

OpenID consists of just sending the user to the OP and getting a signed assertion back. The interaction is solely for the benefit of the RP. There is no long-lived token or other user-specific handle which could be used to indicate that a RP has successfully authenticated a user with an OP.

One way to verify a previous authentication against an OpenID identifier is to just perform authentication again, assuming the same user-agent is being used. The OP should be able to return a positive assertion without user interaction (by verifying a cookie or client cert, for example). The OP is free to require another user interaction, and probably will if the authentication request is coming from another domain (my OP gives me the option to re-authenticate this particular RP without interacting in the future). And in Google's case, the UI that the user went through to get the OAuth token might not use the same session identifier, so the user will have to re-authenticate. But in any case, you'll be able to assert the identity.

ps1 cannot be loaded because running scripts is disabled on this system

open windows powershell in administrator mode and run the following command and its work VOILA!!

Set-ExecutionPolicy RemoteSigned

How do I use .woff fonts for my website?

After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts subdirectory.

In CSS code:

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font.woff") format('woff');
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-bold.woff") format('woff');
    font-weight: bold;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-boldoblique.woff") format('woff');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-oblique.woff") format('woff');
    font-style: italic;
}

After having that definitions, you can just write, for example,

In HTML code:

<div class="mydiv">
    <b>this will be written with awesome-font-bold.woff</b>
    <br/>
    <b><i>this will be written with awesome-font-boldoblique.woff</i></b>
    <br/>
    <i>this will be written with awesome-font-oblique.woff</i>
    <br/>
    this will be written with awesome-font.woff
</div>

In CSS code:

.mydiv {
    font-family: myfont
}

The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.

How to get the background color of an HTML element?

It depends which style from the div you need. Is this a background style which was defined in CSS or background style which was added through javascript(inline) to the current node?

In case of CSS style, you should use computed style. Like you do in getStyle().

With inline style you should use node.style reference: x.style.backgroundColor;

Also notice, that you pick the style by using camelCase/non hyphen reference, so not background-color, but backgroundColor;

Get cookie by name

Just to add an "official" answer to this response, I'm copy/pasting the solution to set and retrieve cookies from MDN (here's the JSfiddle

    document.cookie = "test1=Hello";
    document.cookie = "test2=World";

    var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");

    function alertCookieValue() {
      alert(cookieValue);
    }

In you particular case, you would use the following function

    function getCookieValue() {
      return document.cookie.replace(/(?:(?:^|.*;\s*)obligations\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    }

Note that i only replaced "test2" from the example, with "obligations".

convert htaccess to nginx

Use this: http://winginx.com/htaccess

Online converter, nice way and time saver ;)

How can I iterate over an enum?

#include <iostream>
#include <algorithm>

namespace MyEnum
{
  enum Type
  {
    a = 100,
    b = 220,
    c = -1
  };

  static const Type All[] = { a, b, c };
}

void fun( const MyEnum::Type e )
{
  std::cout << e << std::endl;
}

int main()
{
  // all
  for ( const auto e : MyEnum::All )
    fun( e );

  // some
  for ( const auto e : { MyEnum::a, MyEnum::b } )
    fun( e );

  // all
  std::for_each( std::begin( MyEnum::All ), std::end( MyEnum::All ), fun );

  return 0;
}

Upgrade to python 3.8 using conda

Update for 2020/07

Finally, Anaconda3-2020.07 is out and its core is Python 3.8!

You can now download Anaconda packed with Python 3.8 goodness at:

Comparing Class Types in Java

If you don't want to or can't use instanceof, then compare with equals:

 if(obj.getClass().equals(MyObject.class)) System.out.println("true");

BTW - it's strange because the two Class instances in your statement really should be the same, at least in your example code. They may be different if:

  • the classes have the same short name but are defined in different packages
  • the classes have the same full name but are loaded by different classloaders.

How to slice an array in Bash

There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.

version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}"    # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}"    # 7 1

TypeError: expected string or buffer

lines is a list of strings, re.findall doesn't work with that. try:

import re, sys

f = open('findallEX.txt', 'r')
lines = f.read()
match = re.findall('[A-Z]+', lines)
print match

Angular 2 declaring an array of objects

type NumberArray = Array<{id: number, text: string}>;

const arr: NumberArray = [
    {id: 0, text: 'Number 0'},
    {id: 1, text: 'Number 1'},
    {id: 2, text: 'Number 2'},
    {id: 3, text: 'Number 3 '},
    {id: 4, text: 'Number 4 '},
    {id: 5, text: 'Number 5 '},
];

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If you want happen to be using LESS it can be achieved like so:

li {
    .glyphicon-ok();

    &:before {            
        .glyphicon();            
        margin-left:-25px;
       float:left;
    }
}

Split and join C# string

You can use string.Split and string.Join:

string theString = "Some Very Large String Here";
var array = theString.Split(' ');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));

If you know you always only want to split off the first element, you can use:

var array = theString.Split(' ', 2);

This makes it so you don't have to join:

string restOfArray = array[1];

Tracing XML request/responses with JAX-WS

You need to implement a javax.xml.ws.handler.LogicalHandler, this handler then needs to be referenced in a handler configuration file, which in turn is referenced by an @HandlerChain annotation in your service endpoint (interface or implementation). You can then either output the message via system.out or a logger in your processMessage implementation.

See

http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/twbs_jaxwshandler.html

http://java.sun.com/mailers/techtips/enterprise/2006/TechTips_June06.html

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

In Wordpress just replace

$(function(){...});

with

jQuery(function(){...});

How to give a delay in loop execution using Qt

EDIT (removed wrong solution). EDIT (to add this other option):

Another way to use it would be subclass QThread since it has protected *sleep methods.

QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);

Here's the code to create your own *sleep method.

#include <QThread>    

class Sleeper : public QThread
{
public:
    static void usleep(unsigned long usecs){QThread::usleep(usecs);}
    static void msleep(unsigned long msecs){QThread::msleep(msecs);}
    static void sleep(unsigned long secs){QThread::sleep(secs);}
};

and you call it by doing this:

Sleeper::usleep(10);
Sleeper::msleep(10);
Sleeper::sleep(10);

This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.

How to return a result from a VBA function

Just setting the return value to the function name is still not exactly the same as the Java (or other) return statement, because in java, return exits the function, like this:

public int test(int x) {
    if (x == 1) {
        return 1; // exits immediately
    }

    // still here? return 0 as default.
    return 0;
}

In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:

Public Function test(ByVal x As Integer) As Integer
    If x = 1 Then
        test = 1 ' does not exit immediately. You must manually terminate...
        Exit Function ' to exit
    End If

    ' Still here? return 0 as default.
    test = 0
    ' no need for an Exit Function because we're about to exit anyway.
End Function 

Since this is the case, it's also nice to know that you can use the return variable like any other variable in the method. Like this:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test <> 1 Then ' Test the currently set return value
        test = 0 ' Reset the return value to a *new* value
    End If

End Function 

Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test > 0 Then

        ' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
        ' AND THE RESULT RESETTING THE RETURN VALUE.
        test = test(test - 1)

    End If

End Function

Where does Oracle SQL Developer store connections?

SqlDeveloper stores all the connections in a file named

connections.xml

In windows XP you can find the file in location

C:\Documents and Settings\<username>\Application Data\SQL Developer\systemX.X.X.X.X\o.jdeveloper.db.connection.X.X.X.X.X.X.X\connections.xml

In Windows 7 you will find it in location

C:\Users\<username>\AppData\Roaming\SQL Developer\systemX.X.X.X.X\o.jdeveloper.db.connection.X.X.X.X.X.X.X\connections.xml

How to call a .NET Webservice from Android using KSOAP2?

You can Use below code to call the web service and get response .Make sure that your Web Service return the response in Data Table Format..This code help you if you using data from SQL Server database .If you you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet"); by DocumentElement

private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://localhost/Web_Service.asmx?"; // you can use   IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value); // Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {
    androidHttpTransport.call(SOAP_ACTION, envelope); //call the eb service Method
} catch (Exception e) {
    e.printStackTrace();
} //Next task is to get Response and format that response

SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");

for (int i = 0; i < obj2.getPropertyCount(); i++) //the method getPropertyCount() return the number of rows
{
    obj3 = (SoapObject) obj2.getProperty(i);
    obj3.getProperty(0).toString(); //value of column 1
    obj3.getProperty(1).toString(); //value of column 2
    //like that you will get value from each column
}

If you have any problem regarding this you can write me..

Host binding and Host listening

This is the simple example to use both of them:

import {
  Directive, HostListener, HostBinding
}
from '@angular/core';

@Directive({
  selector: '[Highlight]'
})
export class HighlightDirective {
  @HostListener('mouseenter') mouseover() {
    this.backgroundColor = 'green';
  };

  @HostListener('mouseleave') mouseleave() {
    this.backgroundColor = 'white';
  }

  @HostBinding('style.backgroundColor') get setColor() {
     return this.backgroundColor;
  };

  private backgroundColor = 'white';
  constructor() {}

}

Introduction:

  1. HostListener can bind an event to the element.

  2. HostBinding can bind a style to the element.

  3. this is directive, so we can use it for

    Some Text
  4. So according to the debug, we can find that this div has been binded style = "background-color:white"

    Some Text
  5. we also can find that EventListener of this div has two event: mouseenter and mouseleave. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.

How do you create nested dict in Python?

It is important to remember when using defaultdict and similar nested dict modules such as nested_dict, that looking up a nonexistent key may inadvertently create a new key entry in the dict and cause a lot of havoc.

Here is a Python3 example with nested_dict module:

import nested_dict as nd
nest = nd.nested_dict()
nest['outer1']['inner1'] = 'v11'
nest['outer1']['inner2'] = 'v12'
print('original nested dict: \n', nest)
try:
    nest['outer1']['wrong_key1']
except KeyError as e:
    print('exception missing key', e)
print('nested dict after lookup with missing key.  no exception raised:\n', nest)

# Instead, convert back to normal dict...
nest_d = nest.to_dict(nest)
try:
    print('converted to normal dict. Trying to lookup Wrong_key2')
    nest_d['outer1']['wrong_key2']
except KeyError as e:
    print('exception missing key', e)
else:
    print(' no exception raised:\n')

# ...or use dict.keys to check if key in nested dict
print('checking with dict.keys')
print(list(nest['outer1'].keys()))
if 'wrong_key3' in list(nest.keys()):

    print('found wrong_key3')
else:
    print(' did not find wrong_key3')

Output is:

original nested dict:   {"outer1": {"inner2": "v12", "inner1": "v11"}}

nested dict after lookup with missing key.  no exception raised:  
{"outer1": {"wrong_key1": {}, "inner2": "v12", "inner1": "v11"}} 

converted to normal dict. 
Trying to lookup Wrong_key2 

exception missing key 'wrong_key2' 

checking with dict.keys 

['wrong_key1', 'inner2', 'inner1']  
did not find wrong_key3

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

How to check if a table exists in MS Access for vb macros

Setting a reference to the Microsoft Access 12.0 Object Library allows us to test if a table exists using DCount.

Public Function ifTableExists(tblName As String) As Boolean

    If DCount("[Name]", "MSysObjects", "[Name] = '" & tblName & "'") = 1 Then

        ifTableExists = True

    End If

End Function

add Shadow on UIView using swift 3

Please Try this

func applyShadowOnView(_ view: UIView) {
    view.layer.cornerRadius = 8
    view.layer.shadowColor = UIColor.darkGray.cgColor
    view.layer.shadowOpacity = 1
    view.layer.shadowOffset = .zero
    view.layer.shadowRadius = 5
}

"X does not name a type" error in C++

It is always encouraged in C++ that you have one class per header file, see this discussion in SO [1]. GManNickG answer's tells why this happen. But the best way to solve this is to put User class in one header file (User.h) and MyMessageBox class in another header file (MyMessageBox.h). Then in your User.h you include MyMessageBox.h and in MyMessageBox.h you include User.h. Do not forget "include gaurds" [2] so that your code compiles successfully.

Find the most popular element in int[] array

public static void main(String[] args) {

    int[] myArray = {1,5,4,4,22,4,9,4,4,8};
    Map<Integer,Integer> arrayCounts = new HashMap<>();
    Integer popularCount  = 0;
    Integer popularValue = 0;

    for(int i = 0; i < myArray.length; i++) {
        Integer count = arrayCounts.get(myArray[i]);
        if (count == null) {
            count = 0;
        }
        arrayCounts.put(myArray[i], count == 0 ? 1 : ++count);
        if (count > popularCount) {
            popularCount = count;
            popularValue = myArray[i];
        }
    }

    System.out.println(popularValue + " --> " + popularCount);
}

How do I build an import library (.lib) AND a DLL in Visual C++?

Does your DLL project have any actual exports? If there are no exports, the linker will not generate an import library .lib file.

In the non-Express version of VS, the import libray name is specfied in the project settings here:

Configuration Properties/Linker/Advanced/Import Library

I assume it's the same in Express (if it even provides the ability to configure the name).

How to implement a binary tree?

I want to show a variation of @apadana's method, which is more useful when there is a considerable number of nodes:

'''
Suppose we have the following tree
      10
    /    \
  11      9
 /  \     / \
7   12  15   8
'''
# Step 1 - Create nodes - Use a list instead of defining each node separately
nlist = [10,11,7,9,15,8,12]; n = []
for i in range(len(nlist)): n.append(Node(nlist[i]))

# Step 2 - Set each node position
n[0].left  = n[1]
n[1].left = n[2]
n[0].right = n[3]
n[3].left = n[4]
n[3].right = n[5]
n[1].right = n[6]

Jquery to open Bootstrap v3 modal of remote url

A different perspective to the same problem away from Javascript and using php:

<a data-toggle="modal" href="#myModal">LINK</a>

<div class="modal fade" tabindex="-1" aria-labelledby="gridSystemModalLabel" id="myModal" role="dialog" style="max-width: 90%;">
    <div class="modal-dialog" style="text-align: left;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Title</h4>
            </div>
            <div class="modal-body">
                <?php include( 'remotefile.php'); ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

and put in the remote.php file your basic html source.

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

it happened for me when I deleted the jdk and installed new one somehow the project kept seeing the old one as invalid but couldn't change, so right click on your module -> Open Module Settings -> and choose Compile Sdk Version.

How do I show a console output/window in a forms application?

this one should work.

using System.Runtime.InteropServices;

private void Form1_Load(object sender, EventArgs e)
{
    AllocConsole();
}

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

javascript functions to show and hide divs

I usually do this with classes, that seems to force the browsers to reassess all the styling.

.hiddendiv {display:none;}
.visiblediv {display:block;}

then use;

<script>  
function show() {  
    document.getElementById('benefits').className='visiblediv';  
}  
function close() {  
    document.getElementById('benefits').className='hiddendiv';  
}    
</script>

Note the casing of "className" that trips me up a lot

Is it possible to assign numeric value to an enum in Java?

public enum EXIT_CODE {
    A(104), B(203);

    private int numVal;

    EXIT_CODE(int numVal) {
        this.numVal = numVal;
    }

    public int getNumVal() {
        return numVal;
    }
}

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

Facebook how to check if user has liked page and show content?

With Javascript SDK, you can change the code as below, this should be added after FB.init call.

     // Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
        // the user is logged in and has authenticated your
        // app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed
        // request, and the time the access token 
        // and signed request each expire
        var uid = response.authResponse.userID;
        var accessToken = response.authResponse.accessToken;
        alert('we are fine');
      } else if (response.status === 'not_authorized') {
        // the user is logged in to Facebook, 
        // but has not authenticated your app
        alert('please like us');
         $("#container_notlike").show();
      } else {
        // the user isn't logged in to Facebook.
        alert('please login');
      }
     });

FB.Event.subscribe('edge.create',
function(response) {
    alert('You liked the URL: ' + response);
      $("#container_like").show();
}

Highest Salary in each department

The below listed query will list highest salary in each department.

select deptname, max(salary) from department, employee where 
  department.deptno=employee.deptno group by deptname;

I executed this query successfully on Oracle database.

using sql count in a case statement

If you want to group the results based on a column and take the count based on the same, you can run the query as,

$sql = "SELECT COLUMNNAME,

COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'New',

COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'ACCPTED',

from TABLENAME

GROUP BY COLUMNANME";

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

Installing a local module using npm?

Since asked and answered by the same person, I'll add a npm link as an alternative.

from docs:

This is handy for installing your own stuff, so that you can work on it and test it iteratively without having to continually rebuild.

cd ~/projects/node-bloggy  # go into the dir of your main project
npm link ../node-redis     # link the dir of your dependency

[Edit] As of NPM 2.0, you can declare local dependencies in package.json

"dependencies": {
    "bar": "file:../foo/bar"
  }

How to print SQL statement in codeigniter model

You can display the ActiveRecord generated SQL:

Before the query runs:

$this->db->_compile_select(); 

And after it has run:

$this->db->last_query(); 

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

An additional possible cause.

My HTML page had these starting tags:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

This was on a page that using the slick jquery slideshow.

I removed the tags and replaced with:

<html>

And everything is working again.

How to get length of a string using strlen function

If you really, really want to use strlen(), then

cout << strlen(str.c_str()) << endl;

else the use of .length() is more in keeping with C++.

What is your single most favorite command-line trick using Bash?

Good for making an exact recursive copy/backup of a directory including symlinks (rather than following them or ignoring them like cp):

$ mkdir new_dir
$ cd old_dir
$ tar cf - . | ( cd ../old_dir; tar xf - )

'typeid' versus 'typeof' in C++

typeid can operate at runtime, and return an object describing the run time type of the object, which must be a pointer to an object of a class with virtual methods in order for RTTI (run-time type information) to be stored in the class. It can also give the compile time type of an expression or a type name, if not given a pointer to a class with run-time type information.

typeof is a GNU extension, and gives you the type of any expression at compile time. This can be useful, for instance, in declaring temporary variables in macros that may be used on multiple types. In C++, you would usually use templates instead.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

select *
from user
left join edge
on user.userid = edge.tailuser
and edge.headuser = 5043

Spring Boot REST API - request timeout?

You can configure the Async thread executor for your Springboot REST services. The setKeepAliveSeconds() should consider the execution time for the requests chain. Set the ThreadPoolExecutor's keep-alive seconds. Default is 60. This setting can be modified at runtime, for example through JMX.

@Bean(name="asyncExec")
public Executor asyncExecutor()
{
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(3);
    executor.setMaxPoolSize(3);
    executor.setQueueCapacity(10);
    executor.setThreadNamePrefix("AsynchThread-");
    executor.setAllowCoreThreadTimeOut(true);
    executor.setKeepAliveSeconds(10);
    executor.initialize();

    return executor;
}

Then you can define your REST endpoint as follows

@Async("asyncExec")
@PostMapping("/delayedService")
public CompletableFuture<String> doDelay()
{ 
    String response = service.callDelayedService();
    return CompletableFuture.completedFuture(response);
}

How to increase Maximum Upload size in cPanel?

The solution is to create the php.ini file under your root directory. If the site is the wordpress installation then create the php.ini under your/path/to/wordpress/wp-admin/php.ini and add the following line of codes

[PHP]
post_max_size=120M
upload_max_filesize=132M

Adding a column to an existing table in a Rails migration

You can also do this .. rails g migration add_column_to_users email:string

then rake db:migrate also add :email attribute in your user controller ;

for more detail check out http://guides.rubyonrails.org/active_record_migrations.html

Set Background color programmatically

I didn't understand your question ... what do you mean by "when i set every one of my colour"? try this (edit: "#fffff" in original answer changed to "#ffffff"

  yourView.setBackgroundColor(Color.parseColor("#ffffff"));

Free Barcode API for .NET

I do recommend BarcodeLibrary

Here is a small piece of code of how to use it.

        BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
        {
            IncludeLabel = true,
            Alignment = AlignmentPositions.CENTER,
            Width = 300,
            Height = 100,
            RotateFlipType = RotateFlipType.RotateNoneFlipNone,
            BackColor = Color.White,
            ForeColor = Color.Black,
        };

        Image img = barcode.Encode(TYPE.CODE128B, "123456789");

Set textarea width to 100% in bootstrap modal

I am new to .NET/MVC programming, but my understanding is that the Site.css file (under the Content folder in MVC) is a site-level override for Bootstrap CSS, allowing you to override bootstrap native settings in a portable and non-destructive manner (e.g. you can easily save and reapply your site.css changes when updating Bootstrap on your system.)

In Bootstrap 3.0.0, Site.css has the following style setting:

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

Other blogs have suggested that this 280px width was added in haste near a release date, in a desire to make the UI look better than it does with 100% width input. Fortunately it was placed in a "visible" location in the site file so you would notice it.

Simply change the width setting, either for all three input types, or pull out textarea and give it its own setting if you want to leave the others alone.

Read a variable in bash with a default value

In Bash 4:

name="Ricardo"
read -e -i "$name" -p "Please enter your name: " input
name="${input:-$name}"

This displays the name after the prompt like this:

Please enter your name: Ricardo

with the cursor at the end of the name and allows the user to edit it. The last line is optional and forces the name to be the original default if the user erases the input or default (submitting a null).

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

vba: get unique values from array

I don't know of any built-in functionality in VBA. The best would be to use a collection using the value as key and only add to it if a value doesn't exist.

Why does 2 mod 4 = 2?

Mod just means you take the remainder after performing the division. Since 4 goes into 2 zero times, you end up with a remainder of 2.

What's the purpose of META-INF?

I've noticed that some Java libraries have started using META-INF as a directory in which to include configuration files that should be packaged and included in the CLASSPATH along with JARs. For example, Spring allows you to import XML Files that are on the classpath using:

<import resource="classpath:/META-INF/cxf/cxf.xml" />
<import resource="classpath:/META-INF/cxf/cxf-extensions-*.xml" />

In this example, I'm quoting straight out of the Apache CXF User Guide. On a project I worked on in which we had to allow multiple levels of configuration via Spring, we followed this convention and put our configuration files in META-INF.

When I reflect on this decision, I don't know what exactly would be wrong with simply including the configuration files in a specific Java package, rather than in META-INF. But it seems to be an emerging de facto standard; either that, or an emerging anti-pattern :-)

Open URL in Java to get the content

String url_open ="http://javadl.sun.com/webapps/download/AutoDL?BundleId=76860";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open));

How can I convert a string with dot and comma into a float in Python

Here's a simple way I wrote up for you. :)

>>> number = '123,456,789.908'.replace(',', '') # '123456789.908'
>>> float(number)
123456789.908

Should I URL-encode POST data?

Above posts answers questions related to URL Encoding and How it works, but the original questions was "Should I URL-encode POST data?" which isn't answered.

From my recent experience with URL Encoding, I would like to extend the question further. "Should I URL-encode POST data, same as GET HTTP method. Generally, HTML Forms over the Browser if are filled, submitted and/or GET some information, Browsers will do URL Encoding but If an application exposes a web-service and expects Consumers to do URL-Encoding on data, is it Architecturally and Technically correct to do URL Encode with POST HTTP method ?"

Converting Integers to Roman Numerals - Java

Here's the results of MY homework. It doesn't ensure the input is in the right range and I probably should be using StringBuilder (time I looked it up!) and isn't one single method. But if anyone is reading this far I'd appreciate both positive and negative feedback on it!

import java.util.Scanner;
    /**
     *Main() allows user input and tests 1-3999
     *toRoman() breaks the number down into digits and passes them to romanLogic()
     *romanLogic() converts each digit into a the numerals that represent it.
     */
    public class RomanNumerals
    {
        public static void main(String args[]){
            Scanner in = new Scanner(System.in);
            System.out.print("give us an integer < 4000: ");        
            System.out.println("the roman numeral version is: " + toRoman(in.nextInt()));
            for (int i = 1; i<=3999; i++){
                System.out.println(i +" === "+ toRoman(i));
            }
        }
        public static String toRoman(int i){
            String output = "";
            int digits = i%10;
            int tens = (i%100)/10;
            int hundreds = (i%1000)/100;
            int thousands = (i%10000)/1000;
            return (romanLogic(thousands, "M","","")+
                    romanLogic(hundreds,"C","D","M")+
                    romanLogic(tens,"X","L","C")+
                    romanLogic(digits,"I","V","X"));
        }
        public static String romanLogic(int i, String ones, String fives, String tens){
            String result = "";
            if (i == 0){
                return result;
            } else {
                if ((i>=4)&&(i<=8)){                
                    result += fives;
                }
                if (i==9){
                    result += tens;
                }
                if(i%5 < 4){
                    while(i%5 > 0){
                        result += ones;
                        i--;
                    }
                }
                if(i%5 == 4){
                    result = ones + result;
                }
            }
            return result;
        }    
    }

Display the current time and date in an Android application

For Show Current Date and Time on Textview

    /// For Show Date
    String currentDateString = DateFormat.getDateInstance().format(new Date());
    // textView is the TextView view that should display it
    textViewdate.setText(currentDateString);
    /// For Show Time
    String currentTimeString = DateFormat.getTimeInstance().format(new Date());
    // textView is the TextView view that should display it
    textViewtime.setText(currentTimeString);

Check full Code Android – Display the current date and time in an Android Studio Example with source code

Error : Index was outside the bounds of the array.

public int[] posStatus;       

public UsersInput()    
{    
    //It means postStatus will contain 9 elements from index 0 to 8. 
    this.posStatus = new int[9];   
}

int intUsersInput = 0;   

if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8?    
{    
    posStatus[intUsersInput-1] += 1; //set it to 1    
} 

How to get the selected date value while using Bootstrap Datepicker?

If you wan't the date in full text string format you can do it like this:

$('#your-datepicker').data().datepicker.viewDate

Read and write a String from text file

To avoid confusion and add ease, I have created two functions for reading and writing strings to files in the documents directory. Here are the functions:

func writeToDocumentsFile(fileName:String,value:String) {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
    let path = documentsPath.stringByAppendingPathComponent(fileName)
    var error:NSError?
    value.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error)
}

func readFromDocumentsFile(fileName:String) -> String {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
    let path = documentsPath.stringByAppendingPathComponent(fileName)
    var checkValidation = NSFileManager.defaultManager()
    var error:NSError?
    var file:String

    if checkValidation.fileExistsAtPath(path) {
        file = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as! String
    } else {
        file = "*ERROR* \(fileName) does not exist."
    }

    return file
}

Here is an example of their use:

writeToDocumentsFile("MyText.txt","Hello world!")

let value = readFromDocumentsFile("MyText.txt")
println(value)  //Would output 'Hello world!'

let otherValue = readFromDocumentsFile("SomeText.txt")
println(otherValue)  //Would output '*ERROR* SomeText.txt does not exist.'

Hope this helps!

Xcode Version: 6.3.2

Run text file as commands in Bash

cat /path/* | bash

OR

cat commands.txt | bash

Pass multiple complex objects to a post/put Web API method

Here I found a workaround to pass multiple generic objects (as json) from jquery to a WEB API using JObject, and then cast back to your required specific object type in api controller. This objects provides a concrete type specifically designed for working with JSON.

var combinedObj = {}; 
combinedObj["obj1"] = [your json object 1]; 
combinedObj["obj2"] = [your json object 2];

$http({
       method: 'POST',
       url: 'api/PostGenericObjects/',
       data: JSON.stringify(combinedObj)
    }).then(function successCallback(response) {
         // this callback will be called asynchronously
         // when the response is available
         alert("Saved Successfully !!!");
    }, function errorCallback(response) {
         // called asynchronously if an error occurs
         // or server returns response with an error status.
         alert("Error : " + response.data.ExceptionMessage);
});

and then you can get this object in your controller

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public [OBJECT] PostGenericObjects(object obj)
    {
        string[] str = GeneralMethods.UnWrapObjects(obj);
        var item1 = JsonConvert.DeserializeObject<ObjectType1>(str[0]);
        var item2 = JsonConvert.DeserializeObject<ObjectType2>(str[1]);

        return *something*;
    } 

I have made a generic function to unwrap the complex object, so there is no limitation of number of objects while sending and unwrapping. We can even send more than two objects

public class GeneralMethods
{
    public static string[] UnWrapObjects(object obj)
    {
        JObject o = JObject.Parse(obj.ToString());

        string[] str = new string[o.Count];

        for (int i = 0; i < o.Count; i++)
        {
            string var = "obj" + (i + 1).ToString();
            str[i] = o[var].ToString(); 
        }

        return str;
    }

}

I have posted the solution to my blog with a little more description with simpler code to integrate easily.

Pass multiple complex objects to Web API

I hope it would help someone. I would be interested to hear from the experts here regarding the pros and cons of using this methodology.

Syntax of for-loop in SQL Server

Extra Info

Just to add as no-one has posted an answer that includes how to actually iterate though a dataset inside a loop, you can use the keywords OFFSET FETCH.

Usage

DECLARE @i INT = 0;
SELECT @count=  Count(*) FROM {TABLE}

WHILE @i <= @count
BEGIN

    SELECT * FROM {TABLE}
    ORDER BY {COLUMN}
    OFFSET @i ROWS   
    FETCH NEXT 1 ROWS ONLY  

    SET @i = @i + 1;

END

Sort divs in jQuery based on attribute 'data-sort'?

I used this to sort a gallery of images where the sort array would be altered by an ajax call. Hopefully it can be useful to someone.

_x000D_
_x000D_
var myArray = ['2', '3', '1'];_x000D_
var elArray = [];_x000D_
_x000D_
$('.imgs').each(function() {_x000D_
    elArray[$(this).data('image-id')] = $(this);_x000D_
});_x000D_
_x000D_
$.each(myArray,function(index,value){_x000D_
   $('#container').append(elArray[value]); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
   <div class="imgs" data-image-id='1'>1</div>_x000D_
   <div class="imgs" data-image-id='2'>2</div>_x000D_
   <div class="imgs" data-image-id='3'>3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: http://jsfiddle.net/ruys9ksg/

How to compare Boolean?

.equals(false) will be slower because you are calling a virtual method on an object rather than using faster syntax and rather unexpected by most of the programmers because code standards that are generally used don't really assume you should be doing that check via .equals(false) method.

Replace Multiple String Elements in C#

Another option using linq is

[TestMethod]
public void Test()
{
  var input = "it's worth a lot of money, if you can find a buyer.";
  var expected = "its worth a lot of money if you can find a buyer";
  var removeList = new string[] { ".", ",", "'" };
  var result = input;

  removeList.ToList().ForEach(o => result = result.Replace(o, string.Empty));

  Assert.AreEqual(expected, result);
}

What does "control reaches end of non-void function" mean?

add to your code:

"#include < stdlib.h>"

return EXIT_SUCCESS;

at the end of main()

How to manually trigger validation with jQuery validate?

Or one can simply use: $('#myElem').valid()

if ($('#myElem').valid()){
   // will also trigger unobtrusive validation only for this element if in place 
   // add your extra logic here to execute only when element is valid
}

Note that validate() needs to be called on the form before checking it using this method.

Documentation link: https://jqueryvalidation.org/valid/

Display a float with two decimal places in Python

Shortest Python 3 syntax:

n = 5
print(f'{n:.2f}')

How to create a HashMap with two keys (Key-Pair, Value)?

You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key.

Create an object called Index that takes an x and y value.

public class Index {

    private int x;
    private int y;

    public Index(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
        return this.x ^ this.y;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Index other = (Index) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }
}

Then have your HashMap<Index, Value> to get your result. :)

Difference between os.getenv and os.environ.get

One difference observed (Python27):

os.environ raises an exception if the environmental variable does not exist. os.getenv does not raise an exception, but returns None

How to ignore a particular directory or file for tslint?

Currently using Visual Studio Code and the command to disable tslint is

/* tslint:disable */

Something to note. The disable above disables ALL tslint rules on that page. If you want to disable a specific rule you can specify one/multiple rules.

/* tslint:disable comment-format */
/* tslint:disable:rule1 rule2 rule3 etc.. */

Or enable a rule

/* tslint:enable comment-format */

More in depth on TSLint rule flags

PHP Get Highest Value from Array

// assuming positive numbers

$highest_key;
$highest_value = 0;
foreach ($array as $key => $value) {
    if ($value > $highest_value) {
        $highest_key = $key;
    }
}

// $highest_key holds the highest value

How to list installed packages from a given repo using yum

On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:

yumdb search from_repo repoid

(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:

http://james.fedorapeople.org/yum/commands/find-repos-of-install.py

As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?

How do you change Background for a Button MouseOver in WPF?

All of the answers so far involve completely replacing the default button behavior with something else. However, IMHO it is useful and important to understand that it's possible to change just the part you care about, by editing the existing, default template for a XAML element.

In the case of dealing with the hover effect on a WPF button, the change in appearance in a WPF Button element is caused by a Trigger in the default style for the Button, which is based on the IsMouseOver property and sets the Background and BorderBrush properties of the top-level Border element in the control template. The Button element's background is underneath the Border element's background, so changing the Button.Background property doesn't prevent the hover effect from being seen.

With some effort, you could override this behavior with your own setter, but because the element you need to affect is in the template and not directly accessible in your own XAML, that approach would be difficult and IMHO overly complex.

Another option would be to make use the graphic as the Content for the Button rather than the Background. If you need additional content over the graphic, you can combine them with a Grid as the top-level object in the content.

However, if you literally just want to disable the hover effect entirely (rather than just hiding it), you can use the Visual Studio XAML Designer:

  1. While editing your XAML, select the "Design" tab.
  2. In the "Design" tab, find the button for which you want to disable the effect.
  3. Right-click that button, and choose "Edit Template/Edit a Copy...". Select in the prompt you get where you want the new template resource to be placed. This will appear to do nothing, but in fact the Designer will have added new resources where you told it, and changed your button element to reference the style that uses those resources as the button template.
  4. Now, you can go edit that style. The easiest thing is to delete or comment-out (e.g. Ctrl+E, C) the <Trigger Property="IsMouseOver" Value="true">...</Trigger> element. Of course, you can make any change to the template you want at that point.

When you're done, the button style will look something like this:

<p:Style x:Key="FocusVisual">
  <Setter Property="Control.Template">
    <Setter.Value>
      <ControlTemplate>
        <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</p:Style>
<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
<p:Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
  <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
  <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
  <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
  <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
  <Setter Property="BorderThickness" Value="1"/>
  <Setter Property="HorizontalContentAlignment" Value="Center"/>
  <Setter Property="VerticalContentAlignment" Value="Center"/>
  <Setter Property="Padding" Value="1"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
          <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        </Border>
        <ControlTemplate.Triggers>
          <Trigger Property="IsDefaulted" Value="true">
            <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
          </Trigger>
          <!--<Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
          </Trigger>-->
          <Trigger Property="IsPressed" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
          </Trigger>
          <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</p:Style>

(Note: you can omit the p: XML namespace qualifications in the actual code…I provide them here only because the Stack Overflow XML code formatter gets confused by <Style/> elements that don't have a fully-qualified name with XML namespace.)

If you want to apply the same style to other buttons, you can just right-click them and choose "Edit Template/Apply Resource" and select the style you just added for the first button. You can even make that style the default style for all buttons, using the normal techniques for applying a default style to elements in XAML.

How do I get the Back Button to work with an AngularJS ui-router state machine?

If you are looking for the simplest "back" button, then you could set up a directive like so:

    .directive('back', function factory($window) {
      return {
        restrict   : 'E',
        replace    : true,
        transclude : true,
        templateUrl: 'wherever your template is located',
        link: function (scope, element, attrs) {
          scope.navBack = function() {
            $window.history.back();
          };
        }
      };
    });

Keep in mind this is a fairly unintelligent "back" button because it is using the browser's history. If you include it on your landing page, it will send a user back to any url they came from prior to landing on yours.

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

public myClass{

private Stage dialogStage;



public void msgBox(String title){
    dialogStage = new Stage();
    GridPane grd_pan = new GridPane();
    grd_pan.setAlignment(Pos.CENTER);
    grd_pan.setHgap(10);
    grd_pan.setVgap(10);//pading
    Scene scene =new Scene(grd_pan,300,150);
    dialogStage.setScene(scene);
    dialogStage.setTitle("alert");
    dialogStage.initModality(Modality.WINDOW_MODAL);

    Label lab_alert= new Label(title);
    grd_pan.add(lab_alert, 0, 1);

    Button btn_ok = new Button("fermer");
    btn_ok.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            // TODO Auto-generated method stub
            dialogStage.hide();

        }
    });
    grd_pan.add(btn_ok, 0, 2);

    dialogStage.show();

}



}

Find element's index in pandas Series

>>> myseries[myseries == 7]
3    7
dtype: int64
>>> myseries[myseries == 7].index[0]
3

Though I admit that there should be a better way to do that, but this at least avoids iterating and looping through the object and moves it to the C level.

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

I have used Excel.dll library which is:

  • open source
  • lightweight
  • fast
  • compatible with xls and xlsx

The documentation available over here: https://exceldatareader.codeplex.com/

Strongly recommendable.

How do you run a single query through mysql from the command line?

here's how you can do it with a cool shell trick:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

use the -t flag to enable table-format output

Saving an image in OpenCV

sorry if this is too obvious. Are you sure the webcam is properly seen and detected by OpenCV in other words, do you get an image when you redirect the captured frame to a "highGui" window? For instance like so:

 frame = cvQueryFrame( capture );
 cvNamedWindow( "myWindow", CV_WINDOW_AUTOSIZE );
 cvShowImage( "myWindow", frame );

How to create a directory and give permission in single command

IMO, it's better to use the install command in such situations. I was trying to make systemd-journald persistent across reboots.

install -d  -g systemd-journal -m 2755 -v /var/log/journal

When to use MongoDB or other document oriented database systems?

After two years using MongoDb for a social app, I have witnessed what it really means to live without a SQL RDBMS.

  1. You end up writing jobs to do things like joining data from different tables/collections, something that an RDBMS would do for you automatically.
  2. Your query capabilities with NoSQL are drastically crippled. MongoDb may be the closest thing to SQL but it is still extremely far behind. Trust me. SQL queries are super intuitive, flexible and powerful. MongoDb queries are not.
  3. MongoDb queries can retrieve data from only one collection and take advantage of only one index. And MongoDb is probably one of the most flexible NoSQL databases. In many scenarios, this means more round-trips to the server to find related records. And then you start de-normalizing data - which means background jobs.
  4. The fact that it is not a relational database means that you won't have (thought by some to be bad performing) foreign key constrains to ensure that your data is consistent. I assure you this is eventually going to create data inconsistencies in your database. Be prepared. Most likely you will start writing processes or checks to keep your database consistent, which will probably not perform better than letting the RDBMS do it for you.
  5. Forget about mature frameworks like hibernate.

I believe that 98% of all projects probably are way better with a typical SQL RDBMS than with NoSQL.

Android: Scale a Drawable or background image?

One option to try is to put the image in the drawable-nodpi folder and set background of a layout to the drawable resource id.

This definitely works with scaling down, I haven't tested with scaling up though.

How to access private data members outside the class without making "friend"s?

In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!

class A {
     int iData;
};

int main ()
{
    A a;
    struct ATwin { int pubData; }; // define a twin class with public members
    reinterpret_cast<ATwin*>( &a )->pubData = 42; // set or get value

    return 0;
}

Case Function Equivalent in Excel

Sounds like a job for VLOOKUP!

You can put your 32 -> 1420 type mappings in a couple of columns somewhere, then use the VLOOKUP function to perform the lookup.

java.lang.OutOfMemoryError: Java heap space in Maven

I have solved this problem on my side by 2 ways:

  1. Adding this configuration in pom.xml

    <configuration><argLine>-Xmx1024m</argLine></configuration>
    
  2. Switch to used JDK 1.7 instead of 1.6

Case objects vs Enumerations in Scala

I've seen various versions of making a case class mimic an enumeration. Here is my version:

trait CaseEnumValue {
    def name:String
}

trait CaseEnum {
    type V <: CaseEnumValue
    def values:List[V]
    def unapply(name:String):Option[String] = {
        if (values.exists(_.name == name)) Some(name) else None
    }
    def unapply(value:V):String = {
        return value.name
    }
    def apply(name:String):Option[V] = {
        values.find(_.name == name)
    }
}

Which allows you to construct case classes that look like the following:

abstract class Currency(override name:String) extends CaseEnumValue {
}

object Currency extends CaseEnum {
    type V = Site
    case object EUR extends Currency("EUR")
    case object GBP extends Currency("GBP")
    var values = List(EUR, GBP)
}

Maybe someone could come up with a better trick than simply adding a each case class to the list like I did. This was all I could come up with at the time.

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

Android findViewById() in Custom View

If it's fixed layout you can do like that:

public void onClick(View v) {
   ViewGroup parent = (ViewGroup) IdNumber.this.getParent();
   EditText firstName = (EditText) parent.findViewById(R.id.display_name);
   firstName.setText("Some Text");
}

If you want find the EditText in flexible layout, I will help you later. Hope this help.

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

Append String in Swift

Its very simple:

For ObjC:

     NSString *string1 = @"This is";
     NSString *string2 = @"Swift Language";

ForSwift:

    let string1 = "This is"
    let string2 = "Swift Language"

For ObjC AppendString:

     NSString *appendString=[NSString stringWithFormat:@"%@ %@",string1,string2];

For Swift AppendString:

    var appendString1 = "\(string1) \(string2)"
    var appendString2 = string1+string2

Result:

    print("APPEND STRING 1:\(appendString1)")
    print("APPEND STRING 2:\(appendString2)")

Complete Code In Swift:

    let string1 = "This is"
    let string2 = "Swift Language"
    var appendString = "\(string1) \(string2)"
    var appendString1 = string1+string2
    print("APPEND STRING1:\(appendString1)")
    print("APPEND STRING2:\(appendString2)")

How to discard all changes made to a branch?

In the source root: git reset ./ HEAD <--un-stage any staged changes git checkout ./ <--discard any unstaged changes

How to increase MySQL connections(max_connections)?

From Increase MySQL connection limit:-

MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:

For MySQL 3.x:

# vi /etc/my.cnf
set-variable = max_connections = 250

For MySQL 4.x and 5.x:

# vi /etc/my.cnf
max_connections = 250

Restart MySQL once you’ve made the changes and verify with:

echo "show variables like 'max_connections';" | mysql

EDIT:-(From comments)

The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs

WordPress asking for my FTP credentials to install plugins

The easiest way to solve this problem is add the following FTP information to your wp-config.php

define('FS_METHOD', 'direct');
define('FTP_BASE', '/usr/home/username/public_html/my-site.example.com/wordpress/');
define('FTP_CONTENT_DIR', '/usr/home/username/public_html/my-site.example.com/wordpress/wp-content/');
define('FTP_PLUGIN_DIR ', '/usr/home/username/public_html/my-site.example.com/wordpress/wp-content/plugins/');

FTP_BASE is the full path to the "base"(ABSPATH) folder of the WordPress installation FTP_CONTENT_DIR is the full path to the wp-content folder of the WordPress installation. FTP_PLUGIN_DIR is the full path to the plugins folder of the WordPress installation.

How to remove the hash from window.location (URL) with JavaScript without page refresh?

You can replace hash with null

var urlWithoutHash = document.location.href.replace(location.hash , "" );

href image link download on click

The easiest way of creating download link for image or html is setting download attribute, but this solution works in modern browsers only.

<a href="/path/to/image" download="myimage"><img src="/path/to/image" /></a>

"myimage" is a name of file to download. Extension will be added automatically Example here

Redirect to Action by parameter mvc

Try this,

return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });

Here i mention you are pass multiple values or model also. That's why here i mention that.

When to throw an exception?

Ultimately the decision comes down to whether it is more helpful to deal with application-level errors like this using exception handling, or via your own home-rolled mechanism like returning status codes. I don't think there's a hard-and-fast rule about which is better, but I would consider:

  • Who's calling your code? Is this a public API of some sort or an internal library?
  • What language are you using? If it's Java, for example, then throwing a (checked) exception puts an explicit burden on your caller to handle this error condition in some way, as opposed to a return status which could be ignored. That could be good or bad.
  • How are other error conditions in the same application handled? Callers won't want to deal with a module that handles errors in an idiosyncratic way unlike anything else in the system.
  • How many things can go wrong with the routine in question, and how would they be handled differently? Consider the difference between a series of catch blocks that handle different errors and a switch on an error code.
  • Do you have structured information about the error you need to return? Throwing an exception gives you a better place to put this information than just returning a status.

Exception: Can't bind to 'ngFor' since it isn't a known native property

Use this

<div *ngFor="let talk of talks> 
   {{talk.title}} 
   {{talk.speaker}}
   <p>{{talk.description}} 
</div>

You need to specify variable to iterate over an array of an object

Xcode Project vs. Xcode Workspace - Differences

Xcode Workspace vs Project

  1. What is the difference between the two of them?

Workspace is a set of projects

  1. What are they responsible for?

Workspace is responsible for dependencies between projects. Project is responsible for the source code.

  1. Which one of them should I work with when I'm developing my Apps in team/alone?

You choice should depends on a type of your project. For example if your project relies on CocoaPods dependency manager it creates a workspace.

  1. Is there anything else I should be aware of in matter of these two files?

A competitor of workspace is cross-project references[About]

[Xcode components]

iOS UIImagePickerController result image orientation after upload

Here is a Swift version of the answer by @an0:

func normalizedImage() -> UIImage {

  if (self.imageOrientation == UIImageOrientation.Up) { 
      return self;
  }

  UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
  let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
  self.drawInRect(rect)

  let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext();
  return normalizedImage;
}

Also in a more general function:

func fixOrientation(img:UIImage) -> UIImage {

  if (img.imageOrientation == UIImageOrientation.Up) { 
      return img;
  }

  UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale);
  let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
  img.drawInRect(rect)

  let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext();
  return normalizedImage;

}

Swift 3 version:

func fixOrientation(img: UIImage) -> UIImage {
    if (img.imageOrientation == .up) {
        return img
    }

    UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
    let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
    img.draw(in: rect)

    let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return normalizedImage
}

remove duplicates from sql union

Using UNION automatically removes duplicate rows unless you specify UNION ALL: http://msdn.microsoft.com/en-us/library/ms180026(SQL.90).aspx

get value from DataTable

It looks like you have accidentally declared DataType as an array rather than as a string.

Change line 3 to:

Dim DataType As String = myTableData.Rows(i).Item(1)

That should work.

Can I use CASE statement in a JOIN condition?

Here I have compared the difference in two different result sets:

SELECT main.ColumnName, compare.Value PreviousValue,  main.Value CurrentValue
FROM 
(
    SELECT 'Name' AS ColumnName, 'John' as Value UNION ALL
    SELECT 'UserName' AS ColumnName, 'jh001' as Value UNION ALL
    SELECT 'Department' AS ColumnName, 'HR' as Value UNION ALL
    SELECT 'Phone' AS ColumnName, NULL as Value UNION ALL
    SELECT 'DOB' AS ColumnName, '1993-01-01' as Value UNION ALL
    SELECT 'CreateDate' AS ColumnName, '2017-01-01' as Value UNION ALL
    SELECT 'IsActive' AS ColumnName, '1' as Value
) main
INNER JOIN
(
    SELECT 'Name' AS ColumnName, 'Rahul' as Value UNION ALL
    SELECT 'UserName' AS ColumnName, 'rh001' as Value UNION ALL
    SELECT 'Department' AS ColumnName, 'HR' as Value UNION ALL
    SELECT 'Phone' AS ColumnName, '01722112233' as Value UNION ALL
    SELECT 'DOB' AS ColumnName, '1993-01-01' as Value UNION ALL
    SELECT 'CreateDate' AS ColumnName, '2017-01-01' as Value UNION ALL
    SELECT 'IsActive' AS ColumnName, '1' as Value
) compare
ON main.ColumnName = compare.ColumnName AND
CASE 
    WHEN main.Value IS NULL AND compare.Value IS NULL THEN 0
    WHEN main.Value IS NULL AND compare.Value IS NOT NULL THEN 1
    WHEN main.Value IS NOT NULL AND compare.Value IS NULL THEN 1
    WHEN main.Value <> compare.Value THEN 1
END = 1 

Hide Button After Click (With Existing Form on Page)

Change the button to :

<button onclick="getElementById('hidden-div').style.display = 'block'; this.style.display = 'none'">Check Availability</button>

FIDDLE

Or even better, use a proper event handler by identifying the button :

<button id="show_button">Check Availability</button>

and a script

<script type="text/javascript">
    var button = document.getElementById('show_button')
    button.addEventListener('click',hideshow,false);

    function hideshow() {
        document.getElementById('hidden-div').style.display = 'block'; 
        this.style.display = 'none'
    }   
</script>

FIDDLE

How to draw circle in html page?

You can use border-radius property, or make a div with fixed height and width and a background with png circle.

How to trigger click event on href element

In addition to romkyns's great answer.. here is some relevant documentation/examples.


DOM Elements have a native .click() method.

The HTMLElement.click() method simulates a mouse click on an element.

When click is used, it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an <a> element to initiate navigation as if a real mouse-click had been received. (mdn reference)

Relevant W3 documentation.


A few examples..

  • You can access a specific DOM element from a jQuery object: (example)

      $('a')[0].click();
    
  • You can use the .get() method to retrieve a DOM element from a jQuery object: (example)

      $('a').get(0).click();
    
  • As expected, you can select the DOM element and call the .click() method. (example)

      document.querySelector('a').click();
    

It's worth pointing out that jQuery is not required to trigger a native .click() event.

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

How do you use bcrypt for hashing passwords in PHP?

For OAuth 2 passwords:

$bcrypt = new \Zend\Crypt\Password\Bcrypt;
$bcrypt->create("youpasswordhere", 10)

What is the use of style="clear:both"?

clear:both makes the element drop below any floated elements that precede it in the document.

You can also use clear:left or clear:right to make it drop below only those elements that have been floated left or right.

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
+------------+
+---------------------+
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |
+---------------------+

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

I still remember the first weeks of my programming courses and I totally understand how you feel. Here is the code that solves your problem. In order to learn from this answer, try to run it adding several 'print' in the loop, so you can see the progress of the variables.

import java.util.*;
import java.lang.*;

public class foo
{

   public static void main(String[] args)
   { 
      double[] alpha = new double[50];
      int count = 0;

      for (int i=0; i<50; i++)
      {
          // System.out.print("variable i = " + i + "\n");
          if (i < 25)
          {
                alpha[i] = i*i;
          }
          else {
                alpha[i] = 3*i;
          }

          if (count < 10)
          {
            System.out.print(alpha[i]+ " "); 
          }  
          else {
            System.out.print("\n"); 
            System.out.print(alpha[i]+ " "); 
            count = 0;
          }

          count++;
      }

      System.out.print("\n"); 

    }
}

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Sqliteopenhelper's method have methods create and upgrade,create is used when any table is first time created and upgrade method will called everytime whenever table's number of column is changed.

Xampp MySQL not starting - "Attempting to start MySQL service..."

  1. In the cmd type: services.msc Find MySql and change properties to the disabled.
  2. In the control panel of Xampp uninstall MySql by the checkbox on the left side, and install again by the click in the same checkbox.

What are NR and FNR and what does "NR==FNR" imply?

Look for keys (first word of line) in file2 that are also in file1.
Step 1: fill array a with the first words of file 1:

awk '{a[$1];}' file1

Step 2: Fill array a and ignore file 2 in the same command. For this check the total number of records until now with the number of the current input file.

awk 'NR==FNR{a[$1]}' file1 file2

Step 3: Ignore actions that might come after } when parsing file 1

awk 'NR==FNR{a[$1];next}' file1 file2 

Step 4: print key of file2 when found in the array a

awk 'NR==FNR{a[$1];next} $1 in a{print $1}' file1 file2

Accessing localhost (xampp) from another computer over LAN network - how to?

Host in local IP,

Open CMD : ipconfig

Wireless LAN adapter Wi-Fi: IPv4 Address. . . . . . . . . . . : xx.xxx.xx.xxx

Removing duplicate values from a PowerShell array

Another option is to use Sort-Object (whose alias is sort, but only on Windows) with the
-Unique switch, which combines sorting with removal of duplicates:

$a | sort -unique

Jenkins Host key verification failed

SSH

If you are trying it with SSH, then the Host key Verification error can come due to several reasons.Follow these steps to overcome all the reasons.

  1. Set the Environment variable as HOME and provide the address as the root directory of .ssh folder. e.g:- If your .ssh is kept inside Name folder. C:/Users/Name.
  2. Now make sure that the public SSH key is being provided in the repository link also. Either it is github or bitbucket or any other.
  3. Open git bash. And try cloning the project from the repository. This will help in adding your repository URL in the known_host file, which is being auto created in the .ssh folder.
  4. Now open jenkins and create a new job. Then click on configure.
  5. provide the cloning URL in Source code management under Git. The URL should be start with [email protected]/......... or ssh://proje........
  6. Under the Credential you need to add the username and password of your repository form which you are cloning the project. Select that credential.
  7. And now apply and save the configuration.
  8. Bingo! Start building the project. I hope now you will not get any Host Key verification error!

Install tkinter for Python

For Arch Linux users, it goes a bit like

sudo pacman -S tk

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

We had this exact problem with fontawesome-webfont.woff2 throwing a 406 error on a shared host (Cpanel). I was working on the elusive "cookie-less domain" for a Wordpress Multisite project and my "www.domain.tld" pages would have the following error (3 times) in Chrome:

Font from origin 'http://static.domain.tld' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.domain.tld' is therefore not allowed access.

and in Firefox, a little more detail:

downloadable font: download failed (font-family: "FontAwesome" style:normal weight:normal stretch:normal src index:1): bad URI or cross-site access not allowed source: http://static.domain.tld/wp-content/themes/some-theme-here/fonts/fontawesome-webfont.woff2?v=4.7.0
font-awesome.min.css:4:14 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://static.domain.tld/wp-content/themes/some-theme-here/fonts/fontawesome-webfont.woff?v=4.7.0. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I got to QWANT-ing around (QWANT.com = fantastic) and found this SO post:

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

An hour in chat with different Shared Host support staff (one didn't even know about F12 in a browser...) then waiting for a response to the ticket that got cut after no joy while playing with mod_security. I tried to cobble the code for the .htaccess file together from the post in the meantime, and got this to work to remedy the 406 errors, flawlessly:

    <IfModule mod_headers.c>
    <IfModule mod_rewrite.c>
        SetEnvIf Origin "http(s)?://(.+\.)?domain\.tld(:\d{1,5})?$" CORS=$0
        Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
        Header merge  Vary "Origin"
    </IfModule>
    </IfModule>

I added that to the top of my .htaccess at the site root and now I have a new Uncle named Bob. (***of course change the domain.tld parts to whatever your domain that you are working with is...)

My FAVORITE part of this post though is the ability to RegEx OR (|) multiple sites into this CORS "hack" by doing:

To allow Multiple sites:

SetEnvIf Origin "http(s)?://(.+\.)?(othersite\.com|mywebsite\.com)(:\d{1,5})?$" CORS=$0

This fix honestly kind of blew my mind because I've ran into this issue before, working with Dev's at Fortune 500 companies that are MILES above my knowledgebase of Apache and couldn't solve problems like this without getting IT to tweak on Apache settings.

This is kind of the magic bullet to fix all those CDN issues with cookie-less (or near cookie-less if you use CloudFlare...) domains to reduce the amount of unnecessary web traffic from cookies that get sent with every image request only to be ditched like a bad blind date by the server.

Super Secure, Super Elegant. Love it: You don't have to open up your servers bandwidth to resource thieves / hot-link-er types.

Props to a collective effort from these 3 brilliant minds for solving what was once thought to unsolvable with .htaccess, whom I pieced this code together from:

@Noyo https://stackoverflow.com/users/357774/noyo

@DaveRandom https://stackoverflow.com/users/889949/daverandom

@pratap-koritala https://stackoverflow.com/users/4401569/pratap-koritala

How to convert number to words in java

You probably don't need this any more, but I recently wrote a java class to do this. Apparently Yanick Rochon did something similar. It will convert numbers up to 999 Novemdecillion (999*10^60). It could do more if I knew what came after Novemdecillion, but I would be willing to bet it's unnecessary. Just feed the number as a string in cents. The output is also grammatically correct.

Here is a link to the Bitbucket Repo

How to subtract hours from a date in Oracle so it affects the day also

sysdate-(2/11)

A day consists of 24 hours. So, to subtract 2 hours from a day you need to divide it by 24:

DATE_value - 2/24

Using interval for the same:

DATE_value - interval '2' hour

Copy entire contents of a directory to another using php

The best solution is!

<?php
$src = "/home/www/domain-name.com/source/folders/123456";
$dest = "/home/www/domain-name.com/test/123456";

shell_exec("cp -r $src $dest");

echo "<H3>Copy Paste completed!</H3>"; //output when done
?>

Int division: Why is the result of 1/3 == 0?

Because it treats 1 and 3 as integers, therefore rounding the result down to 0, so that it is an integer.

To get the result you are looking for, explicitly tell java that the numbers are doubles like so:

double g = 1.0/3.0;

AngularJS $http-post - convert binary to excel file and download

Worked for me -

$scope.downloadFile = function () {
        Resource.downloadFile().then(function (response) {
            var blob = new Blob([response.data], { type: "application/pdf" });
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        },
        function (error) {
            debugger;
        });
    };

Which calls the following from my resource factory-

  downloadFile: function () {
           var downloadRequst = {
                method: 'GET',
                url: 'http://localhost/api/downloadFile?fileId=dfckn4niudsifdh.pdf',
                headers: {
                    'Content-Type': "application/pdf",
                    'Accept': "application/pdf"
                },
                responseType: 'arraybuffer'
            }

            return $http(downloadRequst);
        }

Make sure your API sets the header content type too -

        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

Appending to 2D lists in Python

You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:

listy = [[] for i in range(3)]

Running your example code now gives the result you probably expected:

>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]

How to get the filename without the extension in Java?

The easiest way is to use a regular expression.

fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");

The above expression will remove the last dot followed by one or more characters. Here's a basic unit test.

public void testRegex() {
    assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
    assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}

Adding IN clause List to a JPA Query

The proper JPA query format would be:

el.name IN :inclList

If you're using an older version of Hibernate as your provider you have to write:

el.name IN (:inclList)

but that is a bug (HHH-5126) (EDIT: which has been resolved by now).

List of all unique characters in a string?

if the result does not need to be order-preserving, then you can simply use a set

>>> ''.join(set( "aaabcabccd"))
'acbd'
>>>

Python pip install module is not found. How to link python to pip location?

No other solutions were working for me, so I tried:

pip uninstall <module> && pip install <module>

And that resolved it for me. Your mileage may vary.

Vue v-on:click does not work on component

From the documentation:

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
  2. When you modify the length of the array, e.g. vm.items.length = newLength

In my case i stumbled on this problem when migrating from Angular to VUE. Fix was quite easy, but really difficult to find:

setValue(index) {
    Vue.set(this.arr, index, !this.arr[index]);
    this.$forceUpdate(); // Needed to force view rerendering
}

How to run 'sudo' command in windows

All the answers explain how to elevate your command in a new console host.

What amused me was that none of those tools behave like *nix sudo, allowing to execute the command inside the current console.

So, I wrote: gsudo

Source Code https://github.com/gerardog/gsudo

Installation

Via scoop

  • Install scoop if you don't already have it. Then:
scoop install gsudo

Or via Chocolatey

choco install gsudo

Manual instalation:

Demo

gsudo demo

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

I have searched a lot for a solution in which I can compare two array of objects with different attribute names (something like a left outer join). I came up with this solution. Here I used Lodash. I hope this will help you.

var Obj1 = [
    {id:1, name:'Sandra'},
    {id:2, name:'John'},   
];

var Obj2 = [
    {_id:2, name:'John'},
    {_id:4, name:'Bobby'}
];

var Obj3 = lodash.differenceWith(Obj1, Obj2, function (o1, o2) {
    return o1['id'] === o2['_id']
});

console.log(Obj3);
//  {id:1, name:'Sandra'}

Loop through childNodes

Here is how you can do it with for-in loop.

var children = element.childNodes;

for(child in children){
    console.log(children[child]);
}

How do you auto format code in Visual Studio?

The original question said "I cannot find the setting."

Simple answer is: Look at top menu, then

Edit --> Advanced --> Format Document

You will also see the currently assigned key strokes for that function. Nothing special to memorize. This really helps if you use multiple developer environments on different operating systems.

How to pass optional arguments to a method in C++?

Here is an example of passing mode as optional parameter

void myfunc(int blah, int mode = 0)
{
    if (mode == 0)
        do_something();
     else
        do_something_else();
}

you can call myfunc in both ways and both are valid

myfunc(10);     // Mode will be set to default 0
myfunc(10, 1);  // Mode will be set to 1

How to write to a file in Scala?

Starting Scala 2.13, the standard library provides a dedicated resource management utility: Using.

It can be used in this case with resources such as PrintWriter or BufferedWriter which extends AutoCloseable in order to write to a file and, no matter what, close the resource afterwards:

  • For instance, with java.io api:

    import scala.util.Using, java.io.{PrintWriter, File}
    
    // val lines = List("hello", "world")
    Using(new PrintWriter(new File("file.txt"))) {
      writer => lines.foreach(writer.println)
    }
    
  • Or with java.nio api:

    import scala.util.Using, java.nio.file.{Files, Paths}, java.nio.charset.Charset
    
    // val lines = List("hello", "world")
    Using(Files.newBufferedWriter(Paths.get("file.txt"), Charset.forName("UTF-8"))) {
      writer => lines.foreach(line => writer.write(line + "\n"))
    }
    

Position buttons next to each other in the center of page

you can add this style to your buttons:

#button1 , #button2 {
display:inline-block;
/* additional code */
}

this aligns your buttons inline. ('side by side') :)

Regex to get string between curly braces

i have looked into the other answers, and a vital logic seems to be missing from them . ie, select everything between two CONSECUTIVE brackets,but NOT the brackets

so, here is my answer

\{([^{}]+)\}

How to add new item to hash

hash[key]=value Associates the value given by value with the key given by key.

hash[:newKey] = "newValue"

From Ruby documentation: http://www.tutorialspoint.com/ruby/ruby_hashes.htm

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

One thing to note when using uuid1, if you use the default call (without giving clock_seq parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). The problem will never occur in most use cases, but on a virtual machine with poor clock resolution it will bite you.

How to declare Return Types for Functions in TypeScript

Return types using arrow notation is the same as previous answers:

const sum = (a: number, b: number) : number => a + b;

When use getOne and findOne methods Spring Data JPA

I really find very difficult from the above answers. From debugging perspective i almost spent 8 hours to know the silly mistake.

I have testing spring+hibernate+dozer+Mysql project. To be clear.

I have User entity, Book Entity. You do the calculations of mapping.

Were the Multiple books tied to One user. But in UserServiceImpl i was trying to find it by getOne(userId);

public UserDTO getById(int userId) throws Exception {

    final User user = userDao.getOne(userId);

    if (user == null) {
        throw new ServiceException("User not found", HttpStatus.NOT_FOUND);
    }
    userDto = mapEntityToDto.transformBO(user, UserDTO.class);

    return userDto;
}

The Rest result is

{
"collection": {
    "version": "1.0",
    "data": {
        "id": 1,
        "name": "TEST_ME",
        "bookList": null
    },
    "error": null,
    "statusCode": 200
},
"booleanStatus": null

}

The above code did not fetch the books which is read by the user let say.

The bookList was always null because of getOne(ID). After changing to findOne(ID). The result is

{
"collection": {
    "version": "1.0",
    "data": {
        "id": 0,
        "name": "Annama",
        "bookList": [
            {
                "id": 2,
                "book_no": "The karma of searching",
            }
        ]
    },
    "error": null,
    "statusCode": 200
},
"booleanStatus": null

}

Increase max execution time for php

Try to set a longer max_execution_time:

<IfModule mod_php5.c>
    php_value max_execution_time 300
</IfModule>

<IfModule mod_php7.c>
    php_value max_execution_time 300
</IfModule>

Array to Hash Ruby

Or if you have an array of [key, value] arrays, you can do:

[[1, 2], [3, 4]].inject({}) do |r, s|
  r.merge!({s[0] => s[1]})
end # => { 1 => 2, 3 => 4 }

unique combinations of values in selected columns in pandas data frame and count

Placing @EdChum's very nice answer into a function count_unique_index. The unique method only works on pandas series, not on data frames. The function below reproduces the behavior of the unique function in R:

unique returns a vector, data frame or array like x but with duplicate elements/rows removed.

And adds a count of the occurrences as requested by the OP.

df1 = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],                                                                                             
                    'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})                                                                                               
def count_unique_index(df, by):                                                                                                                                                 
    return df.groupby(by).size().reset_index().rename(columns={0:'count'})                                                                                                      

count_unique_index(df1, ['A','B'])                                                                                                                                              
     A    B  count                                                                                                                                                                  
0   no   no      1                                                                                                                                                                  
1   no  yes      2                                                                                                                                                                  
2  yes   no      4                                                                                                                                                                  
3  yes  yes      3