Programs & Examples On #Jama

JAMA is a basic linear algebra package for Java. It provides user-level classes for constructing and manipulating real, dense matrices.

How do you specify the Java compiler version in a pom.xml file?

I faced same issue in eclipse neon simple maven java project

But I add below details inside pom.xml file

   <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

After right click on project > maven > update project (checked force update)

Its resolve me to display error on project

Hope it's will helpful

Thansk

.gitignore and "The following untracked working tree files would be overwritten by checkout"

This worked for me.

 1. git fetch --all
 2. git reset --hard origin/{branch_name}

Java - removing first character of a string

you can do like this:

String str = "Jamaica";
str = str.substring(1, title.length());
return str;

or in general:

public String removeFirstChar(String str){
   return str.substring(1, title.length());
}

Performance of Java matrix math libraries?

For 3d graphics applications the lwjgl.util vector implementation out-performed above mentioned jblas by a factor of about 3.

I have done 1 million matrix multiplications of a vec4 with a 4x4 matrix.

lwjgl finished in about 18ms, jblas required about 60ms.

(I assume, that the JNI approach is not very suitable for fast successive application of relatively small multiplications. Since the translation/mapping may take more time than the actual execution of the multiplication.)

Deep copy, shallow copy, clone

Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.


In the Java context, we first need to make a distinction between "copying a value" and "copying an object".

int a = 1;
int b = a;     // copying a value
int[] s = new int[]{42};
int[] t = s;   // copying a value (the object reference for the array above)

StringBuffer sb = new StringBuffer("Hi mom");
               // copying an object.
StringBuffer sb2 = new StringBuffer(sb);

In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new, either explicitly or under the hood.


Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:

public class Example {
    public int foo;
    public int[] bar;
    public Example() { };
    public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}

Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ... 

The normal interpretation is that a "shallow" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to the same array as in the original; e.g.

Example eg2 = new Example(eg1.foo, eg1.bar);

The normal interpretation of a "deep" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to a copy of the original array; e.g.

Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));

(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)

Two more questions / areas of uncertainty exist:

  • How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?

  • What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?


Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:

  • The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).

  • In fact, the specification does not even specifically state that clone produces a new object.

Here's what the javadoc says:

"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case that x.clone().equals(x) will be true, this is not an absolute requirement."

Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.

In short, clone potentially means something different for every Java class.


Some people argue (as @supercat does in comments) that the Java clone() method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.

What's the difference between unit, functional, acceptance, and integration tests?

The important thing is that you know what those terms mean to your colleagues. Different groups will have slightly varying definitions of what they mean when they say "full end-to-end" tests, for instance.

I came across Google's naming system for their tests recently, and I rather like it - they bypass the arguments by just using Small, Medium, and Large. For deciding which category a test fits into, they look at a few factors - how long does it take to run, does it access the network, database, filesystem, external systems and so on.

http://googletesting.blogspot.com/2010/12/test-sizes.html

I'd imagine the difference between Small, Medium, and Large for your current workplace might vary from Google's.

However, it's not just about scope, but about purpose. Mark's point about differing perspectives for tests, e.g. programmer vs customer/end user, is really important.

How can I provide multiple conditions for data trigger in WPF?

@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)

but if you have values other than boolean try using type converters:

<MultiDataTrigger.Conditions>
    <Condition Value="True">
        <Condition.Binding>
            <MultiBinding Converter="{StaticResource conditionConverter}">
                <Binding Path="Name" />
                <Binding Path="State" />
            </MultiBinding>
        </Condition.Binding>
        <Setter Property="Background" Value="Cyan" />
    </Condition>
</MultiDataTrigger.Conditions>

you can use the values in Convert method any way you like to produce a condition which suits you.

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This can happen if you have a newline (or other control character) in a JSON string literal.

{"foo": "bar
baz"}

If you are the one producing the data, replace actual newlines with escaped ones "\\n" when creating your string literals.

{"foo": "bar\nbaz"}

How to import multiple .csv files at once?

Using purrr and including file IDs as a column:

library(tidyverse)


p <- "my/directory"
files <- list.files(p, pattern="csv", full.names=TRUE) %>%
    set_names()
merged <- files %>% map_dfr(read_csv, .id="filename")

Without set_names(), .id= will use integer indicators, instead of actual file names.

If you then want just the short filename without the full path:

merged <- merged %>% mutate(filename=basename(filename))

What is the main difference between Collection and Collections in Java?

collection : A collection(with small 'c') represents a group of objects/elements.

Collection : The root interface of Java Collections Framework.

Collections : A utility class that is a member of the Java Collections Framework.

Extending from two classes

Extending from multiple classes is not allowed in java.. to prevent Deadly Diamond of death !

What permission do I need to access Internet from an Android application?

Use these:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

What is the meaning of "int(a[::-1])" in Python?

The notation that is used in

a[::-1]

means that for a given string/list/tuple, you can slice the said object using the format

<object_name>[<start_index>, <stop_index>, <step>]

This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.

In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.

So,

a = '1234'
print a[::2]

would print

13

Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example

a = '1234'
print a[3:0:-1]

This would return

432

Note, that it doesn't return 4321 because, the stop index is not included.

Now in your case,

str(int(a[::-1]))

would just reverse a given integer, that is stored in a string, and then convert it back to a string

i.e "1234" -> "4321" -> 4321 -> "4321"

If what you are trying to do is just reverse the given string, then simply a[::-1] would work .

POST Multipart Form Data using Retrofit 2.0 including image

Don't use multiple parameters in the function name just go with simple few args convention that will increase the readability of codes, for this you can do like -

// MultipartBody.Part.createFormData("partName", data)
Call<SomReponse> methodName(@Part MultiPartBody.Part part);
// RequestBody.create(MediaType.get("text/plain"), data)
Call<SomReponse> methodName(@Part(value = "partName") RequestBody part); 
/* for single use or you can use by Part name with Request body */

// add multiple list of part as abstraction |ease of readability|
Call<SomReponse> methodName(@Part List<MultiPartBody.Part> parts); 
Call<SomReponse> methodName(@PartMap Map<String, RequestBody> parts);
// this way you will save the abstraction of multiple parts.

There can be multiple exceptions that you may encounter while using Retrofit, all of the exceptions documented as code, have a walkthrough to retrofit2/RequestFactory.java. you can able to two functions parseParameterAnnotation and parseMethodAnnotation where you can able to exception thrown, please go through this, it will save your much of time than googling/stackoverflow

How to add icon to mat-icon-button

All you need to do is add the mat-icon-button directive to the button element in your template. Within the button element specify your desired icon with a mat-icon component.

You'll need to import MatButtonModule and MatIconModule in your app module file.

From the Angular Material buttons example page, hit the view code button and you'll see several examples which use the material icons font, eg.

<button mat-icon-button>
  <mat-icon aria-label="Example icon-button with a heart icon">favorite</mat-icon>
</button>

In your case, use

<mat-icon>thumb_up</mat-icon>

As per the getting started guide at https://material.angular.io/guide/getting-started, you'll need to load the material icon font in your index.html.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Or import it in your global styles.scss.

@import url("https://fonts.googleapis.com/icon?family=Material+Icons");

As it mentions, any icon font can be used with the mat-icon component.

Regex to check if valid URL that ends in .jpg, .png, or .gif

This expression will match all the image urls -

^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$

Examples -

Valid -

https://itelligencegroup.com/wp-content/usermedia/de_home_teaser-box_puzzle_in_the_sun.png
http://sweetytextmessages.com/wp-content/uploads/2016/11/9-Happy-Monday-images.jpg
example.com/de_home_teaser-box_puzzle_in_the_sun.png
www.example.com/de_home_teaser-box_puzzle_in_the_sun.png
https://www.greetingseveryday.com/wp-content/uploads/2016/08/Happy-Independence-Day-Greetings-Cards-Pictures-in-Urdu-Marathi-1.jpg
http://thuglifememe.com/wp-content/uploads/2017/12/Top-Happy-tuesday-quotes-1.jpg
https://1.bp.blogspot.com/-ejYG9pr06O4/Wlhn48nx9cI/AAAAAAAAC7s/gAVN3tEV3NYiNPuE-Qpr05TpqLiG79tEQCLcBGAs/s1600/Republic-Day-2017-Wallpapers.jpg

Invalid -

https://www.example.com
http://www.example.com
www.example.com
example.com
http://blog.example.com
http://www.example.com/product
http://www.example.com/products?id=1&page=2
http://www.example.com#up
http://255.255.255.255
255.255.255.255
http://invalid.com/perl.cgi?key= | http://web-site.com/cgi-bin/perl.cgi?key1=value1&key2
http://www.siteabcd.com:8008

How to make a variadic macro (variable number of arguments)

C99 way, also supported by VC++ compiler.

#define FOO(fmt, ...) printf(fmt, ##__VA_ARGS__)

Float a div in top right corner without overlapping sibling header

This worked for me:

h1 {
    display: inline;
    overflow: hidden;
}
div {
    position: relative;
    float: right;
}

It's similar to the approach of the media object, by Stubbornella.

Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)

How to correctly close a feature branch in Mercurial?

One way is to just leave merged feature branches open (and inactive):

$ hg up default
$ hg merge feature-x
$ hg ci -m merge

$ hg heads
    (1 head)

$ hg branches
default    43:...
feature-x  41:...
    (2 branches)

$ hg branches -a
default    43:...
    (1 branch)

Another way is to close a feature branch before merging using an extra commit:

$ hg up feature-x
$ hg ci -m 'Closed branch feature-x' --close-branch
$ hg up default
$ hg merge feature-x
$ hg ci -m merge

$ hg heads
    (1 head)

$ hg branches
default    43:...
    (1 branch)

The first one is simpler, but it leaves an open branch. The second one leaves no open heads/branches, but it requires one more auxiliary commit. One may combine the last actual commit to the feature branch with this extra commit using --close-branch, but one should know in advance which commit will be the last one.

Update: Since Mercurial 1.5 you can close the branch at any time so it will not appear in both hg branches and hg heads anymore. The only thing that could possibly annoy you is that technically the revision graph will still have one more revision without childen.

Update 2: Since Mercurial 1.8 bookmarks have become a core feature of Mercurial. Bookmarks are more convenient for branching than named branches. See also this question:

How to use curl to get a GET request exactly same as using Chrome?

If you need to set the user header string in the curl request, you can use the -H option to set user agent like:

curl -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36" http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome

Updated user-agent form newest Chrome at 02-22-2021


Using a proxy tool like Charles Proxy really helps make short work of something like what you are asking. Here is what I do, using this SO page as an example (as of July 2015 using Charles version 3.10):

  1. Get Charles Proxy running
  2. Make web request using browser
  3. Find desired request in Charles Proxy
  4. Right click on request in Charles Proxy
  5. Select 'Copy cURL Request'

Copy cURL Request example in Charles 3.10.2

You now have a cURL request you can run in a terminal that will mirror the request your browser made. Here is what my request to this page looked like (with the cookie header removed):

curl -H "Host: stackoverflow.com" -H "Cache-Control: max-age=0" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36" -H "HTTPS: 1" -H "DNT: 1" -H "Referer: https://www.google.com/" -H "Accept-Language: en-US,en;q=0.8,en-GB;q=0.6,es;q=0.4" -H "If-Modified-Since: Thu, 23 Jul 2015 20:31:28 GMT" --compressed http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome

How to use SSH to run a local shell script on a remote machine?

First, copy the script over to Machine B using scp

[user@machineA]$ scp /path/to/script user@machineB:/home/user/path

Then, just run the script

[user@machineA]$ ssh user@machineB "/home/user/path/script"

This will work if you have given executable permission to the script.

Insert PHP code In WordPress Page and Post

WordPress does not execute PHP in post/page content by default unless it has a shortcode.

The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.

There are two other "quick and easy" ways to accomplish it without a plugin:

  • Make it a shortcode (put it in functions.php and have it echo the country name) which is very easy - see here: Shortcode API at WP Codex

  • Put it in a template file - make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates

How do I create an Excel chart that pulls data from multiple sheets?

2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.

Hope that will help.

How to remove CocoaPods from a project?

To remove pods from a project completely you need to install two thing first...those are follows(Assuming you have already cocoa-pods installed in your system.)...

  1. Cocoapods-Deintegrate Plugin
  2. Cocoapods-Clean Plugin

Installation

  1. Cocoapods-Deintegrate Plugin

    Use this following command on your terminal to install it.

    sudo gem install cocoapods-deintegrate
    
  2. Cocoapods-Clean Plugin

    Use this following command on your terminal to install it.

    sudo gem install cocoapods-clean
    

Usage

First of all goto your project folder by using the as usual command like..

cd (path of the project) //Remove the braces after cd

Now use those two plugins to remove it completely as follows..

  1. Cocoapods-Deintegrate Plugin

    Use this following command on your terminal to deintegrate the pods from your project first.

     pod deintegrate
    

Deintegrating Pods

  1. Cocoapods-Clean Plugin

    After deintegration of pod from your project use this following command on your terminal to clean it completely.

     pod clean
    

    After completing the above tasks there should be the Podfile still remaining on your project directory..Just delete that manually or use this following command on the terminal..

     rm Podfile
    

Thats it...Now you have your project free from pods...Cleaned.

Removing Cocoapods from the system.

Any way try to use the following command on your terminal to uninstall/remove the coca-pods from your system.

sudo gem uninstall cocoapods

It will remove the coca-pods automatically.

Thanks. Hope this helped.

hash function for string

Though djb2, as presented on stackoverflow by cnicutar, is almost certainly better, I think it's worth showing the K&R hashes too:

1) Apparently a terrible hash algorithm, as presented in K&R 1st edition (source)

unsigned long hash(unsigned char *str)
{
    unsigned int hash = 0;
    int c;

    while (c = *str++)
        hash += c;

    return hash;
}

2) Probably a pretty decent hash algorithm, as presented in K&R version 2 (verified by me on pg. 144 of the book); NB: be sure to remove % HASHSIZE from the return statement if you plan on doing the modulus sizing-to-your-array-length outside the hash algorithm. Also, I recommend you make the return and "hashval" type unsigned long instead of the simple unsigned (int).

unsigned hash(char *s)
{
    unsigned hashval;

    for (hashval = 0; *s != '\0'; s++)
        hashval = *s + 31*hashval;
    return hashval % HASHSIZE;
}

Note that it's clear from the two algorithms that one reason the 1st edition hash is so terrible is because it does NOT take into consideration string character order, so hash("ab") would therefore return the same value as hash("ba"). This is not so with the 2nd edition hash, however, which would (much better!) return two different values for those strings.

The GCC C++11 hashing functions used for unordered_map (a hash table template) and unordered_set (a hash set template) appear to be as follows.

Code:

// Implementation of Murmur hash for 32-bit size_t.
size_t _Hash_bytes(const void* ptr, size_t len, size_t seed)
{
  const size_t m = 0x5bd1e995;
  size_t hash = seed ^ len;
  const char* buf = static_cast<const char*>(ptr);

  // Mix 4 bytes at a time into the hash.
  while (len >= 4)
  {
    size_t k = unaligned_load(buf);
    k *= m;
    k ^= k >> 24;
    k *= m;
    hash *= m;
    hash ^= k;
    buf += 4;
    len -= 4;
  }

  // Handle the last few bytes of the input array.
  switch (len)
  {
    case 3:
      hash ^= static_cast<unsigned char>(buf[2]) << 16;
      [[gnu::fallthrough]];
    case 2:
      hash ^= static_cast<unsigned char>(buf[1]) << 8;
      [[gnu::fallthrough]];
    case 1:
      hash ^= static_cast<unsigned char>(buf[0]);
      hash *= m;
  };

  // Do a few final mixes of the hash.
  hash ^= hash >> 13;
  hash *= m;
  hash ^= hash >> 15;
  return hash;
}

How to loop through an associative array and get the key?

<?php
$names = array("firstname"=>"maurice",
               "lastname"=>"muteti", 
               "contact"=>"7844433339");

foreach ($names as $name => $value) {
    echo $name." ".$value."</br>";
}

print_r($names);
?>

How do I get the height and width of the Android Navigation Bar programmatically?

Combining the answer from @egis and others - this works well on a variety of devices, tested on Pixel EMU, Samsung S6, Sony Z3, Nexus 4. This code uses the display dimensions to test for availability of nav bar and then uses the actual system nav bar size if present.

_x000D_
_x000D_
/**_x000D_
 * Calculates the system navigation bar size._x000D_
 */_x000D_
_x000D_
public final class NavigationBarSize {_x000D_
_x000D_
 private final int systemNavBarHeight;_x000D_
 @NonNull_x000D_
 private final Point navBarSize;_x000D_
_x000D_
 public NavigationBarSize(@NonNull Context context) {_x000D_
  Resources resources = context.getResources();_x000D_
  int displayOrientation = resources.getConfiguration().orientation;_x000D_
  final String name;_x000D_
  switch (displayOrientation) {_x000D_
   case Configuration.ORIENTATION_PORTRAIT:_x000D_
    name = "navigation_bar_height";_x000D_
    break;_x000D_
   default:_x000D_
    name = "navigation_bar_height_landscape";_x000D_
  }_x000D_
  int id = resources.getIdentifier(name, "dimen", "android");_x000D_
  systemNavBarHeight = id > 0 ? resources.getDimensionPixelSize(id) : 0;_x000D_
  navBarSize = getNavigationBarSize(context);_x000D_
 }_x000D_
_x000D_
 public void adjustBottomPadding(@NonNull View view, @DimenRes int defaultHeight) {_x000D_
  int height = 0;_x000D_
  if (navBarSize.y > 0) {_x000D_
   // the device has a nav bar, get the correct size from the system_x000D_
   height = systemNavBarHeight;_x000D_
  }_x000D_
  if (height == 0) {_x000D_
   // fallback to default_x000D_
   height = view.getContext().getResources().getDimensionPixelSize(defaultHeight);_x000D_
  }_x000D_
  view.setPadding(0, 0, 0, height);_x000D_
 }_x000D_
_x000D_
 @NonNull_x000D_
 private static Point getNavigationBarSize(@NonNull Context context) {_x000D_
  Point appUsableSize = new Point();_x000D_
  Point realScreenSize = new Point();_x000D_
  WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);_x000D_
  if (windowManager != null) {_x000D_
   Display display = windowManager.getDefaultDisplay();_x000D_
   display.getSize(appUsableSize);_x000D_
   display.getRealSize(realScreenSize);_x000D_
  }_x000D_
  return new Point(realScreenSize.x - appUsableSize.x, realScreenSize.y - appUsableSize.y);_x000D_
 }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Reading Space separated input in python

You can do the following if you already know the number of fields of the input:

client_name = raw_input("Enter you first and last name: ")
first_name, last_name = client_name.split() 

and in case you want to iterate through the fields separated by spaces, you can do the following:

some_input = raw_input() # This input is the value separated by spaces
for field in some_input.split():
    print field # this print can be replaced with any operation you'd like
    #             to perform on the fields.

A more generic use of the "split()" function would be:

    result_list = some_string.split(DELIMITER)

where DELIMETER is replaced with the delimiter you'd like to use as your separator, with single quotes surrounding it.

An example would be:

    result_string = some_string.split('!')    

The code above takes a string and separates the fields using the '!' character as a delimiter.

Why would one omit the close tag?

Sending headers earlier than the normal course may have far reaching consequences. Below are just a few of them that happened to come to my mind at the moment:

  1. While current PHP releases may have output buffering on, the actual production servers you will be deploying your code on are far more important than any development or testing machines. And they do not always tend to follow latest PHP trends immediately.

  2. You may have headaches over inexplicable functionality loss. Say, you are implementing some kind payment gateway, and redirect user to a specific URL after successful confirmation by the payment processor. If some kind of PHP error, even a warning, or an excess line ending happens, the payment may remain unprocessed and the user may still seem unbilled. This is also one of the reasons why needless redirection is evil and if redirection is to be used, it must be used with caution.

  3. You may get "Page loading canceled" type of errors in Internet Explorer, even in the most recent versions. This is because an AJAX response/json include contains something that it shouldn't contain, because of the excess line endings in some PHP files, just as I've encountered a few days ago.

  4. If you have some file downloads in your app, they can break too, because of this. And you may not notice it, even after years, since the specific breaking habit of a download depends on the server, the browser, the type and content of the file (and possibly some other factors I don't want to bore you with).

  5. Finally, many PHP frameworks including Symfony, Zend and Laravel (there is no mention of this in the coding guidelines but it follows the suit) and the PSR-2 standard (item 2.2) require omission of the closing tag. PHP manual itself (1,2), Wordpress, Drupal and many other PHP software I guess, advise to do so. If you simply make a habit of following the standard (and setup PHP-CS-Fixer for your code) you can forget the issue. Otherwise you will always need to keep the issue in your mind.

Bonus: a few gotchas (actually currently one) related to these 2 characters:

  1. Even some well-known libraries may contain excess line endings after ?>. An example is Smarty, even the most recent versions of both 2.* and 3.* branch have this. So, as always, watch for third party code. Bonus in bonus: A regex for deleting needless PHP endings: replace (\s*\?>\s*)$ with empty text in all files that contain PHP code.

How to remove an element from the flow?

Try to use this:

position: relative;
clear: both;

I use it when I can't use absolute position, for example in printing when you use page-break-after: always; works fine only with position:relative.

How to run DOS/CMD/Command Prompt commands from VB.NET?

You could try this method:

Public Class MyUtilities
    Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean) 
        Dim p as Process = new Process() 
        Dim pi as ProcessStartInfo = new ProcessStartInfo() 
        pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments 
        pi.FileName = "cmd.exe" 
        p.StartInfo = pi 
        p.Start() 
    End Sub
End Class

call, for example, in this way:

MyUtilities.RunCommandCom("DIR", "/W", true)

EDIT: For the multiple command on one line the key are the & | && and || command connectors

  • A & B → execute command A, then execute command B.
  • A | B → execute command A, and redirect all it's output into the input of command B.
  • A && B → execute command A, evaluate the errorlevel after running Command A, and if the exit code (errorlevel) is 0, only then execute command B.
  • A || B → execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute command B.

What is an .axd file?

An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

The import org.apache.commons cannot be resolved in eclipse juno

Look for "poi-3.17.jar"!!!

  1. Download from "https://poi.apache.org/download.html".
  2. Click the one Binary Distribution -> poi-bin-3.17-20170915.tar.gz
  3. Unzip the file download and look for this "poi-3.17.jar".

Problem solved and errors disappeared.

How to automatically indent source code?

Ctrl+E, D - Format whole doc
Ctrl+K, Ctrl+F - Format selection

Also available in the menu via Edit|Advanced.

Thomas

Edit-
Ctrl+K, Ctrl+D - Format whole doc in VS 2010

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

Add a CSS border on hover without moving the element

add margin:-1px; which reduces 1px to each side. or if you need only for side you can do margin-left:-1px etc.

Is there an upper bound to BigInteger?

The number is held in an int[] - the maximum size of an array is Integer.MAX_VALUE. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE.

Admittedly, this is implementation dependent, not part of the specification.


In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).

How to set commands output as a variable in a batch file

in a single line:

FOR /F "tokens=*" %%g IN ('*your command*') do (SET VAR=%%g)

the command output will be set in %g then in VAR.

More informations: https://ss64.com/nt/for_cmd.html

mysql -> insert into tbl (select from another table) and some default values

You simply have to do:

INSERT INTO def (catid, title, page, publish) 
SELECT catid, title, 'page','yes' from `abc`

How to have image and text side by side

HTML

<div class='containerBox'>
    <div>
       <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails'>
       <div>
       <h4>Facebook</h4>  
       <div style="font-size:.6em;float:left; margin-left:5px;color:white;">fine location, GPS, coarse location</div>
       <div style="float:right;font-size:.6em; margin-right:5px; color:white;">0 mins ago</div>
       </div>
   </div> 
</div>

CSS

 .iconDetails {
 margin-left:2%;
 float:left; 
 height:40px;
 width:40px;
 } 

.containerBox {
width:300px;
height:60px;
padding:1px;
background-color:#303030;
}
h4{
margin:0px;
margin-top:3%;
margin-left:50px;
color:white;
}

Any tools to generate an XSD schema from an XML instance document?

Trang is the best option here. Open source and cross platform (although Java is required)

From the Trang Website:

Trang converts between different schema languages for XML. It supports the following languages

  • RELAX NG (XML syntax)
  • RELAX NG compact syntax
  • XML 1.0 DTDs
  • W3C XML Schema

A schema written in any of the supported schema languages can be converted into any of the other supported schema languages, except that W3C XML Schema is supported for output only, not for input.

Trang can also infer a schema from one or more example XML documents.

Download Link

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Python dictionary: Get list of values for list of keys

Here are three ways.

Raising KeyError when key is not found:

result = [mapping[k] for k in iterable]

Default values for missing keys.

result = [mapping.get(k, default_value) for k in iterable]

Skipping missing keys.

result = [mapping[k] for k in iterable if k in mapping]

LINQ to SQL Left Outer Join

Public Sub LinqToSqlJoin07()
Dim q = From e In db.Employees _
        Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
        From o In ords.DefaultIfEmpty _
        Select New With {e.FirstName, e.LastName, .Order = o}

ObjectDumper.Write(q) End Sub

Check http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx

How to Upload Image file in Retrofit 2

It is quite easy. Here is the API Interface

public interface Api {

    @Multipart
    @POST("upload")
    Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);

}

And you can use the following code to make a call.

private void uploadFile(File file, String desc) {

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
        RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);

        //The gson builder
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();


        //creating retrofit object
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        //creating our api 
        Api api = retrofit.create(Api.class);

        //creating a call and calling the upload image method 
        Call<MyResponse> call = api.uploadImage(requestFile, descBody);

        //finally performing the call 
        call.enqueue(new Callback<MyResponse>() {
            @Override
            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
                if (!response.body().error) {
                    Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<MyResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

Source: Retrofit Upload File Tutorial.

Some projects cannot be imported because they already exist in the workspace error in Eclipse

In my case, I copied one of the projects (say 'Project1') from the workspace and pasted it to the same workspace. After that I modified the name of the pasted project (say to 'Project2'). I could not see it in the repository.

The main reason was .project file from the new project still had: <name>Project1</name> instead of <name>Project2</name>.

So, I did following things in order to get the issue fixed:

  1. Cut and paste Project2 outside the workspace
  2. Change .project file to have <name>Project2</name>
  3. Try importing Project2 again.

It worked for me.

How to dynamically change the color of the selected menu item of a web page?

I'm late to this question, but it's really super easy. You just define multiple tab classes in your css file, and then load the required tab as your class in the php file while creating the LI tag.

Here's an example of doing it entirely on the server:

CSS

html ul.tabs li.activeTab1, html ul.tabs li.activeTab1 a:hover, html ul.tabs li.activeTab1 a  { 
    background: #0076B5;
    color: white;
    border-bottom: 1px solid #0076B5;
}

html ul.tabs li.activeTab2, html ul.tabs li.activeTab2 a:hover, html ul.tabs li.activeTab2 a {
    background: #008C5D;
    color: white;
    border-bottom: 1px solid #008C5D;
}

PHP

<ul class="tabs">
    <li <?php print 'class="activeTab1"' ?>>
        <a href="<?php print 'Tab1.php';?>">Tab 1</a>
    </li>

    <li <?php print 'class="activeTab2"' ?>>
        <a href="<?php print 'Tab2.php';?>">Tab 2</a>
    </li>
</ul>

C# LINQ find duplicates in List

I created a extention to response to this you could includ it in your projects, I think this return the most case when you search for duplicates in List or Linq.

Example:

//Dummy class to compare in list
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public Person(int id, string name, string surname)
    {
        this.Id = id;
        this.Name = name;
        this.Surname = surname;
    }
}


//The extention static class
public static class Extention
{
    public static IEnumerable<T> getMoreThanOnceRepeated<T>(this IEnumerable<T> extList, Func<T, object> groupProps) where T : class
    { //Return only the second and next reptition
        return extList
            .GroupBy(groupProps)
            .SelectMany(z => z.Skip(1)); //Skip the first occur and return all the others that repeats
    }
    public static IEnumerable<T> getAllRepeated<T>(this IEnumerable<T> extList, Func<T, object> groupProps) where T : class
    {
        //Get All the lines that has repeating
        return extList
            .GroupBy(groupProps)
            .Where(z => z.Count() > 1) //Filter only the distinct one
            .SelectMany(z => z);//All in where has to be retuned
    }
}

//how to use it:
void DuplicateExample()
{
    //Populate List
    List<Person> PersonsLst = new List<Person>(){
    new Person(1,"Ricardo","Figueiredo"), //fist Duplicate to the example
    new Person(2,"Ana","Figueiredo"),
    new Person(3,"Ricardo","Figueiredo"),//second Duplicate to the example
    new Person(4,"Margarida","Figueiredo"),
    new Person(5,"Ricardo","Figueiredo")//third Duplicate to the example
    };

    Console.WriteLine("All:");
    PersonsLst.ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));
    /* OUTPUT:
        All:
        1 -> Ricardo Figueiredo
        2 -> Ana Figueiredo
        3 -> Ricardo Figueiredo
        4 -> Margarida Figueiredo
        5 -> Ricardo Figueiredo
        */

    Console.WriteLine("All lines with repeated data");
    PersonsLst.getAllRepeated(z => new { z.Name, z.Surname })
        .ToList()
        .ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));
    /* OUTPUT:
        All lines with repeated data
        1 -> Ricardo Figueiredo
        3 -> Ricardo Figueiredo
        5 -> Ricardo Figueiredo
        */
    Console.WriteLine("Only Repeated more than once");
    PersonsLst.getMoreThanOnceRepeated(z => new { z.Name, z.Surname })
        .ToList()
        .ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));
    /* OUTPUT:
        Only Repeated more than once
        3 -> Ricardo Figueiredo
        5 -> Ricardo Figueiredo
        */
}

JavaScript - Get Portion of URL Path

window.location.href.split('/');

Will give you an array containing all the URL parts, which you can access like a normal array.

Or an ever more elegant solution suggested by @Dylan, with only the path parts:

window.location.pathname.split('/');

How to check if JSON return is empty with jquery

$.getJSON(url,function(json){
if ( json.length == 0 ) 
{
console.log("NO !")
}
});

NuGet: 'X' already has a dependency defined for 'Y'

In my case I had to delete the file NuGet.exe in the Project folder/.nuget and rebuild the project.

I also have in NuGet.targets the DownloadNuGetExe marked as true:

<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">true</DownloadNuGetExe>

Hope it's helps.

How to convert column with string type to int form in pyspark data frame?

You could use cast(as int) after replacing NaN with 0,

data_df = df.withColumn("Plays", df.call_time.cast('float'))

what is .subscribe in angular?

A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes of the resource held by the subscription.

import { interval } from 'rxjs';

const observable = interval(1000);
const subscription = observable.subscribe(a=> console.log(a));

/** This cancels the ongoing Observable execution which
was started by calling subscribe with an Observer.*/

subscription.unsubscribe();

A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions.

import { interval } from 'rxjs';

const observable1 = interval(400);
const observable2 = interval(300);

const subscription = observable1.subscribe(x => console.log('first: ' + x));
const childSubscription = observable2.subscribe(x => console.log('second: ' + x));

subscription.add(childSubscription);

setTimeout(() => {
// It unsubscribes BOTH subscription and childSubscription
subscription.unsubscribe();
}, 1000);

According to the official documentation, Angular should unsubscribe for you, but apparently, there is a bug.

Why am I getting error CS0246: The type or namespace name could not be found?

Edit: Oh ignore me, you're not using Visual Studio.

Have you added the reference to your project?

As in this sort of thing:

enter image description here

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

Alternative to answer of @JosephMarikle If you do not want to figth against timezone UTC etc:

var dateString =
        ("0" + date.getUTCDate()).slice(-2) + "/" +
        ("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
        date.getUTCFullYear() + " " +
        //return HH:MM:SS with localtime without surprises
        date.toLocaleTimeString()
    console.log(fechaHoraActualCadena);

How to timeout a thread

One thing that I've not seen mentioned is that killing threads is generally a Bad Idea. There are techniques for making threaded methods cleanly abortable, but that's different to just killing a thread after a timeout.

The risk with what you're suggesting is that you probably don't know what state the thread will be in when you kill it - so you risk introducing instability. A better solution is to make sure your threaded code either doesn't hang itself, or will respond nicely to an abort request.

What do numbers using 0x notation mean?

It's a hexadecimal number.

0x6400 translates to 4*16^2 + 6*16^3 = 25600

Use of "instanceof" in Java

instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Read more from the Oracle language definition here.

Why won't bundler install JSON gem?

I found the solution here. There is a problem with json version 1.8.1 and ruby 2.2.3, so install json 1.8.3 version.

gem install json -v1.8.3

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SQL Management Studio you can:

  1. Right click on the result set grid, select 'Save Result As...' and save in.

  2. On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.

If you need to automate it, use bcp tool.

Which MIME type to use for a binary file that's specific to my program?

mimetype headers are recognised by the browser for the purpose of a (fast) possible identifying a handler to use the downloaded file as target, for example, PDF would be downloaded and your Adobe Reader program would be executed with the path of the PDF file as an argument,

If your needs are to write a browser extension to handle your downloaded file, through your operation-system, or you simply want to make you project a more 'professional looking' go ahead and select a unique mimetype for you to use, it would make no difference since the operation-system would have no handle to open it with (some browsers has few bundled-plugins, for example new Google Chrome versions has a built-in PDF-reader),

if you want to make sure the file would be downloaded have a look at this answer: https://stackoverflow.com/a/34758866/257319

if you want to make your file type especially organised, it might be worth adding a few letters in the first few bytes of the file, for example, every JPG has this at it's file start:

if you can afford a jump of 4 or 8 bytes it could be very helpful for you in the rest of the way

:)

Get program path in VB.NET?

You can also use:

Dim strPath As String = AppDomain.CurrentDomain.BaseDirectory

Why does an onclick property set with setAttribute fail to work in IE?

Did you try:

    execBtn.setAttribute("onclick", function() { runCommand() });

How can I make my website's background transparent without making the content (images & text) transparent too?

Just include following in your code

<body background="C:\Users\Desktop\images.jpg"> 

if you want to specify the size and opacity you can use following

<p><img style="opacity:0.9;" src="C:\Users\Desktop\images.jpg" width="300" height="231" alt="Image" /></p> 

Dynamically adding HTML form field using jQuery

You can add any type of HTML with methods like append and appendTo (among others):

jQuery manipulation methods

Example:

$('form#someform').append('<input type="text" name="something" id="something" />');

How can I parse a YAML file in Python

The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml:

#!/usr/bin/env python

import yaml

with open("example.yaml", 'r') as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

And that's it. A plain yaml.load() function also exists, but yaml.safe_load() should always be preferred unless you explicitly need the arbitrary object serialization/deserialization provided in order to avoid introducing the possibility for arbitrary code execution.

Note the PyYaml project supports versions up through the YAML 1.1 specification. If YAML 1.2 specification support is needed, see ruamel.yaml as noted in this answer.

JQuery - Call the jquery button click event based on name property

You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;

$(function() {
    $("input[name = 'xyz']").css("border","2px solid red");
})

DEMO

Thread Safe C# Singleton Pattern

This is called Double checked locking mechanism, first, we will check whether the instance is created or not. If not then only we will synchronize the method and create the instance. It will drastically improve the performance of the application. Performing lock is heavy. So to avoid the lock first we need to check the null value. This is also thread safe and it is the best way to achieve the best performance. Please have a look at the following code.

public sealed class Singleton
{
    private static readonly object Instancelock = new object();
    private Singleton()
    {
    }
    private static Singleton instance = null;

    public static Singleton GetInstance
    {
        get
        {
            if (instance == null)
            {
                lock (Instancelock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

List all kafka topics

Kafka uses ZooKeeper so you need to first start a ZooKeeper server if you don't already have one.

If you do not want to install and have a separate zookeeper server, you can use the convenience script packaged with kafka to get a quick-and-dirty single-node ZooKeeper instance.

Starting the single-node Zookeeper instance:

bin/zookeeper-server-start.sh config/zookeeper.properties

Starting the Kafka Server:

bin/kafka-server-start.sh config/server.properties

Listing the Topics available in Kafka:

bin/kafka-topics.sh --list --zookeeper localhost:2181

How to update value of a key in dictionary in c#?

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5

How and where are Annotations used in Java?

Following are some of the places where you can use annotations.

a. Annotations can be used by compiler to detect errors and suppress warnings
b. Software tools can use annotations to generate code, xml files, documentation etc., For example, Javadoc use annotations while generating java documentation for your class.
c. Runtime processing of the application can be possible via annotations.
d. You can use annotations to describe the constraints (Ex: @Null, @NotNull, @Max, @Min, @Email).
e. Annotations can be used to describe type of an element. Ex: @Entity, @Repository, @Service, @Controller, @RestController, @Resource etc.,
f. Annotation can be used to specify the behaviour. Ex: @Transactional, @Stateful
g. Annotation are used to specify how to process an element. Ex: @Column, @Embeddable, @EmbeddedId
h. Test frameworks like junit and testing use annotations to define test cases (@Test), define test suites (@Suite) etc.,
i. AOP (Aspect Oriented programming) use annotations (@Before, @After, @Around etc.,)
j. ORM tools like Hibernate, Eclipselink use annotations

You can refer this link for more details on annotations.

You can refer this link to see how annotations are used to build simple test suite.

Server configuration is missing in Eclipse

Did you, by any chance, deleted stuff from your workspace, or moved it around?

When you create a server for the first time, either globally or through the project's "run on server" settings, Eclipse creates a project in the Servers view, as BalusC pointed out. Eclipse stores this server inside your workspace, in a project called Servers. The project needs to be open for tomcat to run.

(If you want, you can store the server settings elsewher. You can right click and open the server instance from the Servers view and configure various parameters and locations)

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

Can we have functions inside functions in C++?

No.

What are you trying to do?

workaround:

int main(void)
{
  struct foo
  {
    void operator()() { int a = 1; }
  };

  foo b;
  b(); // call the operator()

}

nginx missing sites-available directory

If you'd prefer a more direct approach, one that does NOT mess with symlinking between /etc/nginx/sites-available and /etc/nginx/sites-enabled, do the following:

  1. Locate your nginx.conf file. Likely at /etc/nginx/nginx.conf
  2. Find the http block.
  3. Somewhere in the http block, write include /etc/nginx/conf.d/*.conf; This tells nginx to pull in any files in the conf.d directory that end in .conf. (I know: it's weird that a directory can have a . in it.)
  4. Create the conf.d directory if it doesn't already exist (per the path in step 3). Be sure to give it the right permissions/ownership. Likely root or www-data.
  5. Move or copy your separate config files (just like you have in /etc/nginx/sites-available) into the directory conf.d.
  6. Reload or restart nginx.
  7. Eat an ice cream cone.

Any .conf files that you put into the conf.d directory from here on out will become active as long as you reload/restart nginx after.

Note: You can use the conf.d and sites-enabled + sites-available method concurrently if you wish. I like to test on my dev box using conf.d. Feels faster than symlinking and unsymlinking.

How do I convert Word files to PDF programmatically?

Seems to be some relevent info here:

Converting MS Word Documents to PDF in ASP.NET

Also, with Office 2007 having publish to PDF functionality, I guess you could use office automation to open the *.DOC file in Word 2007 and Save as PDF. I'm not too keen on office automation as it's slow and prone to hanging, but just throwing that out there...

How to get URL of current page in PHP

 $uri = $_SERVER['REQUEST_URI'];

This will give you the requested directory and file name. If you use mod_rewrite, this is extremely useful because it tells you what page the user was looking at.

If you need the actual file name, you might want to try either $_SERVER['PHP_SELF'], the magic constant __FILE__, or $_SERVER['SCRIPT_FILENAME']. The latter 2 give you the complete path (from the root of the server), rather than just the root of your website. They are useful for includes and such.

$_SERVER['PHP_SELF'] gives you the file name relative to the root of the website.

 $relative_path = $_SERVER['PHP_SELF'];
 $complete_path = __FILE__;
 $complete_path = $_SERVER['SCRIPT_FILENAME'];

How to create UILabel programmatically using Swift?

Another code swift3

let myLabel = UILabel()
    myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    myLabel.center = CGPoint(x: 0, y: 0)
    myLabel.textAlignment = .center
    myLabel.text = "myLabel!!!!!"
    self.view.addSubview(myLabel)

How to copy selected files from Android with adb pull

You can move your files to other folder and then pull whole folder.

adb shell mkdir /sdcard/tmp
adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir
adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end)
adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back
adb shell rmdir /sdcard/tmp # remove temporary directory

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

How do I tell if a regular file does not exist in Bash?

There are three distinct ways to do this:

  1. Negate the exit status with bash (no other answer has said this):

    if ! [ -e "$file" ]; then
        echo "file does not exist"
    fi
    

    Or:

    ! [ -e "$file" ] && echo "file does not exist"
    
  2. Negate the test inside the test command [ (that is the way most answers before have presented):

    if [ ! -e "$file" ]; then
        echo "file does not exist"
    fi
    

    Or:

    [ ! -e "$file" ] && echo "file does not exist"
    
  3. Act on the result of the test being negative (|| instead of &&):

    Only:

    [ -e "$file" ] || echo "file does not exist"
    

    This looks silly (IMO), don't use it unless your code has to be portable to the Bourne shell (like the /bin/sh of Solaris 10 or earlier) that lacked the pipeline negation operator (!):

    if [ -e "$file" ]; then
        :
    else
        echo "file does not exist"
    fi
    

Regex: match everything but specific pattern

Not a regexp expert, but I think you could use a negative lookahead from the start, e.g. ^(?!foo).*$ shouldn't match anything starting with foo.

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

Matplotlib-Animation "No MovieWriters Available"

If you are using Ubuntu 14.04 ffmpeg is not available. You can install it by using the instructions directly from https://www.ffmpeg.org/download.html.

In short you will have to:

sudo add-apt-repository ppa:mc3man/trusty-media
sudo apt-get update
sudo apt-get install ffmpeg gstreamer0.10-ffmpeg

If this does not work maybe try using sudo apt-get dist-upgrade but this may broke things in your system.

What's the difference between unit tests and integration tests?

A unit test should have no dependencies on code outside the unit tested. You decide what the unit is by looking for the smallest testable part. Where there are dependencies they should be replaced by false objects. Mocks, stubs .. The tests execution thread starts and ends within the smallest testable unit.

When false objects are replaced by real objects and tests execution thread crosses into other testable units, you have an integration test

How to get a tab character?

put it in between <pre></pre> tags then use this characters &#9;

it would not work without the <pre></pre> tags

Mac SQLite editor

Sqliteman is my current preference: It uses QT, so it's cross-platform. Since I develop on Windows, Linux and OS X, it helps to have the same tools available on each.

I also tried SQLite Admin (Windows, so irrelevant to the question anyway) for a while, but it seems unmaintained these days, and has the most annoying hotkeys of any application I've ever used - Ctrl-S clears the current query, with no hope of undo.

g++ undefined reference to typeinfo

I encounter an situation that is rare, but this may help other friends in similar situation. I have to work on an older system with gcc 4.4.7. I have to compile code with c++11 or above support, so I build the latest version of gcc 5.3.0. When building my code and linking to the dependencies if the dependency is build with older compiler, then I got 'undefined reference to' error even though I clearly defined the linking path with -L/path/to/lib -llibname. Some packages such as boost and projects build with cmake usually has a tendency to use the older compiler, and they usually cause such problems. You have to go a long way to make sure they use the newer compiler.

error: command 'gcc' failed with exit status 1 on CentOS

I bet you have to install libxml2-devel or libxml++-devel or even python-devel. But it is only a wild guess, not seeing the actual error from the log file. But it seems gcc is missing either a header file or a library file.

Multiple github accounts on the same computer?

This answer is for beginners (none-git gurus). I recently had this problem and maybe its just me but most of the answers seemed to require rather advance understanding of git. After reading several stack overflow answers including this thread, here are the steps I needed to take in order to easily switch between GitHub accounts (e.g. assume two GitHub accounts, github.com/personal and gitHub.com/work):

  1. Check for existing ssh keys: Open Terminal and run this command to see/list existing ssh keys ls -al ~/.ssh
    files with extension .pub are your ssh keys so you should have two for the personal and work accounts. If there is only one or none, its time to generate other wise skip this.

    - Generating ssh key: login to github (either the personal or work acc.), navigate to Settings and copy the associated email.
    now go back to Terminal and run ssh-keygen -t rsa -C "the copied email", you'll see:

    Generating public/private rsa key pair.
    Enter file in which to save the key (/.../.ssh/id_rsa):


    id_rsa is the default name for the soon to be generated ssh key so copy the path and rename the default, e.g. /.../.ssh/id_rsa_work if generating for work account. provide a password or just enter to ignore and, you'll read something like The key's randomart image is: and the image. done.
    Repeat this step once more for your second github account. Make sure you use the right email address and a different ssh key name (e.g. id_rsa_personal) to avoid overwriting.
    At this stage, you should see two ssh keys when running ls -al ~/.ssh again.
  2. Associate ssh key with gitHub account: Next step is to copy one of the ssh keys, run this but replacing your own ssh key name: pbcopy < ~/.ssh/id_rsa_work.pub, replace id_rsa_work.pub with what you called yours.
    Now that our ssh key is copied to clipboard, go back to github account [Make sure you're logged in to work account if the ssh key you copied is id_rsa_work] and navigate to
    Settings - SSH and GPG Keys and click on New SSH key button (not New GPG key btw :D)
    give some title for this key, paste the key and click on Add SSH key. You've now either successfully added the ssh key or noticed it has been there all along which is fine (or you got an error because you selected New GPG key instead of New SSH key :D).
  3. Associate ssh key with gitHub account: Repeat the above step for your second account.
  4. Edit the global git configuration: Last step is to make sure the global configuration file is aware of all github accounts (so to say).
    Run git config --global --edit to edit this global file, if this opens vim and you don't know how to use it, press i to enter Insert mode, edit the file as below, and press esc followed by :wq to exit insert mode:

    [inside this square brackets give a name to the followed acc.] name = github_username email = github_emailaddress [any other name] name = github_username email = github_email [credential] helper = osxkeychain useHttpPath = true

Done!, now when trying to push or pull from a repo, you'll be asked which GitHub account should be linked with this repo and its asked only once, the local configuration will remember this link and not the global configuration so you can work on different repos that are linked with different accounts without having to edit global configuration each time.

trim left characters in sql server?

You can use LEN in combination with SUBSTRING:

SELECT SUBSTRING(myColumn, 7, LEN(myColumn)) from myTable

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

Oracle listener not running and won't start

Problem

The listener service is stopped in services.msc.

Cause

User password was changed.

Solution

  • Open services.msc.
  • Right-click the specific listener service.
  • Click Properties.
  • Click the Logon tab.
  • Change the password.
  • Click OK.
  • Start the service.

How To Run PHP From Windows Command Line in WAMPServer

The PHP CLI as its called ( php for the Command Line Interface ) is called php.exe It lives in c:\wamp\bin\php\php5.x.y\php.exe ( where x and y are the version numbers of php that you have installed )

If you want to create php scrips to run from the command line then great its easy and very useful.

Create yourself a batch file like this, lets call it phppath.cmd :

PATH=%PATH%;c:\wamp\bin\php\phpx.y.z
php -v

Change x.y.z to a valid folder name for a version of PHP that you have installed within WAMPServer

Save this into one of your folders that is already on your PATH, so you can run it from anywhere.

Now from a command window, cd into your source folder and run >phppath.

Then run

php your_script.php

It should work like a dream.

Here is an example that configures PHP Composer and PEAR if required and they exist

@echo off

REM **************************************************************
REM * PLACE This file in a folder that is already on your PATH
REM * Or just put it in your C:\Windows folder as that is on the
REM * Search path by default
REM * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
REM * EDIT THE NEXT 3 Parameters to fit your installed WAMPServer
REM **************************************************************


set baseWamp=D:\wamp
set defaultPHPver=7.4.3
set composerInstalled=%baseWamp%\composer
set phpFolder=\bin\php\php

if %1.==. (
    set phpver=%baseWamp%%phpFolder%%defaultPHPver%
) else (
    set phpver=%baseWamp%%phpFolder%%1
)

PATH=%PATH%;%phpver%
php -v
echo ---------------------------------------------------------------


REM IF PEAR IS INSTALLED IN THIS VERSION OF PHP

IF exist %phpver%\pear (
    set PHP_PEAR_SYSCONF_DIR=%baseWamp%%phpFolder%%phpver%
    set PHP_PEAR_INSTALL_DIR=%baseWamp%%phpFolder%%phpver%\pear
    set PHP_PEAR_DOC_DIR=%baseWamp%%phpFolder%%phpver%\docs
    set PHP_PEAR_BIN_DIR=%baseWamp%%phpFolder%%phpver%
    set PHP_PEAR_DATA_DIR=%baseWamp%%phpFolder%%phpver%\data
    set PHP_PEAR_PHP_BIN=%baseWamp%%phpFolder%%phpver%\php.exe
    set PHP_PEAR_TEST_DIR=%baseWamp%%phpFolder%%phpver%\tests

    echo PEAR INCLUDED IN THIS CONFIG
    echo ---------------------------------------------------------------
) else (
    echo PEAR DOES NOT EXIST IN THIS VERSION OF php
    echo ---------------------------------------------------------------
)

REM IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM **************************************************************
REM * IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM *
REM * This assumes that composer is installed in /wamp/composer
REM *
REM **************************************************************
IF EXIST %composerInstalled% (
    ECHO COMPOSER INCLUDED IN THIS CONFIG
    echo ---------------------------------------------------------------
    set COMPOSER_HOME=%baseWamp%\composer
    set COMPOSER_CACHE_DIR=%baseWamp%\composer

    PATH=%PATH%;%baseWamp%\composer

    rem echo TO UPDATE COMPOSER do > composer self-update
    echo ---------------------------------------------------------------
) else (
    echo ---------------------------------------------------------------
    echo COMPOSER IS NOT INSTALLED
    echo ---------------------------------------------------------------
)

set baseWamp=
set defaultPHPver=
set composerInstalled=
set phpFolder=

Call this command file like this to use the default version of PHP

> phppath

Or to get a specific version of PHP like this

> phppath 5.6.30

How do I add a foreign key to an existing SQLite table?

Please check https://www.sqlite.org/lang_altertable.html#otheralter

The only schema altering commands directly supported by SQLite are the "rename table" and "add column" commands shown above. However, applications can make other arbitrary changes to the format of a table using a simple sequence of operations. The steps to make arbitrary changes to the schema design of some table X are as follows:

  1. If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF.
  2. Start a transaction.
  3. Remember the format of all indexes and triggers associated with table X. This information will be needed in step 8 below. One way to do this is to run a query like the following: SELECT type, sql FROM sqlite_master WHERE tbl_name='X'.
  4. Use CREATE TABLE to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
  5. Transfer content from X into new_X using a statement like: INSERT INTO new_X SELECT ... FROM X.
  6. Drop the old table X: DROP TABLE X.
  7. Change the name of new_X to X using: ALTER TABLE new_X RENAME TO X.
  8. Use CREATE INDEX and CREATE TRIGGER to reconstruct indexes and triggers associated with table X. Perhaps use the old format of the triggers and indexes saved from step 3 above as a guide, making changes as appropriate for the alteration.
  9. If any views refer to table X in a way that is affected by the schema change, then drop those views using DROP VIEW and recreate them with whatever changes are necessary to accommodate the schema change using CREATE VIEW.
  10. If foreign key constraints were originally enabled then run PRAGMA foreign_key_check to verify that the schema change did not break any foreign key constraints.
  11. Commit the transaction started in step 2.
  12. If foreign keys constraints were originally enabled, reenable them now.

The procedure above is completely general and will work even if the schema change causes the information stored in the table to change. So the full procedure above is appropriate for dropping a column, changing the order of columns, adding or removing a UNIQUE constraint or PRIMARY KEY, adding CHECK or FOREIGN KEY or NOT NULL constraints, or changing the datatype for a column, for example.

Why does "return list.sort()" return None, not the list?

Here is an email from Guido van Rossum in Python's dev list explaining why he choose not to return self on operations that affects the object and don't return a new one.

This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:

 x.compress().chop(y).sort(z)

which would be the same as

  x.compress()
  x.chop(y)
  x.sort(z)

I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else.

I'd like to reserve chaining for operations that return new values, like string processing operations:

 y = x.rstrip("\n").split(":").lower()

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

To find them, you can use this

;WITH cte AS
(
   SELECT 0 AS CharCode
   UNION ALL
   SELECT CharCode + 1 FROM cte WHERE CharCode <31
)
SELECT
   *
FROM
   mytable T
     cross join cte
WHERE
   EXISTS (SELECT *
        FROM mytable Tx
        WHERE Tx.PKCol = T.PKCol
             AND
              Tx.MyField LIKE '%' + CHAR(cte.CharCode) + '%'
         )

Replacing the EXISTS with a JOIN will allow you to REPLACE them, but you'll get multiple rows... I can't think of a way around that...

Is it possible to interactively delete matching search pattern in Vim?

1. In my opinion, the most convenient way is to search for one occurrence first, and then invoke the following :substitute command:

:%s///gc

Since the pattern is empty, this :substitute command will look for the occurrences of the last-used search pattern, and will then replace them with the empty string, each time asking for user confirmation, realizing exactly the desired behavior.

2. If it is a common pattern in one’s editing habits, one can further define a couple of text-object selection mappings to operate specifically on the match of the last search pattern under the cursor. The following two mappings can be used in both Visual and Operator-pending modes to select the text of the preceding match of the last search pattern.

vnoremap <silent> i/ :<c-u>call SelectMatch()<cr>
onoremap <silent> i/ :call SelectMatch()<cr>
function! SelectMatch()
    if search(@/, 'bcW')
        norm! v
        call search(@/, 'ceW')
    else
        norm! gv
    endif
endfunction

Using these mappings one can delete the match under the cursor with di/, or apply any other operator or visually select it with vi/.

SQL Server loop - how do I loop through a set of records

Just another approach if you are fine using temp tables.I have personally tested this and it will not cause any exception (even if temp table does not have any data.)

CREATE TABLE #TempTable
(
    ROWID int identity(1,1) primary key,
    HIERARCHY_ID_TO_UPDATE int,
)

--create some testing data
--INSERT INTO #TempTable VALUES(1)
--INSERT INTO #TempTable VALUES(2)
--INSERT INTO #TempTable VALUES(4)
--INSERT INTO #TempTable VALUES(6)
--INSERT INTO #TempTable VALUES(8)

DECLARE @MAXID INT, @Counter INT

SET @COUNTER = 1
SELECT @MAXID = COUNT(*) FROM #TempTable

WHILE (@COUNTER <= @MAXID)
BEGIN
    --DO THE PROCESSING HERE 
    SELECT @HIERARCHY_ID_TO_UPDATE = PT.HIERARCHY_ID_TO_UPDATE
    FROM #TempTable AS PT
    WHERE ROWID = @COUNTER

    SET @COUNTER = @COUNTER + 1
END


IF (OBJECT_ID('tempdb..#TempTable') IS NOT NULL)
BEGIN
    DROP TABLE #TempTable
END

Deserialize a json string to an object in python

There are different methods to deserialize json string to an object. All above methods are acceptable but I suggest using a library to prevent duplicate key issues or serializing/deserializing of nested objects.

Pykson, is a JSON Serializer and Deserializer for Python which can help you achieve. Simply define Payload class model as JsonObject then use Pykson to convert json string to object.

from pykson import Pykson, JsonObject, StringField

class Payload(pykson.JsonObject):
    action = StringField()
    method = StringField()
    data = StringField()

json_text = '{"action":"print","method":"onData","data":"Madan Mohan"}'
payload = Pykson.from_json(json_text, Payload)

cannot make a static reference to the non-static field

the lines

account.withdraw(balance, 2500);
account.deposit(balance, 3000);

you might want to make withdraw and deposit non-static and let it modify the balance

public void withdraw(double withdrawAmount) {
    balance = balance - withdrawAmount;
}

public void deposit(double depositAmount) {
    balance = balance + depositAmount;
}   

and remove the balance parameter from the call

How can I determine the current CPU utilization from the shell?

You need to sample the load average for several seconds and calculate the CPU utilization from that. If unsure what to you, get the sources of "top" and read it.

CSS smooth bounce animation

In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:

.ball {
  animation: bounce 1s infinite alternate;
  -webkit-animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from {
    margin-top: 0;
  }
  to {
    margin-top: -15px;
  }
}

Import CSV to SQLite

I am merging info from previous answers here with my own experience. The easiest is to add the comma-separated table headers directly to your csv file, followed by a new line, and then all your csv data.

If you are never doing sqlite stuff again (like me), this might save you a web search or two:

In the Sqlite shell enter:

$ sqlite3 yourfile.sqlite
sqlite>  .mode csv
sqlite>  .import test.csv yourtable
sqlite>  .exit

If you haven't got Sqlite installed on your Mac, run

$ brew install sqlite3

You may need to do one web search for how to install Homebrew.

Easiest way to convert int to string in C++

Use:

#include<iostream>
#include<string>

std::string intToString(int num);

int main()
{
    int integer = 4782151;

    std::string integerAsStr = intToString(integer);

    std::cout << "integer = " << integer << std::endl;
    std::cout << "integerAsStr = " << integerAsStr << std::endl;

    return 0;
}

std::string intToString(int num)
{
    std::string numAsStr;
    bool isNegative = num < 0;
    if(isNegative) num*=-1;

    do
    {
       char toInsert = (num % 10) + 48;
       numAsStr.insert(0, 1, toInsert);

       num /= 10;
    }while (num);
  
    return isNegative? numAsStr.insert(0, 1, '-') : numAsStr;
}

Registry key Error: Java version has value '1.8', but '1.7' is required

The error is explicit ...

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.8', but '1.7' is required.

Error: could not find java.dll

Error: Could not find Java SE Runtime Environment.

... you are attempting to use the java.exe 1.7 executable while the HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment > CurrentVersion registry key has the value 1.8.

The recurring theme to proposed solutions is that the error is a configuration error. The error can be solved in various different manners (e.g. reconfiguration of the users environment or removal of java executables with fingers-crossed and hope that there exists another fallback java.exe in the users %PATH% and that the fallback java.exe is the correct executable).

The correct solution depends on what you're trying to achieve: "are you trying to downgrade from jdk-8 to jdk-7? Are trying to upgrade to jdk-8? ..."

Reproduction steps

  1. install jdk-7u80-windows-x64.exe

notes:

  • the java.exe executable available in the users %PATH% is installed in C:\Windows\System32
  • the installation does not update the users %PATH%
  • the HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment > CurrentVersion string registry entry is created (among others) with the value 1.7
  1. install jdk-8u191-windows-x64.exe

notes:

  • the users %PATH% is updated to include C:\Program Files (x86)\Common Files\Oracle\Java\javapath as the first entry
  • the the HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment > CurrentVersion string registry entries value is updated to 1.8
  1. update the users %PATH% environment variable, remove C:\Program Files (x86)\Common Files\Oracle\Java\javapath

  2. in a new command prompt java -version

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.8', but '1.7' is required.

Error: could not find java.dll

Error: Could not find Java SE Runtime Environment.

Solution(s)

  1. OP's solution https://stackoverflow.com/a/29769311/1423507 is a "fingers-crossed and hope that there exists a fallback java.exe in the users %PATH% and that the fallback executable is correct" approach to the error. Given the reproduction steps, removing the java.exe, javaw.exe and javaws.exe executables from C:\Windows\System32 (only in my case) will result in no longer having any java.exe present in the users %PATH% resulting in the error 'java' is not recognized as an internal or external command, operable program or batch file. which is not so much of a solution.

  2. answers https://stackoverflow.com/a/35775493/1423507 and https://stackoverflow.com/a/36516620/1423507 work however you're reverting to using java.exe 1.7 (e.g. update the CurrentVersion registry key's value to match the java.exe version found in the users %PATH%).

  3. make surejava.exe 1.8 is the first found in the users %PATH% (how you do that is irrelevant) i.e.:

    • update the users %PATH% to include C:\Program Files (x86)\Common Files\Oracle\Java\javapath first (ensure that the executables in that directory are correct)
    • update the users %PATH% to include the absolute path of your java binaries first (set PATH="C:\Program Files\Java\jre1.8.0_191\bin;%PATH%")
    • set java specific environment variables and update the users %PATH% with them (set JAVA_HOME="C:\Program Files\Java"; set JRE_HOME=%JAVA_HOME%\jre1.8.0_191; set PATH=%JRE_HOME%\bin;%PATH%)

How do I save a stream to a file in C#?

private void SaveFileStream(String path, Stream stream)
{
    var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
    stream.CopyTo(fileStream);
    fileStream.Dispose();
}

How to print pthread_t

OK, seems this is my final answer. We have 2 actual problems:

  • How to get shorter unique IDs for thread for logging.
  • Anyway we need to print real pthread_t ID for thread (just to link to POSIX values at least).

1. Print POSIX ID (pthread_t)

You can simply treat pthread_t as array of bytes with hex digits printed for each byte. So you aren't limited by some fixed size type. The only issue is byte order. You probably like if order of your printed bytes is the same as for simple "int" printed. Here is example for little-endian and only order should be reverted (under define?) for big-endian:

#include <pthread.h>
#include <stdio.h>

void print_thread_id(pthread_t id)
{
    size_t i;
    for (i = sizeof(i); i; --i)
        printf("%02x", *(((unsigned char*) &id) + i - 1));
}

int main()
{
    pthread_t id = pthread_self();

    printf("%08x\n", id);
    print_thread_id(id);

    return 0;
}

2. Get shorter printable thread ID

In any of proposed cases you should translate real thread ID (posix) to index of some table. But there is 2 significantly different approaches:

2.1. Track threads.

You may track threads ID of all the existing threads in table (their pthread_create() calls should be wrapped) and have "overloaded" id function that get you just table index, not real thread ID. This scheme is also very useful for any internal thread-related debug an resources tracking. Obvious advantage is side effect of thread-level trace / debug facility with future extension possible. Disadvantage is requirement to track any thread creation / destruction.

Here is partial pseudocode example:

pthread_create_wrapper(...)
{
   id = pthread_create(...)
   add_thread(id);
}

pthread_destruction_wrapper()
{
   /* Main problem is it should be called.
      pthread_cleanup_*() calls are possible solution. */
   remove_thread(pthread_self());
}

unsigned thread_id(pthread_t known_pthread_id)
{
  return seatch_thread_index(known_pthread_id);
}

/* user code */
printf("04x", thread_id(pthread_self()));

2.2. Just register new thread ID.

During logging call pthread_self() and search internal table if it know thread. If thread with such ID was created its index is used (or re-used from previously thread, actually it doesn't matter as there are no 2 same IDs for the same moment). If thread ID is not known yet, new entry is created so new index is generated / used.

Advantage is simplicity. Disadvantage is no tracking of thread creation / destruction. So to track this some external mechanics is required.

Failed to authenticate on SMTP server error using gmail

Did you turn on the "Allow less secure apps" on? go to this link

https://myaccount.google.com/security#connectedapps

Take a look at the Sign-in & security -> Apps with account access menu.

You must turn the option "Allow less secure apps" ON.

If is still doesn't work try one of these:

And change your .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=xxxxxx
MAIL_ENCRYPTION=tls

because the one's you have specified in the mail.php will only be used if the value is not available in the .env file.

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

How to show all of columns name on pandas dataframe?

A quick and dirty solution would be to convert it to a string

print('\t'.join(data_all2.columns))

would cause all of them to be printed out separated by tabs Of course, do note that with 102 names, all of them rather long, this will be a bit hard to read through

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

python ValueError: invalid literal for float()

I would all but guarantee that the issue is some sort of non-printing character that's present in the value you pulled off your socket. It looks like you're using Python 2.x, in which case you can check for them with this:

print repr(temp)

You'll likely see something in there that's escaped in the form \x00. These non-printing characters don't show up when you print directly to the console, but their presence is enough to negatively impact the parsing of a string value into a float.

-- Edited for question changes --

It turns this is partly accurate for your issue - the root cause however appears to be that you're reading more information than you expect from your socket or otherwise receiving multiple values. You could do something like

map(float, temp.strip().split('\r\n'))

In order to convert each of the values, but if your function is supposed to return a single float value this is likely to cause confusion. Anyway, the issue certainly revolves around the presence of characters you did not expect to see in the value you retrieved from your socket.

MAMP mysql server won't start. No mysql processes are running

rm /Applications/MAMP/db/mysql56/*

Works fine, but then it shows "No database found" in phpmyadmin although there are databases, so my drupal gave me errors because of this.

All I need to do is simply remove two files ib_logfile0 and ib_logfile1 from /Applications/MAMP/db/mysql56/ and that did the trick for me.

How to hide first section header in UITableView (grouped style)

Update[9/19/17]: Old answer doesn't work for me anymore in iOS 11. Thanks Apple. The following did:

self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
self.tableView.estimatedSectionHeaderHeight = 20.0f;
self.tableView.contentInset = UIEdgeInsetsMake(-18.0, 0.0f, 0.0f, 0.0);

Previous Answer:

As posted in the comments by Chris Ostomo the following worked for me:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN; // to get rid of empty section header
}

Convert SVG to PNG in Python

Here is an approach where Inkscape is called by Python.

Note that it suppresses certain crufty output that Inkscape writes to the console (specifically, stderr and stdout) during normal error-free operation. The output is captured in two string variables, out and err.

import subprocess               # May want to use subprocess32 instead

cmd_list = [ '/full/path/to/inkscape', '-z', 
             '--export-png', '/path/to/output.png',
             '--export-width', 100,
             '--export-height', 100,
             '/path/to/input.svg' ]

# Invoke the command.  Divert output that normally goes to stdout or stderr.
p = subprocess.Popen( cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE )

# Below, < out > and < err > are strings or < None >, derived from stdout and stderr.
out, err = p.communicate()      # Waits for process to terminate

# Maybe do something with stdout output that is in < out >
# Maybe do something with stderr output that is in < err >

if p.returncode:
    raise Exception( 'Inkscape error: ' + (err or '?')  )

For example, when running a particular job on my Mac OS system, out ended up being:

Background RRGGBBAA: ffffff00
Area 0:0:339:339 exported to 100 x 100 pixels (72.4584 dpi)
Bitmap saved as: /path/to/output.png

(The input svg file had a size of 339 by 339 pixels.)

Assign variable in if condition statement, good practice or not?

you could do something like so:

if (value = /* sic */ some_function()){
  use_value(value)
}

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Bootstrap 4 (^beta) has changed the classes for responsive hiding/showing elements. See this link for correct classes to use: http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

move div with CSS transition

I added the vendor prefixes, and changed the animation to all, so you have both opacity and width that are animated.

Is this what you're looking for ? http://jsfiddle.net/u2FKM/3/

How to get current url in view in asp.net core 1.0

If you're looking to also get the port number out of the request you'll need to access it through the Request.Host property for AspNet Core.

The Request.Host property is not simply a string but, instead, an object that holds both the host domain and the port number. If the port number is specifically written out in the URL (i.e. "https://example.com:8080/path/to/resource"), then calling Request.Host will give you the host domain and the port number like so: "example.com:8080".

If you only want the value for the host domain or only want the value for the port number then you can access those properties individually (i.e. Request.Host.Host or Request.Host.Port).

git replacing LF with CRLF

I had this problem too.

SVN doesn't do any line ending conversion, so files are committed with CRLF line endings intact. If you then use git-svn to put the project into git then the CRLF endings persist across into the git repository, which is not the state git expects to find itself in - the default being to only have unix/linux (LF) line endings checked in.

When you then check out the files on windows, the autocrlf conversion leaves the files intact (as they already have the correct endings for the current platform), however the process that decides whether there is a difference with the checked in files performs the reverse conversion before comparing, resulting in comparing what it thinks is an LF in the checked out file with an unexpected CRLF in the repository.

As far as I can see your choices are:

  1. Re-import your code into a new git repository without using git-svn, this will mean line endings are converted in the intial git commit --all
  2. Set autocrlf to false, and ignore the fact that the line endings are not in git's preferred style
  3. Check out your files with autocrlf off, fix all the line endings, check everything back in, and turn it back on again.
  4. Rewrite your repository's history so that the original commit no longer contains the CRLF that git wasn't expecting. (The usual caveats about history rewriting apply)

Footnote: if you choose option #2 then my experience is that some of the ancillary tools (rebase, patch etc) do not cope with CRLF files and you will end up sooner or later with files with a mix of CRLF and LF (inconsistent line endings). I know of no way of getting the best of both.

How do you enable auto-complete functionality in Visual Studio C++ express edition?

Include the class that you are using Within your text file, then intelliSense will know where to look when you type within your text file. This works for me.

So it’s important to check the Unreal API to see where the included class is so that you have the path to type on the include line. Hope that makes sense.

PHP isset() with multiple parameters

The parameter(s) to isset() must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:

if (isset($_POST['search_term'], $_POST['postcode'])) {
}

This will return true only if all arguments to isset() are set and do not contain null.

Note that isset($var) and isset($var) == true have the same effect, so the latter is somewhat redundant.

Update

The second part of your expression uses empty() like this:

empty ($_POST['search_term'] . $_POST['postcode']) == false

This is wrong for the same reasons as above. In fact, you don't need empty() here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:

isset($_POST['search_term'], $_POST['postcode']) && 
    $_POST['search_term'] && 
    $_POST['postcode']

Or using an equivalent expression:

!empty($_POST['search_term']) && !empty($_POST['postcode'])

Final thoughts

You should consider using filter functions to manage the inputs:

$data = filter_input_array(INPUT_POST, array(
    'search_term' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
    'postcode' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
));

if ($data === null || in_array(null, $data, true)) {
    // some fields are missing or their values didn't pass the filter
    die("You did something naughty");
}

// $data['search_term'] and $data['postcode'] contains the fields you want

Btw, you can customize your filters to check for various parts of the submitted values.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

An established connection was aborted by the software in your host machine

In My Case, I was running Android Studio and Eclipse at a time. AS and Eclipse were trying to communicate a device/emulator through adb.

Solution: I closed Android Studio. Then I restarted Eclipse.

Hope this helps you :)

When should I use "this" in a class?

To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.

If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.

Access denied for user 'test'@'localhost' (using password: YES) except root user

For anyone else who did all the advice but the problem still persists.

Check for stored procedure and view DEFINERS. Those definers may no longer exists.

My problem showed up when we changed the wildcard host (%) to IP specific, making the database more secure. Unfortunately there are some views that are still using 'user'@'%' even though 'user'@'172....' is technically correct.

How to create a GUID in Excel?

I am using the following function in v.2013 excel vba macro code

Public Function GetGUID() As String 
    GetGUID = Mid$(CreateObject("Scriptlet.TypeLib").GUID, 2, 36) 
End Function 

How do I resize a Google Map with JavaScript after it has loaded?

If you're using Google Maps v2, call checkResize() on your map after resizing the container. link

UPDATE

Google Maps JavaScript API v2 was deprecated in 2011. It is not available anymore.

When a 'blur' event occurs, how can I find out which element focus went *to*?

You can fix IE with :

 event.currentTarget.firstChild.ownerDocument.activeElement

It looks like "explicitOriginalTarget" for FF.

Antoine And J

How to disable submit button once it has been clicked?

Using JQuery, you can do this..

$("#submitbutton").click(
   function() {
      alert("Sending...");
      window.location.replace("path to url");
   }
);

Counting the number of files in a directory using Java

Since Java 8, you can do that in three lines:

try (Stream<Path> files = Files.list(Paths.get("your/path/here"))) {
    long count = files.count();
}

Regarding the 5000 child nodes and inode aspects:

This method will iterate over the entries but as Varkhan suggested you probably can't do better besides playing with JNI or direct system commands calls, but even then, you can never be sure these methods don't do the same thing!

However, let's dig into this a little:

Looking at JDK8 source, Files.list exposes a stream that uses an Iterable from Files.newDirectoryStream that delegates to FileSystemProvider.newDirectoryStream.

On UNIX systems (decompiled sun.nio.fs.UnixFileSystemProvider.class), it loads an iterator: A sun.nio.fs.UnixSecureDirectoryStream is used (with file locks while iterating through the directory).

So, there is an iterator that will loop through the entries here.

Now, let's look to the counting mechanism.

The actual count is performed by the count/sum reducing API exposed by Java 8 streams. In theory, this API can perform parallel operations without much effort (with multihtreading). However the stream is created with parallelism disabled so it's a no go...

The good side of this approach is that it won't load the array in memory as the entries will be counted by an iterator as they are read by the underlying (Filesystem) API.

Finally, for the information, conceptually in a filesystem, a directory node is not required to hold the number of the files that it contains, it can just contain the list of it's child nodes (list of inodes). I'm not an expert on filesystems, but I believe that UNIX filesystems work just like that. So you can't assume there is a way to have this information directly (i.e: there can always be some list of child nodes hidden somewhere).

How can I link a photo in a Facebook album to a URL

You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."

Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.

Update:

The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg

Run Jquery function on window events: load, resize, and scroll?

just call your function inside the events.

load:

$(document).ready(function(){  // or  $(window).load(function(){
    topInViewport($(mydivname));
});

resize:

$(window).resize(function () {
    topInViewport($(mydivname));
});

scroll:

$(window).scroll(function () {
    topInViewport($(mydivname));
});

or bind all event in one function

$(window).on("load scroll resize",function(e){

Is there a way to do repetitive tasks at intervals?

A broader answer to this question might consider the Lego brick approach often used in Occam, and offered to the Java community via JCSP. There is a very good presentation by Peter Welch on this idea.

This plug-and-play approach translates directly to Go, because Go uses the same Communicating Sequential Process fundamentals as does Occam.

So, when it comes to designing repetitive tasks, you can build your system as a dataflow network of simple components (as goroutines) that exchange events (i.e. messages or signals) via channels.

This approach is compositional: each group of small components can itself behave as a larger component, ad infinitum. This can be very powerful because complex concurrent systems are made from easy to understand bricks.

Footnote: in Welch's presentation, he uses the Occam syntax for channels, which is ! and ? and these directly correspond to ch<- and <-ch in Go.

Selenium WebDriver can't find element by link text

Use xpath and text()

driver.findElement(By.Xpath("//strong[contains(text(),'" + service +"')]"));

How to prevent Browser cache for php site

I had problem with caching my css files. Setting headers in PHP didn't help me (perhaps because the headers would need to be set in the stylesheet file instead of the page linking to it?).

I found the solution on this page: https://css-tricks.com/can-we-prevent-css-caching/

The solution:

Append timestamp as the query part of the URI for the linked file.
(Can be used for css, js, images etc.)

For development:

<link rel="stylesheet" href="style.css?<?php echo date('Y-m-d_H:i:s'); ?>">

For production (where caching is mostly a good thing):

<link rel="stylesheet" type="text/css" href="style.css?version=3.2">
(and rewrite manually when it is required)

Or combination of these two:

<?php
    define( "DEBUGGING", true ); // or false in production enviroment
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo (DEBUGGING) ? date('_Y-m-d_H:i:s') : ""; ?>">

EDIT:

Or prettier combination of those two:

<?php
    // Init
    define( "DEBUGGING", true ); // or false in production enviroment
    // Functions
    function get_cache_prevent_string( $always = false ) {
        return (DEBUGGING || $always) ? date('_Y-m-d_H:i:s') : "";
    }
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo get_cache_prevent_string(); ?>">

For div to extend full height

This is an old question. CSS has evolved. There now is the vh (viewport height) unit, also new layout options like flexbox or CSS grid to achieve classical designs in cleaner ways.

How to write a switch statement in Ruby

You can use regular expressions, such as finding a type of string:

case foo
when /^(true|false)$/
   puts "Given string is boolean"
when /^[0-9]+$/ 
   puts "Given string is integer"
when /^[0-9\.]+$/
   puts "Given string is float"
else
   puts "Given string is probably string"
end

Ruby's case will use the equality operand === for this (thanks @JimDeville). Additional information is available at "Ruby Operators". This also can be done using @mmdemirbas example (without parameter), only this approach is cleaner for these types of cases.

VS Code - Search for text in all files in a directory

You can do Edit, Find in Files (or Ctrl+Shift+F - default key binding, Cmd+Shift+F on MacOS) to search the Currently open Folder.

There is an ellipsis on the dialog where you can include/exclude files, and options in the search box for matching case/word and using Regex.

What does ellipsize mean in android?

Note: your text must be larger than the container box for the following to marquee:

 android:ellipsize="marquee"    

Assign an initial value to radio button as checked

The other way to set default checked on radio buttons, especially if you're using angularjs is setting the 'ng-checked' flag to "true" eg: <input id="d_man" value="M" ng-disabled="some Value" type="radio" ng-checked="true">Man

the checked="checked" did not work for me..

HTML/Javascript: how to access JSON data loaded in a script tag with src set

Another alternative to use the exact json within javascript. As it is Javascript Object Notation you can just create your object directly with the json notation. If you store this in a .js file you can use the object in your application. This was a useful option for me when I had some static json data that I wanted to cache in a file separately from the rest of my app.

    //Just hard code json directly within JS
    //here I create an object CLC that represents the json!
    $scope.CLC = {
        "ContentLayouts": [
            {
                "ContentLayoutID": 1,
                "ContentLayoutTitle": "Right",
                "ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/right.png",
                "ContentLayoutIndex": 0,
                "IsDefault": true
            },
            {
                "ContentLayoutID": 2,
                "ContentLayoutTitle": "Bottom",
                "ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/bottom.png",
                "ContentLayoutIndex": 1,
                "IsDefault": false
            },
            {
                "ContentLayoutID": 3,
                "ContentLayoutTitle": "Top",
                "ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/top.png",
                "ContentLayoutIndex": 2,
                "IsDefault": false
            }
        ]
    };

Which Eclipse version should I use for an Android app?

The ADT plug-in is yet not compatible with 3.6

I have been using Eclipse 3.6 with ADT for the past three months for developing applications on Android. I haven't faced any issues so far. It really good and working fine.

How to generate a random string in Ruby

Ruby 1.9+:

ALPHABET = ('a'..'z').to_a
#=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

10.times.map { ALPHABET.sample }.join
#=> "stkbssowre"

# or

10.times.inject('') { |s| s + ALPHABET.sample }
#=> "fdgvacnxhc"

Android runOnUiThread explanation

If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?

You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:

private void populateTable() {
    runOnUiThread(new Runnable(){
        public void run() {
            //If there are stories, add them to the table
            for (Parcelable currentHeadline : allHeadlines) {
                addHeadlineToTable(currentHeadline);
            }
            try {
                dialog.dismiss();
            } catch (final Exception ex) {
                Log.i("---","Exception in thread");
            }
        }
    });
}

How to redirect to action from JavaScript method?

I wish that I could just comment on yojimbo87's answer to post this, but I don't have enough reputation to comment yet. It was pointed out that this relative path only works from the root:

        window.location.href = "/{controller}/{action}/{params}";

Just wanted to confirm that you can use @Url.Content to provide the absolute path:

function DeleteJob() {
    if (confirm("Do you really want to delete selected job/s?"))
        window.location.href = '@Url.Content("~/{controller}/{action}/{params}")';
    else
        return false;
}

Setting environment variables for accessing in PHP when using Apache

If your server is Ubuntu and Apache version is 2.4

Server version: Apache/2.4.29 (Ubuntu)

Then you export variables in "/etc/apache2/envvars" location.

Just like this below line, you need to add an extra line in "/etc/apache2/envvars" export GOROOT=/usr/local/go

Date constructor returns NaN in IE, but works in Firefox and Chrome

The Date constructor accepts any value. If the primitive [[value]] of the argument is number, then the Date that is created has that value. If primitive [[value]] is String, then the specification only guarantees that the Date constructor and the parse method are capable of parsing the result of Date.prototype.toString and Date.prototype.toUTCString()

A reliable way to set a Date is to construct one and use the setFullYear and setTime methods.

An example of that appears here: http://jibbering.com/faq/#parseDate

ECMA-262 r3 does not define any date formats. Passing string values to the Date constructor or Date.parse has implementation-dependent outcome. It is best avoided.


Edit: The entry from comp.lang.javascript FAQ is: An Extended ISO 8601 local date format YYYY-MM-DD can be parsed to a Date with the following:-

/**Parses string formatted as YYYY-MM-DD to a Date object.
 * If the supplied string does not match the format, an 
 * invalid Date (value NaN) is returned.
 * @param {string} dateStringInRange format YYYY-MM-DD, with year in
 * range of 0000-9999, inclusive.
 * @return {Date} Date object representing the string.
 */

  function parseISO8601(dateStringInRange) {
    var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
        date = new Date(NaN), month,
        parts = isoExp.exec(dateStringInRange);

    if(parts) {
      month = +parts[2];
      date.setFullYear(parts[1], month - 1, parts[3]);
      if(month != date.getMonth() + 1) {
        date.setTime(NaN);
      }
    }
    return date;
  }

Can't use Swift classes inside Objective-C

The file is created automatically (talking about Xcode 6.3.2 here). But you won't see it, since it's in your Derived Data folder. After marking your swift class with @objc, compile, then search for Swift.h in your Derived Data folder. You should find the Swift header there.

I had the problem, that Xcode renamed my my-Project-Swift.h to my_Project-Swift.h Xcode doesn't like "." "-" etc. symbols. With the method above you can find the filename and import it to a Objective-C class.

SQL JOIN vs IN performance?

That's rather hard to say - in order to really find out which one works better, you'd need to actually profile the execution times.

As a general rule of thumb, I think if you have indices on your foreign key columns, and if you're using only (or mostly) INNER JOIN conditions, then the JOIN will be slightly faster.

But as soon as you start using OUTER JOIN, or if you're lacking foreign key indexes, the IN might be quicker.

Marc

Merging two images with PHP

You can try my function for merging images horizontally or vertically without changing image ratio. just copy paste will work.

function merge($filename_x, $filename_y, $filename_result, $mergeType = 0) {

    //$mergeType 0 for horizandal merge 1 for vertical merge

 // Get dimensions for specified images
 list($width_x, $height_x) = getimagesize($filename_x);
 list($width_y, $height_y) = getimagesize($filename_y);


$lowerFileName = strtolower($filename_x); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    $image_x = imagecreatefromjpeg($filename_x);    
}else if(substr_count($lowerFileName, '.png')>0){
    $image_x = imagecreatefrompng($filename_x); 
}else if(substr_count($lowerFileName, '.gif')>0){
    $image_x = imagecreatefromgif($filename_x); 
}


$lowerFileName = strtolower($filename_y); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    $image_y = imagecreatefromjpeg($filename_y);    
}else if(substr_count($lowerFileName, '.png')>0){
    $image_y = imagecreatefrompng($filename_y); 
}else if(substr_count($lowerFileName, '.gif')>0){
    $image_y = imagecreatefromgif($filename_y); 
}


if($mergeType==0){
    //for horizandal merge
     if($height_y<$height_x){
        $new_height = $height_y;

        $new_x_height = $new_height;
        $precentageReduced = ($height_x - $new_height)/($height_x/100);
        $new_x_width = ceil($width_x - (($width_x/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_x_width, $new_x_height);
        imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
        $image_x = $tmp;

        $height_x = $new_x_height;
        $width_x = $new_x_width;

     }else{
        $new_height = $height_x;

        $new_y_height = $new_height;
        $precentageReduced = ($height_y - $new_height)/($height_y/100);
        $new_y_width = ceil($width_y - (($width_y/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_y_width, $new_y_height);
        imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
        $image_y = $tmp;

        $height_y = $new_y_height;
        $width_y = $new_y_width;

     }

     $new_width = $width_x + $width_y;

     $image = imagecreatetruecolor($new_width, $new_height);

    imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
    imagecopy($image, $image_y, $width_x, 0, 0, 0, $width_y, $height_y);

}else{


    //for verical merge
    if($width_y<$width_x){
        $new_width = $width_y;

        $new_x_width = $new_width;
        $precentageReduced = ($width_x - $new_width)/($width_x/100);
        $new_x_height = ceil($height_x - (($height_x/100) * $precentageReduced));

        $tmp = imagecreatetruecolor($new_x_width, $new_x_height);
        imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
        $image_x = $tmp;

        $width_x = $new_x_width;
        $height_x = $new_x_height;

     }else{
        $new_width = $width_x;

        $new_y_width = $new_width;
        $precentageReduced = ($width_y - $new_width)/($width_y/100);
        $new_y_height = ceil($height_y - (($height_y/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_y_width, $new_y_height);
        imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
        $image_y = $tmp;

        $width_y = $new_y_width;
        $height_y = $new_y_height;

     }

     $new_height = $height_x + $height_y;

     $image = imagecreatetruecolor($new_width, $new_height);

    imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
    imagecopy($image, $image_y, 0, $height_x, 0, 0, $width_y, $height_y);

}





$lowerFileName = strtolower($filename_result); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    imagejpeg($image, $filename_result);
}else if(substr_count($lowerFileName, '.png')>0){
    imagepng($image, $filename_result);
}else if(substr_count($lowerFileName, '.gif')>0){
    imagegif($image, $filename_result); 
}


 // Clean up
 imagedestroy($image);
 imagedestroy($image_x);
 imagedestroy($image_y);

}


merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged_har.jpg',0); //merge horizontally
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged.jpg',1); //merge vertically

Maven not found in Mac OSX mavericks

I am not allowed to comment to pkyeck's response which did not work for a few people including me, so I am adding a separate comment in continuation to his response:

Basically try to add the variable which he has mentioned in the .profile file if the .bash_profile did not work. It is located in your home directory and then restart the terminal. that got it working for me.

The obvious blocker would be that you do not have an access to edit the .profile file, for which use the "touch" to check the access and the "sudo" command to get the access

  1. touch .profile

  2. vi .profile

Here are the variable pkyeck suggests that we added as a solution which worked with editing .profile for me:

  1. export M2_HOME=/apache-maven-3.3.3

  2. export PATH=$PATH:$M2_HOME/bin

How to delete a stash created with git stash create?

To delete a normal stash created with git stash , you want git stash drop or git stash drop stash@{n}. See below for more details.


You don't need to delete a stash created with git stash create. From the docs:

Create a stash entry (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. This is intended to be useful for scripts. It is probably not the command you want to use; see "save" above.

Since nothing references the stash commit, it will get garbage collected eventually.


A stash created with git stash or git stash save is saved to refs/stash, and can be deleted with git stash drop. As with all Git objects, the actual stash contents aren't deleted from your computer until a gc prunes those objects after they expire (default is 2 weeks later).

Older stashes are saved in the refs/stash reflog (try cat .git/logs/refs/stash), and can be deleted with git stash drop stash@{n}, where n is the number shown by git stash list.

How to get names of enum entries?

Quite a few answers here and considering I looked it up despite this being 7 years old question, I surmise many more will come here. Here's my solution, which is a bit simpler than other ones, it handles numeric-only/text-only/mixed value enums, all the same.

enum funky {
    yum , tum='tum', gum = 'jump', plum = 4
}

const list1 = Object.keys(funky)
  .filter(k => (Number(k).toString() === Number.NaN.toString()));
console.log(JSON.stringify(list1)); // ["yum","tum","gum","plum"]" 

 // for the numeric enum vals (like yum = 0, plum = 4), typescript adds val = key implicitly (0 = yum, 4 = plum)
 // hence we need to filter out such numeric keys (0 or 4)
 

Dynamically adding properties to an ExpandoObject

As explained here by Filip - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/

You can add a method too at runtime.

x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();

How do I get elapsed time in milliseconds in Ruby?

The answer is something like:

t_start = Time.now
# time-consuming operation
t_end = Time.now

milliseconds = (t_start - t_end) * 1000.0

However, the Time.now approach risks to be inaccurate. I found this post by Luca Guidi:

https://blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way/

system clock is constantly floating and it doesn't move only forwards. If your calculation of elapsed time is based on it, you're very likely to run into calculation errors or even outages.

So, it is recommended to use Process.clock_gettime instead. Something like:

def measure_time
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  yield
  end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  elapsed_time = end_time - start_time
  elapsed_time.round(3)
end

Example:

elapsed = measure_time do
    # your time-consuming task here:
    sleep 2.2321
end

=> 2.232

How to Apply Mask to Image in OpenCV?

Here is some code to apply binary mask on a video frame sequence acquired from a webcam. comment and uncomment the "bitwise_not(Mon_mask,Mon_mask);"line and see the effect.

bests, Ahmed.

#include "cv.h"      // include it to used Main OpenCV functions.
#include "highgui.h" //include it to use GUI functions.

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    int c;

int radius=100;
      CvPoint2D32f center;
    //IplImage* color_img;
      Mat image, image0,image1; 
        IplImage *tmp;
    CvCapture* cv_cap = cvCaptureFromCAM(0);

    while(1)  {
        tmp = cvQueryFrame(cv_cap); // get frame
          // IplImage to Mat
            Mat imgMat(tmp);
            image =tmp; 



    center.x = tmp->width/2;
    center.y = tmp->height/2;

         Mat Mon_mask(image.size(), CV_8UC1, Scalar(0,0,0));


        circle(Mon_mask, center, radius, Scalar(255,255,255), -1, 8, 0 ); //-1 means filled

        bitwise_not(Mon_mask,Mon_mask);// commenté ou pas = RP ou DMLA 





        if(tmp != 0)

           imshow("Glaucom", image); // show frame

     c = cvWaitKey(10); // wait 10 ms or for key stroke
    if(c == 27)
        break; // if ESC, break and quit
    }
    /* clean up */
    cvReleaseCapture( &cv_cap );
    cvDestroyWindow("Glaucom");

}

decompiling DEX into Java sourcecode

Recent Debian have Python package androguard:

Description-en: full Python tool to play with Android files
 Androguard is a full Python tool to play with Android files.
  * DEX, ODEX
  * APK
  * Android's binary xml
  * Android resources
  * Disassemble DEX/ODEX bytecodes
  * Decompiler for DEX/ODEX files

Install corresponding packages:

sudo apt-get install androguard python-networkx

Decompile DEX file:

$ androdd -i classes.dex -o ./dir-for-output

Extract classes.dex from Apk + Decompile:

$ androdd -i app.apk -o ./dir-for-output

Apk file is nothing more that Java archive (JAR), you may extract files from archive via:

$ unzip app.apk -d ./dir-for-output

Define preprocessor macro through CMake?

For a long time, CMake had the add_definitions command for this purpose. However, recently the command has been superseded by a more fine grained approach (separate commands for compile definitions, include directories, and compiler options).

An example using the new add_compile_definitions:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION})
add_compile_definitions(WITH_OPENCV2)

Or:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2)

The good part about this is that it circumvents the shabby trickery CMake has in place for add_definitions. CMake is such a shabby system, but they are finally finding some sanity.

Find more explanation on which commands to use for compiler flags here: https://cmake.org/cmake/help/latest/command/add_definitions.html

Likewise, you can do this per-target as explained in Jim Hunziker's answer.

How do you build a Singleton in Dart?

This is also a way to create a Singleton class

class Singleton{
  Singleton._();
  static final Singleton db = Singleton._();
}

Android Text over image

You want to use a FrameLayout or a Merge layout to achieve this. Android dev guide has a great example of this here: Android Layout Tricks #3: Optimize by merging.

When to use Task.Delay, when to use Thread.Sleep?

My opinion,

Task.Delay() is asynchronous. It doesn't block the current thread. You can still do other operations within current thread. It returns a Task return type (Thread.Sleep() doesn't return anything ). You can check if this task is completed(use Task.IsCompleted property) later after another time-consuming process.

Thread.Sleep() doesn't have a return type. It's synchronous. In the thread, you can't really do anything other than waiting for the delay to finish.

As for real-life usage, I have been programming for 15 years. I have never used Thread.Sleep() in production code. I couldn't find any use case for it. Maybe that's because I mostly do web application development.

PowerShell script to return versions of .NET Framework on a machine?

Here's my take on this question following the msft documentation:

$gpParams = @{
    Path        = 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
    ErrorAction = 'SilentlyContinue'
}
$release = Get-ItemProperty @gpParams | Select-Object -ExpandProperty Release

".NET Framework$(
    switch ($release) {
        ({ $_ -ge 528040 }) { ' 4.8'; break }
        ({ $_ -ge 461808 }) { ' 4.7.2'; break }
        ({ $_ -ge 461308 }) { ' 4.7.1'; break }
        ({ $_ -ge 460798 }) { ' 4.7'; break }
        ({ $_ -ge 394802 }) { ' 4.6.2'; break }
        ({ $_ -ge 394254 }) { ' 4.6.1'; break }
        ({ $_ -ge 393295 }) { ' 4.6'; break }
        ({ $_ -ge 379893 }) { ' 4.5.2'; break }
        ({ $_ -ge 378675 }) { ' 4.5.1'; break }
        ({ $_ -ge 378389 }) { ' 4.5'; break }
        default { ': 4.5+ not installed.' }
    }
)"

This example works with all PowerShell versions and will work in perpetuity as 4.8 is the last .NET Framework version.

Add Custom Headers using HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
{
    const string WEBSERVICE_URL = "<<Web Service URL>>";
    try
    {
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "GET";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

How to import a module given its name as string?

If you want it in your locals:

>>> mod = 'sys'
>>> locals()['my_module'] = __import__(mod)
>>> my_module.version
'2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'

same would work with globals()

How to unzip files programmatically in Android?

Based on Vasily Sochinsky's answer a bit tweaked & with a small fix:

public static void unzip(File zipFile, File targetDirectory) throws IOException {
    ZipInputStream zis = new ZipInputStream(
            new BufferedInputStream(new FileInputStream(zipFile)));
    try {
        ZipEntry ze;
        int count;
        byte[] buffer = new byte[8192];
        while ((ze = zis.getNextEntry()) != null) {
            File file = new File(targetDirectory, ze.getName());
            File dir = ze.isDirectory() ? file : file.getParentFile();
            if (!dir.isDirectory() && !dir.mkdirs())
                throw new FileNotFoundException("Failed to ensure directory: " +
                        dir.getAbsolutePath());
            if (ze.isDirectory())
                continue;
            FileOutputStream fout = new FileOutputStream(file);
            try {
                while ((count = zis.read(buffer)) != -1)
                    fout.write(buffer, 0, count);
            } finally {
                fout.close();
            }
            /* if time should be restored as well
            long time = ze.getTime();
            if (time > 0)
                file.setLastModified(time);
            */
        }
    } finally {
        zis.close();
    }
}

Notable differences

  • public static - this is a static utility method that can be anywhere.
  • 2 File parameters because String are :/ for files and one could not specify where the zip file is to be extracted before. Also path + filename concatenation > https://stackoverflow.com/a/412495/995891
  • throws - because catch late - add a try catch if really not interested in them.
  • actually makes sure that the required directories exist in all cases. Not every zip contains all the required directory entries in advance of file entries. This had 2 potential bugs:
    • if the zip contains an empty directory and instead of the resulting directory there is an existing file, this was ignored. The return value of mkdirs() is important.
    • could crash on zip files that don't contain directories.
  • increased write buffer size, this should improve performance a bit. Storage is usually in 4k blocks and writing in smaller chunks is usually slower than necessary.
  • uses the magic of finally to prevent resource leaks.

So

unzip(new File("/sdcard/pictures.zip"), new File("/sdcard"));

should do the equivalent of the original

unpackZip("/sdcard/", "pictures.zip")

How to install npm peer dependencies automatically?

The project npm-install-peers will detect peers and install them.

As of v1.0.1 it doesn't support writing back to the package.json automatically, which would essentially solve our need here.

Please add your support to issue in flight: https://github.com/spatie/npm-install-peers/issues/4

Use a loop to plot n charts Python

We can create a for loop and pass all the numeric columns into it. The loop will plot the graphs one by one in separate pane as we are including plt.figure() into it.

import pandas as pd
import seaborn as sns
import numpy as np

numeric_features=[x for x in data.columns if data[x].dtype!="object"]
#taking only the numeric columns from the dataframe.

for i in data[numeric_features].columns:
    plt.figure(figsize=(12,5))
    plt.title(i)
    sns.boxplot(data=data[i])

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

make sure you're using the newest jquery, and problem solved

I met this problem with this code:

<script src="/scripts/plugins/jquery/jquery-1.6.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>

After change it to this:

<script src="/scripts/plugins/jquery/jquery-1.7.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>

It works fine

How do I concatenate two strings in Java?

import com.google.common.base.Joiner;

String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));

This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.

Best Way to View Generated Source of Webpage?

Justin is dead on. The key point here is that HTML is just a language for describing a document. Once the browser reads it, it's gone. Open tags, close tags, and formatting are all taken care of by the parser and then go away. Any tool that shows you HTML is generating it based on the contents of the document, so it will always be valid.

I had to explain this to another web developer once, and it took a little while for him to accept it.

You can try it for yourself in any JavaScript console:

el = document.createElement('div');
el.innerHTML = "<p>Some text<P>More text";
el.innerHTML; // <p>Some text</p><p>More text</p>

The un-closed tags and uppercase tag names are gone, because that HTML was parsed and discarded after the second line.

The right way to modify the document from JavaScript is with document methods (createElement, appendChild, setAttribute, etc.) and you'll observe that there's no reference to tags or HTML syntax in any of those functions. If you're using document.write, innerHTML, or other HTML-speaking calls to modify your pages, the only way to validate it is to catch what you're putting into them and validate that HTML separately.

That said, the simplest way to get at the HTML representation of the document is this:

document.documentElement.innerHTML

Convert from lowercase to uppercase all values in all character variables in dataframe

It simple with apply function in R

f <- apply(f,2,toupper)

No need to check if the column is character or any other type.

GET and POST methods with the same Action name in the same Controller

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

Also see "How a Method Becomes An Action"

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I know this is not an answer, but I'd like to contribute to this matter for what it's worth. It would be great if they could release justify-self for flexbox to make it truly flexible.

It's my belief that when there are multiple items on the axis, the most logical way for justify-self to behave is to align itself to its nearest neighbours (or edge) as demonstrated below.

I truly hope, W3C takes notice of this and will at least consider it. =)

enter image description here

This way you can have an item that is truly centered regardless of the size of the left and right box. When one of the boxes reaches the point of the center box it will simply push it until there is no more space to distribute.

enter image description here

The ease of making awesome layouts are endless, take a look at this "complex" example.

enter image description here

slashes in url variables

You could easily replace the forward slashes / with something like an underscore _ such as Wikipedia uses for spaces. Replacing special characters with underscores, etc., is common practice.

Reading settings from app.config or web.config in .NET

I was able to get the below approach working for .NET Core projects:

Steps:

  1. Create an appsettings.json (format given below) in your project.
  2. Next create a configuration class. The format is provided below.
  3. I have created a Login() method to show the usage of the Configuration Class.

    Create appsettings.json in your project with content:

    {
      "Environments": {
        "QA": {
          "Url": "somevalue",
     "Username": "someuser",
          "Password": "somepwd"
      },
      "BrowserConfig": {
        "Browser": "Chrome",
        "Headless": "true"
      },
      "EnvironmentSelected": {
        "Environment": "QA"
      }
    }
    
    public static class Configuration
    {
        private static IConfiguration _configuration;
    
        static Configuration()
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile($"appsettings.json");
    
            _configuration = builder.Build();
    
        }
        public static Browser GetBrowser()
        {
    
            if (_configuration.GetSection("BrowserConfig:Browser").Value == "Firefox")
            {
                return Browser.Firefox;
            }
            if (_configuration.GetSection("BrowserConfig:Browser").Value == "Edge")
            {
                return Browser.Edge;
            }
            if (_configuration.GetSection("BrowserConfig:Browser").Value == "IE")
            {
                return Browser.InternetExplorer;
            }
            return Browser.Chrome;
        }
    
        public static bool IsHeadless()
        {
            return _configuration.GetSection("BrowserConfig:Headless").Value == "true";
        }
    
        public static string GetEnvironment()
        {
            return _configuration.GetSection("EnvironmentSelected")["Environment"];
        }
        public static IConfigurationSection EnvironmentInfo()
        {
            var env = GetEnvironment();
            return _configuration.GetSection($@"Environments:{env}");
        }
    
    }
    
    
    public void Login()
    {
        var environment = Configuration.EnvironmentInfo();
        Email.SendKeys(environment["username"]);
        Password.SendKeys(environment["password"]);
        WaitForElementToBeClickableAndClick(_driver, SignIn);
    }
    

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

A trick that works is to position box #2 with position: absolute instead of position: relative. We usually put a position: relative on an outer box (here box #2) when we want an inner box (here box #3) with position: absolute to be positioned relative to the outer box. But remember: for box #3 to be positioned relative to box #2, box #2 just need to be positioned. With this change, we get:

And here is the full code with this change:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <style type="text/css">

            /* Positioning */
            #box1 { overflow: hidden }
            #box2 { position: absolute }
            #box3 { position: absolute; top: 10px }

            /* Styling */
            #box1 { background: #efe; padding: 5px; width: 125px }
            #box2 { background: #fee; padding: 2px; width: 100px; height: 100px }
            #box3 { background: #eef; padding: 2px; width: 75px; height: 150px }

        </style>
    </head>
    <body>
        <br/><br/><br/>
        <div id="box1">
            <div id="box2">
                <div id="box3"/>
            </div>
        </div>
    </body>
</html>

get current page from url

You could try this below.

string url = "http://localhost:1302/TESTERS/Default6.aspx";

string fileName = System.IO.Path.GetFileName(url);

Hope this helps.

Create table with jQuery - append

I wrote rather good function that can generate vertical and horizontal tables:

function generateTable(rowsData, titles, type, _class) {
    var $table = $("<table>").addClass(_class);
    var $tbody = $("<tbody>").appendTo($table);


    if (type == 2) {//vertical table
        if (rowsData.length !== titles.length) {
            console.error('rows and data rows count doesent match');
            return false;
        }
        titles.forEach(function (title, index) {
            var $tr = $("<tr>");
            $("<th>").html(title).appendTo($tr);
            var rows = rowsData[index];
            rows.forEach(function (html) {
                $("<td>").html(html).appendTo($tr);
            });
            $tr.appendTo($tbody);
        });

    } else if (type == 1) {//horsantal table 
        var valid = true;
        rowsData.forEach(function (row) {
            if (!row) {
                valid = false;
                return;
            }

            if (row.length !== titles.length) {
                valid = false;
                return;
            }
        });

        if (!valid) {
            console.error('rows and data rows count doesent match');
            return false;
        }

        var $tr = $("<tr>");
        titles.forEach(function (title, index) {
            $("<th>").html(title).appendTo($tr);
        });
        $tr.appendTo($tbody);

        rowsData.forEach(function (row, index) {
            var $tr = $("<tr>");
            row.forEach(function (html) {
                $("<td>").html(html).appendTo($tr);
            });
            $tr.appendTo($tbody);
        });
    }

    return $table;
}

usage example:

var title = [
    '????? ?????',
    '????? ?????????',
    '????? ?? ???'
];

var rows = [
    [number_format(data.source.area,2)],
    [number_format(data.intersection.area,2)],
    [number_format(data.deference.area,2)]
];

var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");

$ft.appendTo( GroupAnalyse.$results );

var title = [
    '???',
    '?????? ????',
    '?????? ????',
    '?????',
    '????? ??? ?????',
];

var rows = data.edgesData.map(function (r) {
    return [
        r.directionText,
        r.lineLength,
        r.newLineLength,
        r.stateText,
        r.lineLengthDifference
    ];
});


var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");

$et.appendTo( GroupAnalyse.$results );

$('<hr/>').appendTo( GroupAnalyse.$results );

example result:

example result

Should I call Close() or Dispose() for stream objects?

The documentation says that these two methods are equivalent:

StreamReader.Close: This implementation of Close calls the Dispose method passing a true value.

StreamWriter.Close: This implementation of Close calls the Dispose method passing a true value.

Stream.Close: This method calls Dispose, specifying true to release all resources.

So, both of these are equally valid:

/* Option 1, implicitly calling Dispose */
using (StreamWriter writer = new StreamWriter(filename)) { 
   // do something
} 

/* Option 2, explicitly calling Close */
StreamWriter writer = new StreamWriter(filename)
try {
    // do something
}
finally {
    writer.Close();
}

Personally, I would stick with the first option, since it contains less "noise".

Chrome ignores autocomplete="off"

TL;DR: Tell Chrome that this is a new password input and it won't provide old ones as autocomplete suggestions:

<input type="password" name="password" autocomplete="new-password">

autocomplete="off" doesn't work due to a design decision - lots of research shows that users have much longer and harder to hack passwords if they can store them in a browser or password manager.

The specification for autocomplete has changed, and now supports various values to make login forms easy to auto complete:

<!-- Auto fills with the username for the site, even though it's email format -->
<input type="email" name="email" autocomplete="username">

<!-- current-password will populate for the matched username input  -->
<input type="password" autocomplete="current-password" />

If you don't provide these Chrome still tries to guess, and when it does it ignores autocomplete="off".

The solution is that autocomplete values also exist for password reset forms:

<label>Enter your old password:
    <input type="password" autocomplete="current-password" name="pass-old" />
</label>
<label>Enter your new password:
    <input type="password" autocomplete="new-password" name="pass-new" />
</label>
<label>Please repeat it to be sure:
    <input type="password" autocomplete="new-password" name="pass-repeat" />
</label>

You can use this autocomplete="new-password" flag to tell Chrome not to guess the password, even if it has one stored for this site.

Chrome can also manage passwords for sites directly using the credentials API, which is a standard and will probably have universal support eventually.

How do you round a number to two decimal places in C#?

I know its an old question but please note for the following differences between Math round and String format round:

decimal d1 = (decimal)1.125;
Math.Round(d1, 2).Dump();   // returns 1.12
d1.ToString("#.##").Dump(); // returns "1.13"

decimal d2 = (decimal)1.1251;
Math.Round(d2, 2).Dump();   // returns 1.13
d2.ToString("#.##").Dump(); // returns "1.13"

JavaScript to get rows count of a HTML table

This is another option, using jQuery and getting only tbody rows (with the data) and desconsidering thead/tfoot.

$("#tableId > tbody > tr").length

_x000D_
_x000D_
console.log($("#myTableId > tbody > tr").length);
_x000D_
.demo {
   width:100%;
   height:100%;
   border:1px solid #C0C0C0;
   border-collapse:collapse;
   border-spacing:2px;
   padding:5px;
}

.demo caption {
   caption-side:top;
   text-align:center;
}

.demo th {
   border:1px solid #C0C0C0;
   padding:5px;
   background:#F0F0F0;
}

.demo td {
   border:1px solid #C0C0C0;
   text-align:left;
   padding:5px;
   background:#FFFFFF;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId" class="demo">
   <caption>Table 1</caption>
   <thead>
      <tr>
         <th>Header 1</th>
         <th>Header 2</th>
         <th>Header 3</th>
         <th>Header 4</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
   </tbody>
   <tfoot>
      <tr>
         <td colspan=4 style="background:#F0F0F0">&nbsp; </td>
      </tr>
   </tfoot>
</table>
_x000D_
_x000D_
_x000D_

CentOS: Enabling GD Support in PHP Installation

The thing that did the trick for me eventually was:

yum install gd gd-devel php-gd

and then restart apache:

service httpd restart

Can't connect to Postgresql on port 5432

I had this same issue. I originally installed version 10 because that was the default install with Ubuntu 18.04. I later upgraded to 13.2 because I wanted the latest version. I made all the config modifications, but it was still just binging to 1207.0.0.1 and then I thought - maybe it is looking at the config files for version 10. I modified those and restarted the postgres service. Bingo! It was binding to 0.0.0.0

I will need to completely remove 10 and ensure that I am forcing the service to run under version 13.2, so if you upgraded from another version, try updating the other config files in that older directory.

MySQL LEFT JOIN Multiple Conditions

Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result

SELECT a.* FROM a 
    LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']} 
    WHERE a.keyword LIKE '%".$keyword."%' 
    GROUP BY group_id

Automatically resize images with browser size using CSS

The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!

<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />

Change the window width and the image scales obligingly.

Creating and playing a sound in swift

Swift 3 here's how i do it.

{

import UIKit
import AVFoundation

        let url = Bundle.main.url(forResource: "yoursoundname", withExtension: "wav")!
        do {

            player = try AVAudioPlayer(contentsOf: url); guard let player = player else { return }

            player.prepareToPlay()
            player.play()
        } catch let error as Error {
            print(error)

        }
    }

Check if int is between two numbers

One problem is that a ternary relational construct would introduce serious parser problems:

<expr> ::= <expr> <rel-op> <expr> |
           ... |
           <expr> <rel-op> <expr> <rel-op> <expr>

When you try to express a grammar with those productions using a typical PGS, you'll find that there is a shift-reduce conflict at the point of the first <rel-op>. The parse needs to lookahead an arbitrary number of symbols to see if there is a second <rel-op> before it can decide whether the binary or ternary form has been used. In this case, you could not simply ignore the conflict because that would result in incorrect parses.

I'm not saying that this grammar is fatally ambiguous. But I think you'd need a backtracking parser to deal with it correctly. And that is a serious problem for a programming language where fast compilation is a major selling point.

'True' and 'False' in Python

is compares identity. A string will never be identical to a not-string.

== is equality. But a string will never be equal to either True or False.

You want neither.

path = '/bla/bla/bla'

if path:
    print "True"
else:
    print "False"

What does "where T : class, new()" mean?

That means that type T must be a class and have a constructor that does not take any arguments.

For example, you must be able to do this:

T t = new T();

document.getElementById vs jQuery $()

All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it

<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>

Online Demo! - https://codepen.io/frank-dspeed/pen/mdywbre

How to show full column content in a Spark Dataframe?

results.show(20,false) did the trick for me in Scala.

Hexadecimal string to byte array in C

As far as I know, there's no standard function to do so, but it's simple to achieve in the following manner:

#include <stdio.h>

int main(int argc, char **argv) {
    const char hexstring[] = "DEadbeef10203040b00b1e50", *pos = hexstring;
    unsigned char val[12];

     /* WARNING: no sanitization or error-checking whatsoever */
    for (size_t count = 0; count < sizeof val/sizeof *val; count++) {
        sscanf(pos, "%2hhx", &val[count]);
        pos += 2;
    }

    printf("0x");
    for(size_t count = 0; count < sizeof val/sizeof *val; count++)
        printf("%02x", val[count]);
    printf("\n");

    return 0;
}

Edit

As Al pointed out, in case of an odd number of hex digits in the string, you have to make sure you prefix it with a starting 0. For example, the string "f00f5" will be evaluated as {0xf0, 0x0f, 0x05} erroneously by the above example, instead of the proper {0x0f, 0x00, 0xf5}.

Amended the example a little bit to address the comment from @MassimoCallegari

Reverse a string without using reversed() or [::-1]?

This is my solution using the for i in range loop:

def reverse(string):
    tmp = ""
    for i in range(1,len(string)+1):
        tmp += string[len(string)-i]            
    return tmp

It's pretty easy to understand. I start from 1 to avoid index out of bound.

A good Sorted List for Java

To test the efficiancy of earlier awnser by Konrad Holl, I did a quick comparison with what I thought would be the slow way of doing it:

package util.collections;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 *
 * @author Earl Bosch
 * @param <E> Comparable Element
 *
 */
public class SortedList<E extends Comparable> implements List<E> {

    /**
     * The list of elements
     */
    private final List<E> list = new ArrayList();

    public E first() {
        return list.get(0);
    }

    public E last() {
        return list.get(list.size() - 1);
    }

    public E mid() {
        return list.get(list.size() >>> 1);
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public boolean add(E e) {
        list.add(e);
        Collections.sort(list);
        return true;
    }

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public boolean contains(Object obj) {
        return list.contains((E) obj);
    }

    @Override
    public Iterator<E> iterator() {
        return list.iterator();
    }

    @Override
    public Object[] toArray() {
        return list.toArray();
    }

    @Override
    public <T> T[] toArray(T[] arg0) {
        return list.toArray(arg0);
    }

    @Override
    public boolean remove(Object obj) {
        return list.remove((E) obj);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return list.containsAll(c);
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {

        list.addAll(c);
        Collections.sort(list);
        return true;
    }

    @Override
    public boolean addAll(int index, Collection<? extends E> c) {
        throw new UnsupportedOperationException("Not supported.");
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        return list.removeAll(c);
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return list.retainAll(c);
    }

    @Override
    public E get(int index) {
        return list.get(index);
    }

    @Override
    public E set(int index, E element) {
        throw new UnsupportedOperationException("Not supported.");
    }

    @Override
    public void add(int index, E element) {
        throw new UnsupportedOperationException("Not supported.");
    }

    @Override
    public E remove(int index) {
        return list.remove(index);
    }

    @Override
    public int indexOf(Object obj) {
        return list.indexOf((E) obj);
    }

    @Override
    public int lastIndexOf(Object obj) {
        return list.lastIndexOf((E) obj);
    }

    @Override
    public ListIterator<E> listIterator() {
        return list.listIterator();
    }

    @Override
    public ListIterator<E> listIterator(int index) {
        return list.listIterator(index);
    }

    @Override
    public List<E> subList(int fromIndex, int toIndex) {
        throw new UnsupportedOperationException("Not supported.");
    }

}

Turns out its about twice as fast! I think its because of SortedLinkList slow get - which make's it not a good choice for a list.

Compared times for same random list:

  • SortedLinkList : 15731.460
  • SortedList : 6895.494
  • ca.odell.glazedlists.SortedList : 712.460
  • org.apache.commons.collections4.TreeList : 3226.546

Seems glazedlists.SortedList is really fast...

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

I know this is an old thread, but I thought I'd post a vote for xUnit.NET. While most of the other testing frameworks mentioned are all pretty much the same, xUnit.NET has taken a pretty unique, modern, and flexible approach to unit testing. It changes terminology, so you no longer define TestFixtures and Tests...you specify Facts and Theories about your code, which integrates better with the concept of what a test is from a TDD/BDD perspective.

xUnit.NET is also EXTREMELY extensible. Its FactAttribute and TraitAttribute attribute classes are not sealed, and provide overridable base methods that give you a lot of control over how the methods those attributes decorate should be executed. While xUnit.NET in its default form allows you to write test classes that are similar to NUnit test fixtures with their test methods, you are not confined to this form of unit testing at all. You are free to extend the framework to support BDD-style Concern/Context/Observation specifications, as depicted here.

xUnit.NET also supports fit-style testing directly out of the box with its Theory attribute and corresponding data attributes. Fit input data may be loaded from excel, database, or even a custom data source such as a Word document (by extending the base data attribute.) This allows you to capitalize on a single testing platform for both unit tests and integration tests, which can be huge in reducing product dependencies and required training.

Other approaches to testing may also be implemented with xUnit.NET...the possibilities are pretty limitless. Combined with another very forward looking mocking framework, Moq, the two create a very flexible, extensible, and powerful platform for implementing automated testing.