Programs & Examples On #Malware

Malware is any malicious software, script, or code developed or used for the purpose of compromising or harming information assets without the owner’s informed consent. Examples include viruses, worms, spyware, keyloggers, backdoors, etc.

Visual Studio 2015 installer hangs during install?

I temporarily disabled my antivirus (AVG) and restarted the install. That fixed it.

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

How to display the first few characters of a string in Python?

Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'

Alternatively

>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

Do the following.

  1. Close the sdk manager and eclipse.

  2. Go to the folder where you have stored your adt.

  3. In that adt folder you'll find a folder known as tools.

  4. Make a copy of the contents of that folder and paste it in a folder called copytools.

  5. Now go to the command prompt and go to the location of the copytools.

  6. Then execute the command android.bat the sdk manager will start.

  7. Now update all the plugins you want. It'll update your original folder.

  8. After the update delete the copy.

Enjoy. Hope this helps.

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

psoul's excellent post answers to your question so I won't replicate his good work, but I feel it'd help to explain why this is at once a perfectly valid but also terribly silly question. After all, this is a place to learn, right?

Modern computer programs are produced through a series of conversions, starting with the input of a human-readable body of text instructions (called "source code") and ending with a computer-readable body of instructions (called alternatively "binary" or "machine code").

The way that a computer runs a set of machine code instructions is ultimately very simple. Each action a processor can take (e.g., read from memory, add two values) is represented by a numeric code. If I told you that the number 1 meant scream and the number 2 meant giggle, and then held up cards with either 1 or 2 on them expecting you to scream or giggle accordingly, I would be using what is essentially the same system a computer uses to operate.

A binary file is just a set of those codes (usually call "op codes") and the information ("arguments") that the op codes act on.

Now, assembly language is a computer language where each command word in the language represents exactly one op-code on the processor. There is a direct 1:1 translation between an assembly language command and a processor op-code. This is why coding assembly for an x386 processor is different than coding assembly for an ARM processor.

Disassembly is simply this: a program reads through the binary (the machine code), replacing the op-codes with their equivalent assembly language commands, and outputs the result as a text file. It's important to understand this; if your computer can read the binary, then you can read the binary too, either manually with an op-code table in your hand (ick) or through a disassembler.

Disassemblers have some new tricks and all, but it's important to understand that a disassembler is ultimately a search and replace mechanism. Which is why any EULA which forbids it is ultimately blowing hot air. You can't at once permit the computer reading the program data and also forbid the computer reading the program data.

(Don't get me wrong, there have been attempts to do so. They work as well as DRM on song files.)

However, there are caveats to the disassembly approach. Variable names are non-existent; such a thing doesn't exist to your CPU. Library calls are confusing as hell and often require disassembling further binaries. And assembly is hard as hell to read in the best of conditions.

Most professional programmers can't sit and read assembly language without getting a headache. For an amateur it's just not going to happen.

Anyway, this is a somewhat glossed-over explanation, but I hope it helps. Everyone can feel free to correct any misstatements on my part; it's been a while. ;)

How to make Python script run as service?

I offer two recommendations:

supervisord

1) Install the supervisor package (more verbose instructions here):

sudo apt-get install supervisor

2) Create a config file for your daemon at /etc/supervisor/conf.d/flashpolicyd.conf:

[program:flashpolicyd]
directory=/path/to/project/root
environment=ENV_VARIABLE=example,OTHER_ENV_VARIABLE=example2
command=python flashpolicyd.py
autostart=true
autorestart=true

3) Restart supervisor to load your new .conf

supervisorctl update
supervisorctl restart flashpolicyd

systemd (if currently used by your Linux distro)

[Unit]
Description=My Python daemon

[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/project/main.py
WorkingDirectory=/opt/project/
Environment=API_KEY=123456789
Environment=API_PASS=password
Restart=always
RestartSec=2

[Install]
WantedBy=sysinit.target

Place this file into /etc/systemd/system/my_daemon.service and enable it using systemctl daemon-reload && systemctl enable my_daemon && systemctl start my_daemon --no-block.

To view logs:

systemctl status my_daemon

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

Run CSS3 animation only once (at page loading)

So i just found a solution for that: In the hover animation do this:

animation: hover 1s infinite alternate ease-in-out,splash 1;

What does <T> denote in C#

This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx

An example of this is to make a collection of items of a specific type.

class MyArray<T>
{
    T[] array = new T[10];

    public T GetItem(int index)
    {
        return array[index];
    }
}

In your code, you could then do something like this:

MyArray<int> = new MyArray<int>();

In this case, T[] array would work like int[] array, and public T GetItem would work like public int GetItem.

Is there a way to add a gif to a Markdown file?

Showing gifs need two things

1- Use this syntax as in these examples

![Alt Text](https://media.giphy.com/media/vFKqnCdLPNOKc/giphy.gif)

Yields:

Alt Text

2- The image url must end with gif

3- For posterity: if the .gif link above ever goes bad, you will not see the image and instead see the alt-text and URL, like this:

Alt Text

4- for resizing the gif you can use this syntax as in this Github tutorial link

<img src="https://media.giphy.com/media/vFKqnCdLPNOKc/giphy.gif" width="40" height="40" />

Yields:

Difference in months between two dates

Use Noda Time:

LocalDate start = new LocalDate(2013, 1, 5);
LocalDate end = new LocalDate(2014, 6, 1);
Period period = Period.Between(start, end, PeriodUnits.Months);
Console.WriteLine(period.Months); // 16

(example source)

Undoing a git rebase

If you successfully rebased against remote branch and can not git rebase --abort you still can do some tricks to save your work and don't have forced pushes. Suppose your current branch that was rebased by mistake is called your-branch and is tracking origin/your-branch

  • git branch -m your-branch-rebased # rename current branch
  • git checkout origin/your-branch # checkout to latest state that is known to origin
  • git checkout -b your-branch
  • check git log your-branch-rebased, compare to git log your-branch and define commits that are missing from your-branch
  • git cherry-pick COMMIT_HASH for every commit in your-branch-rebased
  • push your changes. Please aware that two local branches are associated with remote/your-branch and you should push only your-branch

Succeeded installing but could not start apache 2.4 on my windows 7 system

I have the same problem too, after upgrading win7 to win10. then I check services.msc and found "World Wide Web Publishing Service" was running automatically by default. So then I disabled it, and running the Apache service again.

how to change a selections options based on another select option selected?

You can use switch case like this:

_x000D_
_x000D_
$(document).ready(function () {_x000D_
  $("#type").change(function () {_x000D_
     switch($(this).val()) {_x000D_
        case 'item1':_x000D_
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");_x000D_
            break;_x000D_
        case 'item2':_x000D_
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");_x000D_
            break;_x000D_
        case 'item3':_x000D_
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");_x000D_
            break;_x000D_
        default:_x000D_
            $("#size").html("<option value=''>--select one--</option>");_x000D_
     }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="type">_x000D_
    <option value="item0">--Select an Item--</option>_x000D_
    <option value="item1">item1</option>_x000D_
    <option value="item2">item2</option>_x000D_
    <option value="item3">item3</option>_x000D_
</select>_x000D_
_x000D_
<select id="size">_x000D_
    <option value="">-- select one -- </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

git status shows fatal: bad object HEAD

I solved this by copying the branch data (with the errors) to my apple laptop local git folder.

Somehow in the terminal and when running: git status, tells me more specific data where the error occurs. If you look under the errors, hopefully you see a list of folders with error. In my case GIT showed the folder which was responsible for the error. Deleting that folder and commiting the branche, I succeeded. git status was working again the other devices updating by git pull; everything working again on every machine.

Hopefully this will work for you also.

Save range to variable

My use case was to save range to variable and then select it later on

Dim targetRange As Range
Set targetRange = Sheets("Sheet").Range("Name")
Application.Goto targetRange
Set targetRangeQ = Nothing ' reset

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Both tmux and GNU Screen work under cygwin. They can be installed from the cygwin installer. Just search for their name there and you probably will get to the latest version (at least for tmux).

Simple WPF RadioButton Binding?

I came up with a simple solution.

I have a model.cs class with:

private int _isSuccess;
public int IsSuccess { get { return _isSuccess; } set { _isSuccess = value; } }

I have Window1.xaml.cs file with DataContext set to model.cs. The xaml contains the radiobuttons:

<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=1}" Content="one" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=2}" Content="two" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=3}" Content="three" />

Here is my converter:

public class RadioBoolToIntConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int integer = (int)value;
        if (integer==int.Parse(parameter.ToString()))
            return true;
        else
            return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return parameter;
    }
}

And of course, in Window1's resources:

<Window.Resources>
    <local:RadioBoolToIntConverter x:Key="radioBoolToIntConverter" />
</Window.Resources>

A Windows equivalent of the Unix tail command

If you use PowerShell then this works:

Get-Content filenamehere -Wait -Tail 30

Posting Stefan's comment from below, so people don't miss it

PowerShell 3 introduces a -Tail parameter to include only the last x lines

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Got this error because I had the Data Source Name in User DSN instead of System DSN enter image description here

CSS opacity only to background color, not the text on it?

The easiest solution is to create 3 divs. One that will contain the other 2, the one with transparent background and the one with content. Make the first div's position relative and set the one with transparent background to negative z-index, then adjust the position of the content to fit over the transparent background. This way you won't have issues with absolute positioning.

How to call an element in a numpy array?

Also, you could try to use ndarray.item(), for example, arr.item((0, 0))(rowid+colid to index) or arr.item(0)(flatten index), its doc https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html

How can I divide two integers to get a double?

I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.

Convert String to Uri

I am just using the java.net package. Here you can do the following:

...
import java.net.URI;
...

String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);

Installing a pip package from within a Jupyter Notebook not working

%pip install fedex    #fedex = package name

in 2019.

In older versions of conda:

import sys
!{sys.executable} -m pip install fedex     #fedex = package name

*note - you do need to import sys

How to get the last value of an ArrayList

If you use a LinkedList instead , you can access the first element and the last one with just getFirst() and getLast() (if you want a cleaner way than size() -1 and get(0))

Implementation

Declare a LinkedList

LinkedList<Object> mLinkedList = new LinkedList<>();

Then this are the methods you can use to get what you want, in this case we are talking about FIRST and LAST element of a list

/**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    /**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }

So , then you can use

mLinkedList.getLast(); 

to get the last element of the list.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

How to get the current time as datetime

Works with Swift 5 (Xcode 10 & Xcode 11) (from France UTC)

func getCurrentDateTime() {
    let now = Date()
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "fr_FR")
    formatter.dateFormat = "EEEE dd MMMM YYYY HH:mm"
    myLabel.text = formatter.string(from: now)
    myLabel.font = UIFont(name: "HelveticaNeue-Light", size: 12)
    myLabel.textColor = UIColor.black
}

If you want to display only the date, set formatter.dateFormat

formatter.dateFormat = "EEEE dd MMMM YYYY"

To display only hours, change formatter.dateFormat to

formatter.dateFormat = "HH:mm"

Don't forget to add getCurrentDateTime() on viewDidLoad.

Callback to a Fragment from a DialogFragment

According to the official documentation:

Fragment#setTargetFragment

Optional target for this fragment. This may be used, for example, if this fragment is being started by another, and when done wants to give a result back to the first. The target set here is retained across instances via FragmentManager#putFragment.

Fragment#getTargetFragment

Return the target fragment set by setTargetFragment(Fragment, int).

So you can do this:

// In your fragment

public class MyFragment extends Fragment implements OnClickListener {
    private void showDialog() {
        DialogFragment dialogFrag = MyDialogFragment.newInstance(this);
        // Add this
        dialogFrag.setTargetFragment(this, 0);
        dialogFrag.show(getFragmentManager, null);
    }
    ...
}

// then

public class MyialogFragment extends DialogFragment {
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // Then get it
        Fragment fragment = getTargetFragment();
        if (fragment instanceof OnClickListener) {
            listener = (OnClickListener) fragment;
        } else {
            throw new RuntimeException("you must implement OnClickListener");
        }
    }
    ...
}

source command not found in sh shell

This may help you, I was getting this error because I was trying to reload my .profile with the command . .profile and it had a syntax error

convert nan value to zero

This should work:

from numpy import *

a = array([[1, 2, 3], [0, 3, NaN]])
where_are_NaNs = isnan(a)
a[where_are_NaNs] = 0

In the above case where_are_NaNs is:

In [12]: where_are_NaNs
Out[12]: 
array([[False, False, False],
       [False, False,  True]], dtype=bool)

Save array in mysql database

Use the PHP function serialize() to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize() they can be converted to arrays again if needed.

What is "Linting"?

Linting is the process of checking the source code for Programmatic as well as Stylistic errors. This is most helpful in identifying some common and uncommon mistakes that are made during coding.

A Lint or a Linter is a program that supports linting (verifying code quality). They are available for most languages like JavaScript, CSS, HTML, Python, etc..

Some of the useful linters are JSLint, CSSLint, JSHint, Pylint

jQuery.ajax handling continue responses: "success:" vs ".done"?

From JQuery Documentation

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); 

(added in jQuery 1.6) An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you follow your link, it tells you that the error results from the $injector not being able to resolve your dependencies. This is a common issue with angular when the javascript gets minified/uglified/whatever you're doing to it for production.

The issue is when you have e.g. a controller;

angular.module("MyApp").controller("MyCtrl", function($scope, $q) {
  // your code
})

The minification changes $scope and $q into random variables that doesn't tell angular what to inject. The solution is to declare your dependencies like this:

angular.module("MyApp")
  .controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
  // your code
}])

That should fix your problem.

Just to re-iterate, everything I've said is at the link the error message provides to you.

Add (insert) a column between two columns in a data.frame

Create an example data.frame and add a column to it.

df = data.frame(a = seq(1, 3), b = seq(4,6), c = seq(7,9))
df['d'] <- seq(10,12)
df

  a b c  d
1 1 4 7 10
2 2 5 8 11
3 3 6 9 12

Rearrange by column index

df[, colnames(df)[c(1:2,4,3)]]

or by column name

df[, c('a', 'b', 'd', 'c')]

The result is

  a b  d c
1 1 4 10 7
2 2 5 11 8
3 3 6 12 9

How to test abstract class in Java with JUnit?

I would create a jUnit inner class that inherits from the abstract class. This can be instantiated and have access to all the methods defined in the abstract class.

public class AbstractClassTest {
   public void testMethod() {
   ...
   }
}


class ConcreteClass extends AbstractClass {

}

remove borders around html input

In my case I am using a CSS framework which adds box-shadow, so I had to also add

box-shadow: none;

So the complete snippet is:

border: none; 
border-width: 0; 
box-shadow: none;

How can I create tests in Android Studio?

Android Studio v.2.3.3

Highlight the code context you want to test, and use the hotkey: CTRL+SHIFT+T

Use the dialog interface to complete your setup.

The testing framework is supposed to mirror your project package layout for best results, but you can manually create custom tests, provided you have the correct directory and build settings.

Nodemailer with Gmail and NodeJS

I had the same problem. Allowing "less secure apps" in my Google security settings made it work!

How to find the installed pandas version

Simplest Solution

Code:

import pandas as pd
pd.__version__

**Its double underscore before and after the word "version".

Output:

'0.14.1'

How to implement a Navbar Dropdown Hover in Bootstrap v4?

Google brought me here but... The examples provided work if the dropdown menu is overlaping (at least by 1px) with its parent when show. If not, it loses focus and nothing works as intended.

Here is a working solution with jQuery and Bootstrap 4.5.2 :

$('li.nav-item').mouseenter(function (e) {

        e.stopImmediatePropagation();

        if ($(this).hasClass('dropdown')) {

            // target element containing dropdowns, show it
            $(this).addClass('show');
            $(this).find('.dropdown-menu').addClass('show');

            // Close dropdown on mouseleave
            $('.dropdown-menu').mouseleave(function (e) {
                e.stopImmediatePropagation();
                $(this).removeClass('show');
            });

            // If you have a prenav above, this clears open dropdowns (since you probably will hover the nav-item going up and it will reopen its dropdown otherwise)
            $('#prenav').off().mouseenter(function (e) {
                e.stopImmediatePropagation();
                $('.dropdown-menu').removeClass('show');
            });

        } else {
            // unset open dropdowns if hover is on simple nav element
            $('.dropdown-menu').removeClass('show');
        }
    });

Validate Dynamically Added Input fields

In regards to @RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.

(function ($) {

    $.fn.initValidation = function () {

        $(this).removeData("validator");
        $(this).removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse(this);

        return this;
    };

}(jQuery));

This can be used like this:

$("#SomeForm").initValidation();

Event listener for when element becomes visible?

If you just want to run some code when an element becomes visible in the viewport:

function onVisible(element, callback) {
  new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if(entry.intersectionRatio > 0) {
        callback(element);
        observer.disconnect();
      }
    });
  }).observe(element);
}

When the element has become visible the intersection observer calls callback and then destroys itself with .disconnect().

Use it like this:

onVisible(document.querySelector("#myElement"), () => console.log("it's visible"));

Eclipse error: R cannot be resolved to a variable

I'm not posting this as an answer but a confirmation to Paresh's accepted answer. I recently updated SDK tools to Revision 22 and I noticed my code changes was not being affective on the device i'm testing at all. Such as the url I was using, I was getting errors for connection time out regarding the url I was "previously" using. Therefore I cleaned the project and built again only to find out that autogenerated R.java file is missing.

After reading Paresh's answer and checking what's going on with my sdk manager this is what I saw: enter image description here

SDK Build-tools 17 was not installed and there was already a new update to SDK tools even though it does not mention any change related to this problem in the changelog, this update brought back my R.java file and the related problems were gone after an eclipse restart and final clean/rebuild on the project.

Resize iframe height according to content height in it

Below is my onload event handler.

I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments. This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5. It might need some extra tweaking, but the general idea should be clear.

    function onLoadDialog(frame) {
    try {
        var body = frame.contentDocument.body;
        var $body = $(body);
        var $frame = $(frame);
        var contentDiv = frame.parentNode;
        var $contentDiv = $(contentDiv);

        var savedShow = $contentDiv.dialog('option', 'show');
        var position = $contentDiv.dialog('option', 'position');
        // disable show effect to enable re-positioning (UI bug?)
        $contentDiv.dialog('option', 'show', null);
        // show dialog, otherwise sizing won't work
        $contentDiv.dialog('open');

        // Maximize frame width in order to determine minimal scrollHeight
        $frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
                contentDiv.offsetWidth + frame.offsetWidth);

        var minScrollHeight = body.scrollHeight;
        var maxWidth = body.offsetWidth;
        var minWidth = 0;
        // decrease frame width until scrollHeight starts to grow (wrapping)
        while (Math.abs(maxWidth - minWidth) > 10) {
            var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
            $body.css('width', width);
            if (body.scrollHeight > minScrollHeight) {
                minWidth = width;
            } else {
                maxWidth = width;
            }
        }
        $frame.css('width', maxWidth);
        // use maximum height to avoid vertical scrollbar (if possible)
        var maxHeight = $contentDiv.dialog('option', 'maxHeight')
        $frame.css('height', maxHeight);
        $body.css('width', '');
        // correct for vertical scrollbar (if necessary)
        while (body.clientWidth < maxWidth) {
            $frame.css('width', maxWidth + (maxWidth - body.clientWidth));
        }

        var minScrollWidth = body.scrollWidth;
        var minHeight = Math.min(minScrollHeight, maxHeight);
        // descrease frame height until scrollWidth decreases (wrapping)
        while (Math.abs(maxHeight - minHeight) > 10) {
            var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
            $body.css('height', height);
            if (body.scrollWidth < minScrollWidth) {
                minHeight = height;
            } else {
                maxHeight = height;
            }
        }
        $frame.css('height', maxHeight);
        $body.css('height', '');

        // reset widths to 'auto' where possible
        $contentDiv.css('width', 'auto');
        $contentDiv.css('height', 'auto');
        $contentDiv.dialog('option', 'width', 'auto');

        // re-position the dialog
        $contentDiv.dialog('option', 'position', position);

        // hide dialog
        $contentDiv.dialog('close');
        // restore show effect
        $contentDiv.dialog('option', 'show', savedShow);
        // open using show effect
        $contentDiv.dialog('open');
        // remove show effect for consecutive requests
        $contentDiv.dialog('option', 'show', null);

        return;
    }

    //An error is raised if the IFrame domain != its container's domain
    catch (e) {
        window.status = 'Error: ' + e.number + '; ' + e.description;
        alert('Error: ' + e.number + '; ' + e.description);
    }
};

Access-Control-Allow-Origin: * in tomcat

I was setting up cors.support.credentials to true along with cors.allowed.origins as *, which won't work.

When cors.allowed.origins is * , then cors.support.credentials should be false (default value or shouldn't be set explicitly).

https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html

Double vs. BigDecimal?

My English is not good so I'll just write a simple example here.

    double a = 0.02;
    double b = 0.03;
    double c = b - a;
    System.out.println(c);

    BigDecimal _a = new BigDecimal("0.02");
    BigDecimal _b = new BigDecimal("0.03");
    BigDecimal _c = _b.subtract(_a);
    System.out.println(_c);

Program output:

0.009999999999999998
0.01

Somebody still want to use double? ;)

How do you append rows to a table using jQuery?

You should append to the table and not the rows.

<script type="text/javascript">
$('a').click(function() {
    $('#myTable').append('<tr class="child"><td>blahblah<\/td></tr>');
});
</script>

List<T> or IList<T>

You can look at this argument from several angles including the one of a purely OO approach which says to program against an Interface not an implementation. With this thought, using IList follows the same principal as passing around and using Interfaces that you define from scratch. I also believe in the scalability and flexibility factors provided by an Interface in general. If a class implmenting IList<T> needs to be extended or changed, the consuming code does not have to change; it knows what the IList Interface contract adheres to. However using a concrete implementation and List<T> on a class that changes, could cause the calling code to need to be changed as well. This is because a class adhering to IList<T> guarantees a certain behavior that is not guaranteed by a concrete type using List<T>.

Also having the power to do something like modify the default implementation of List<T> on a class Implementing IList<T> for say the .Add, .Remove or any other IList method gives the developer a lot of flexibility and power, otherwise predefined by List<T>

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

Make a div fill up the remaining width

Flex-boxes are the solution - and they're fantastic. I've been wanting something like this out of css for a decade. All you need is to add display: flex to your style for "Main" and flex-grow: 100 (where 100 is arbitrary - its not important that it be exactly 100). Try adding this style (colors added to make the effect visible):

<style>
    #Main {
        background-color: lightgray;
        display: flex;
    }

    #div1 {
        border: 1px solid green;   
        height: 50px; 
        display: inline-flex; 
    }
    #div2 {
        border: 1px solid blue;    
        height: 50px;
        display: inline-flex;
        flex-grow: 100;
    }
    #div3 {
        border: 1px solid orange;        
        height: 50px;
        display: inline-flex;
    }
</style>

More info about flex boxes here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

C# Base64 String to JPEG Image

First, convert the base 64 string to an Image, then use the Image.Save method.

To convert from base 64 string to Image:

 public Image Base64ToImage(string base64String)
 {
    // Convert base 64 string to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    // Convert byte[] to Image
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        Image image = Image.FromStream(ms, true);
        return image;
    }
 }

To convert from Image to base 64 string:

public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to base 64 string
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Finally, you can easily to call Image.Save(filePath); to save the image.

How to make graphics with transparent background in R using ggplot2?

Just to improve YCR's answer:

1) I added black lines on x and y axis. Otherwise they are made transparent too.

2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.

Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.

MyTheme_transparent <- theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
    legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
    axis.line = element_line(colour = "black") # adding a black line for x and y axis
)

Installing lxml module in python

For RHEL/CentOS, run "python --version" command to find out Python version. E.g. below:

$ python --version 
  Python 2.7.12

Now run "sudo yum search lxml" to find out python*-lxml package.

$ sudo yum search lxml
Failed to set locale, defaulting to C
Loaded plugins: priorities, update-motd, upgrade-helper
1014 packages excluded due to repository priority protections
============================================================================================================= N/S matched: lxml =============================================================================================================
python26-lxml-docs.noarch : Documentation for python-lxml
python27-lxml-docs.noarch : Documentation for python-lxml
python26-lxml.x86_64 : ElementTree-like Python bindings for libxml2 and libxslt
python27-lxml.x86_64 : ElementTree-like Python bindings for libxml2 and libxslt

Now you can choose package as per your Python version and run command like below:

$ sudo yum install python27-lxml.x86_64

Multiple models in a view

I want to say that my solution was like the answer provided on this stackoverflow page: ASP.NET MVC 4, multiple models in one view?

However, in my case, the linq query they used in their Controller did not work for me.

This is said query:

var viewModels = 
        (from e in db.Engineers
         select new MyViewModel
         {
             Engineer = e,
             Elements = e.Elements,
         })
        .ToList();

Consequently, "in your view just specify that you're using a collection of view models" did not work for me either.

However, a slight variation on that solution did work for me. Here is my solution in case this helps anyone.

Here is my view model in which I know I will have just one team but that team may have multiple boards (and I have a ViewModels folder within my Models folder btw, hence the namespace):

namespace TaskBoard.Models.ViewModels
{
    public class TeamBoards
    {
        public Team Team { get; set; }
        public List<Board> Boards { get; set; }
    }
}

Now this is my controller. This is the most significant difference from the solution in the link referenced above. I build out the ViewModel to send to the view differently.

public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            TeamBoards teamBoards = new TeamBoards();
            teamBoards.Boards = (from b in db.Boards
                                 where b.TeamId == id
                                 select b).ToList();
            teamBoards.Team = (from t in db.Teams
                               where t.TeamId == id
                               select t).FirstOrDefault();

            if (teamBoards == null)
            {
                return HttpNotFound();
            }
            return View(teamBoards);
        }

Then in my view I do not specify it as a list. I just do "@model TaskBoard.Models.ViewModels.TeamBoards" Then I only need a for each when I iterate over the Team's boards. Here is my view:

@model TaskBoard.Models.ViewModels.TeamBoards

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Team</h4>
    <hr />


    @Html.ActionLink("Create New Board", "Create", "Board", new { TeamId = @Model.Team.TeamId}, null)
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => Model.Team.Name)
        </dt>

        <dd>
            @Html.DisplayFor(model => Model.Team.Name)
            <ul>
                @foreach(var board in Model.Boards)
                { 
                    <li>@Html.DisplayFor(model => board.BoardName)</li>
                }
            </ul>
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Team.TeamId }) |
    @Html.ActionLink("Back to List", "Index")
</p>

I am fairly new to ASP.NET MVC so it took me a little while to figure this out. So, I hope this post helps someone figure it out for their project in a shorter timeframe. :-)

How can I get the day of a specific date with PHP

$date = '2014-02-25';
date('D', strtotime($date));

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

You don't need to uninstall WebDAV, just add these lines to the web.config:

<system.webServer>
  <modules>
    <remove name="WebDAVModule" />
  </modules>
  <handlers>
    <remove name="WebDAV" />
  </handlers>
</system.webServer>

What's the best way to determine which version of Oracle client I'm running?

You can get the version of the oracle client by running this command sqlplus /nolog on cmd. Another alternative will be to browse to the path C:\Program Files\Oracle\Inventory and open the "Inventory.xml" file which will give you the version as per below:

<?xml version="1.0" standalone="yes" ?>
<!-- Copyright (c) 1999, 2019, Oracle and/or its affiliates.
All rights reserved. -->
<!-- Do not modify the contents of this file by hand. -->
<INVENTORY>
<VERSION_INFO>
   <SAVED_WITH>12.2.0.1.4</SAVED_WITH>
   <MINIMUM_VER>2.1.0.6.0</MINIMUM_VER>
</VERSION_INFO>

to call onChange event after pressing Enter key

You can use event.key

_x000D_
_x000D_
function Input({onKeyPress}) {_x000D_
  return (_x000D_
    <div>_x000D_
      <h2>Input</h2>_x000D_
      <input type="text" onKeyPress={onKeyPress}/>_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
class Form extends React.Component {_x000D_
  state = {value:""}_x000D_
_x000D_
  handleKeyPress = (e) => {_x000D_
    if (e.key === 'Enter') {_x000D_
      this.setState({value:e.target.value})_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <section>_x000D_
        <Input onKeyPress={this.handleKeyPress}/>_x000D_
        <br/>_x000D_
        <output>{this.state.value}</output>_x000D_
      </section>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Form />,_x000D_
  document.getElementById("react")_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id="react"></div>
_x000D_
_x000D_
_x000D_

JavaScript Promises - reject vs. throw

Another important fact is that reject() DOES NOT terminate control flow like a return statement does. In contrast throw does terminate control flow.

Example:

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  throw "err";_x000D_
  console.log("NEVER REACHED");_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

vs

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  reject(); // resolve() behaves similarly_x000D_
  console.log("ALWAYS REACHED"); // "REJECTED" will print AFTER this_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

Is there a TRY CATCH command in Bash

As everybody says, bash doesn't have a proper language-supported try/catch syntax. You can launch bash with the -e argument or use set -e inside the script to abort the entire bash process if any command has a non-zero exit code. (You can also set +e to temporarily allow failing commands.)

So, one technique to simulate a try/catch block is to launch a sub-process to do the work with -e enabled. Then in the main process, check the return code of the sub-process.

Bash supports heredoc strings, so you don't have to write two separate files to handle this. In the below example, the TRY heredoc will run in a separate bash instance, with -e enabled, so the sub-process will crash if any command returns a non-zero exit code. Then, back in the main process, we can check the return code to handle a catch block.

#!/bin/bash

set +e
bash -e <<TRY
  echo hello
  cd /does/not/exist
  echo world
TRY
if [ $? -ne 0 ]; then
  echo caught exception
fi

It's not a proper language-supported try/catch block, but it may scratch a similar itch for you.

Getting the textarea value of a ckeditor textarea with javascript

At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:

CKEDITOR.on("instanceCreated", function(event) {
    event.editor.on("change", function () {
        $("#trackingDiv").html(event.editor.getData());
    });
});

I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.

Modify tick label text

If you do not work with fig and ax and you want to modify all labels (e.g. for normalization) you can do this:

labels, locations = plt.yticks()
plt.yticks(labels, labels/max(labels))

Permission denied (publickey,keyboard-interactive)

You may want to double check the authorized_keys file permissions:

$ chmod 600 ~/.ssh/authorized_keys

Newer SSH server versions are very picky on this respect.

filedialog, tkinter and opening files

I had to specify individual commands first and then use the * to bring all in command.

from tkinter import filedialog
from tkinter import *

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

Flatten list of lists

>>> lis=[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> [x[0] for x in lis]
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]

When is a CDATA section necessary within a script tag?

Basically it is to allow to write a document that is both XHTML and HTML. The problem is that within XHTML, the XML parser will interpret the &,<,> characters in the script tag and cause XML parsing error. So, you can write your JavaScript with entities, e.g.:

if (a &gt; b) alert('hello world');

But this is impractical. The bigger problem is that if you read the page in HTML, the tag script is considered CDATA 'by default', and such JavaScript will not run. Therefore, if you want the same page to be OK both using XHTML and HTML parsers, you need to enclose the script tag in CDATA element in XHTML, but NOT to enclose it in HTML.

This trick marks the start of a CDATA element as a JavaScript comment; in HTML the JavaScript parser ignores the CDATA tag (it's a comment). In XHTML, the XML parser (which is run before the JavaScript) detects it and treats the rest until end of CDATA as CDATA.

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

For Jar

Add pom.xml

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

How to get phpmyadmin username and password

If you don't remember your password, then run this command in the Shell:

mysqladmin.exe -u root password NewPassword

where 'NewPassword' is your new password.

Accessing members of items in a JSONArray with Java

HashMap regs = (HashMap) parser.parse(stringjson);

(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");

Convert string to Color in C#

I've used something like this before:

        public static T CreateFromString<T>(string stringToCreateFrom) {

        T output = Activator.CreateInstance<T>();

        if (!output.GetType().IsEnum)
            throw new IllegalTypeException();

        try {
            output = (T) Enum.Parse(typeof (T), stringToCreateFrom, true);
        }
        catch (Exception ex) {
            string error = "Cannot parse '" + stringToCreateFrom + "' to enum '" + typeof (T).FullName + "'";
            _logger.Error(error, ex);
            throw new IllegalArgumentException(error, ex);
        }

        return output;
    }

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

Write in body request with HttpClient

Extending your code (assuming that the XML you want to send is in xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);

Print a variable in hexadecimal in Python

Another answer with later print/format style is:

res[0]=12
res[1]=23
print("my num is 0x{0:02x}{1:02x}".format(res[0],res[1]))

How do I specify the exit code of a console application in .NET?

The enumeration option is excellent however can be improved upon by multiplying the numbers as in:

enum ExitCodes : int
{
  Success = 0,
  SignToolNotInPath = 1,
  AssemblyDirectoryBad = 2,
  PFXFilePathBad = 4,
  PasswordMissing = 8,
  SignFailed = 16,
  UnknownError = 32
}

In the case of multiple errors, adding the specific error numbers together will give you a unique number that will represent the combination of detected errors.

For example, an errorlevel of 6 can only consist of errors 4 and 2, 12 can only consist of errors 4 and 8, 14 can only consist of 2, 4 and 8 etc.

How to display a json array in table format?

using jquery $.each you can access all data and also set in table like this

<table style="width: 100%">
     <thead>
          <tr>
               <th>Id</th>
               <th>Name</th>
               <th>Category</th>
               <th>Color</th>
           </tr>
     </thead>
     <tbody id="tbody">
     </tbody>
</table>

$.each(data, function (index, item) {
     var eachrow = "<tr>"
                 + "<td>" + item[1] + "</td>"
                 + "<td>" + item[2] + "</td>"
                 + "<td>" + item[3] + "</td>"
                 + "<td>" + item[4] + "</td>"
                 + "</tr>";
     $('#tbody').append(eachrow);
});

Git: Remove committed file after push

You can revert only one file to a specified revision.

First you can check on which commits the file was changed.

git log path/to/file.txt

Then you can checkout the file with the revision number.

git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt

After that you can commit and push it again.

Remove unwanted parts from strings in a column

I often use list comprehensions for these types of tasks because they're often faster.

There can be big differences in performance between the various methods for doing things like this (i.e. modifying every element of a series within a DataFrame). Often a list comprehension can be fastest - see code race below for this task:

import pandas as pd
#Map
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))
10000 loops, best of 3: 187 µs per loop
#List comprehension
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = [x.lstrip('+-').rstrip('aAbBcC') for x in data['result']]
10000 loops, best of 3: 117 µs per loop
#.str
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = data['result'].str.lstrip('+-').str.rstrip('aAbBcC')
1000 loops, best of 3: 336 µs per loop

How to use awk sort by column 3

How about just sort.

sort -t, -nk3 user.csv

where

  • -t, - defines your delimiter as ,.

  • -n - gives you numerical sort. Added since you added it in your attempt. If your user field is text only then you dont need it.

  • -k3 - defines the field (key). user is the third field.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

Possible solution that worked for me with jest

import React from "react";
import { shallow } from "enzyme";
import { Provider } from "react-redux";
import configureMockStore from "redux-mock-store";
import TestPage from "../TestPage";

const mockStore = configureMockStore();
const store = mockStore({});

describe("Testpage Component", () => {
    it("should render without throwing an error", () => {
        expect(
            shallow(
                <Provider store={store}>
                    <TestPage />
                </Provider>
            ).exists(<h1>Test page</h1>)
        ).toBe(true);
    });
});

How to use LogonUser properly to impersonate domain user from workgroup client

I was having the same problem. Don't know if you've solved this or not, but what I was really trying to do was access a network share with AD credentials. WNetAddConnection2() is what you need to use in that case.

Eclipse error: "Editor does not contain a main type"

private int user_movie_matrix[][];Th. should be `private int user_movie_matrix[][];.

private int user_movie_matrix[][]; should be private static int user_movie_matrix[][];

cfiltering(numberOfUsers, numberOfMovies); should be new cfiltering(numberOfUsers, numberOfMovies);

Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.

Getting text from td cells with jQuery

First of all, your selector is overkill. I suggest using a class or ID selector like my example below. Once you've corrected your selector, simply use jQuery's .each() to iterate through the collection:

ID Selector:

$('#mytable td').each(function() {
    var cellText = $(this).html();    
});

Class Selector:

$('.myTableClass td').each(function() {
    var cellText = $(this).html();    
});

Additional Information:

Take a look at jQuery's selector docs.

How to create an Array with AngularJS's ng-model

You can do a variety of things. What I would do is this.

Create an array on scope that will be your data structure for the phone numbers.

$scope.telephone = '';
$scope.numbers = [];

Then in your html I would have this

<input type="text" ng-model="telephone">
<button ng-click="submitNumber()">Submit</button>

Then when your user clicks submit, run submitNumber(), which pushes the new telephone number into the numbers array.

$scope.submitNumber = function(){
  $scope.numbers.push($scope.telephone);
}

milliseconds to time in javascript

try this function :-

_x000D_
_x000D_
function msToTime(ms) {_x000D_
  var d = new Date(null)_x000D_
  d.setMilliseconds(ms)_x000D_
  return d.toLocaleTimeString("en-US")_x000D_
}_x000D_
_x000D_
var ms = 4000000_x000D_
alert(msToTime(ms))
_x000D_
_x000D_
_x000D_

How to add new line into txt file

Why not do it with one method call:

File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });

which will do the newline for you, and allow you to insert multiple lines at once if you want.

Get Android Device Name

Simply use

BluetoothAdapter.getDefaultAdapter().getName()

How to duplicate sys.stdout to a log file?

None of the answers above really seems to answer the problem posed. I know this is an old thread, but I think this problem is a lot simpler than everyone is making it:

class tee_err(object):

 def __init__(self):
    self.errout = sys.stderr

    sys.stderr = self

    self.log = 'logfile.log'
    log = open(self.log,'w')
    log.close()

 def write(self, line):

    log = open(self.log,'a')
    log.write(line)
    log.close()   

    self.errout.write(line)

Now this will repeat everything to the normal sys.stderr handler and your file. Create another class tee_out for sys.stdout.

Process.start: how to get the output?

When you create your Process object set StartInfo appropriately:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

You can use int.Parse() or int.TryParse() to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.

python list by value not by reference

As mentioned by phihag in his answer,

b = a[:]

will work for your case since slicing a list creates a new memory id of the list (meaning you are no longer referencing the same object in your memory and the changes you make to one will not be reflected in the other.)

However, there is a slight problem. If your list is multidimensional, as in lists within lists, simply slicing will not solve this problem. Changes made in the higher dimensions, i.e. the lists within the original list, will be shared between the two.

Do not fret, there is a solution. The module copy has a nifty copying technique that takes care of this issue.

from copy import deepcopy

b = deepcopy(a)

will copy a list with a new memory id no matter how many levels of lists it contains!

Convert binary to ASCII and vice versa

I'm not sure how you think you can do it other than character-by-character -- it's inherently a character-by-character operation. There is certainly code out there to do this for you, but there is no "simpler" way than doing it character-by-character.

First, you need to strip the 0b prefix, and left-zero-pad the string so it's length is divisible by 8, to make dividing the bitstring up into characters easy:

bitstring = bitstring[2:]
bitstring = -len(bitstring) % 8 * '0' + bitstring

Then you divide the string up into blocks of eight binary digits, convert them to ASCII characters, and join them back into a string:

string_blocks = (bitstring[i:i+8] for i in range(0, len(bitstring), 8))
string = ''.join(chr(int(char, 2)) for char in string_blocks)

If you actually want to treat it as a number, you still have to account for the fact that the leftmost character will be at most seven digits long if you want to go left-to-right instead of right-to-left.

$(window).scrollTop() vs. $(document).scrollTop()

First, you need to understand the difference between window and document. The window object is a top level client side object. There is nothing above the window object. JavaScript is an object orientated language. You start with an object and apply methods to its properties or the properties of its object groups. For example, the document object is an object of the window object. To change the document's background color, you'd set the document's bgcolor property.

window.document.bgcolor = "red" 

To answer your question, There is no difference in the end result between window and document scrollTop. Both will give the same output.

Check working example at http://jsfiddle.net/7VRvj/6/

In general use document mainly to register events and use window to do things like scroll, scrollTop, and resize.

How to percent-encode URL parameters in Python?

In Python 3, urllib.quote has been moved to urllib.parse.quote and it does handle unicode by default.

>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'

Custom Drawable for ProgressBar/ProgressDialog

I was having some trouble using an Indeterminate Progress Dialog with the solution here, after some work and trial and error I got it to work.

First, create the animation you want to use for the Progress Dialog. In my case I used 5 images.

../res/anim/progress_dialog_icon_drawable_animation.xml:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_progress_dialog_drawable_1" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_2" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_3" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_4" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_5" android:duration="150" />
</animation-list>

Where you want to show a ProgressDialog:

dialog = new ProgressDialog(Context.this);
dialog.setIndeterminate(true);
dialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.progress_dialog_icon_drawable_animation));
dialog.setMessage("Some Text");
dialog.show();

This solution is really simple and worked for me, you could extend ProgressDialog and make it override the drawable internally, however, this was really too complicated for what I needed so I did not do it.

Error while trying to run project: Unable to start program. Cannot find the file specified

I had this issue on VS2008: I removed the .suo; .ncb; and user project file, then restarted the solution and it fixed the problem for me.

Jackson with JSON: Unrecognized field, not marked as ignorable

You can use Jackson's class-level annotation:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties

@JsonIgnoreProperties
class { ... }

It will ignore every property you haven't defined in your POJO. Very useful when you are just looking for a couple of properties in the JSON and don't want to write the whole mapping. More info at Jackson's website. If you want to ignore any non declared property, you should write:

@JsonIgnoreProperties(ignoreUnknown = true)

Folder structure for a Node.js project

More example from my project architecture you can see here:

+-- Dockerfile
+-- README.md
+-- config
¦   +-- production.json
+-- package.json
+-- schema
¦   +-- create-db.sh
¦   +-- db.sql
+-- scripts
¦   +-- deploy-production.sh 
+-- src
¦   +-- app -> Containes API routes
¦   +-- db -> DB Models (ORM)
¦   +-- server.js -> the Server initlializer.
+-- test

Basically, the logical app separated to DB and APP folders inside the SRC dir.

How to get the string size in bytes?

If you use sizeof()then a char *str and char str[] will return different answers. char str[] will return the length of the string(including the string terminator) while char *str will return the size of the pointer(differs as per compiler).

How do I obtain a Query Execution Plan in SQL Server?

Beside the methods described in previous answers, you can also use a free execution plan viewer and query optimization tool ApexSQL Plan (which I’ve recently bumped into).

You can install and integrate ApexSQL Plan into SQL Server Management Studio, so execution plans can be viewed from SSMS directly.

Viewing Estimated execution plans in ApexSQL Plan

  1. Click the New Query button in SSMS and paste the query text in the query text window. Right click and select the “Display Estimated Execution Plan” option from the context menu.

New Query button in SSMS

  1. The execution plan diagrams will be shown the Execution Plan tab in the results section. Next right-click the execution plan and in the context menu select the “Open in ApexSQL Plan” option.

Execution Plan

  1. The Estimated execution plan will be opened in ApexSQL Plan and it can be analyzed for query optimization.

Estimated execution plan

Viewing Actual execution plans in ApexSQL Plan

To view the Actual execution plan of a query, continue from the 2nd step mentioned previously, but now, once the Estimated plan is shown, click the “Actual” button from the main ribbon bar in ApexSQL Plan.

click the “Actual” button from the main ribbon bar

Once the “Actual” button is clicked, the Actual execution plan will be shown with detailed preview of the cost parameters along with other execution plan data.

Actual execution plan

More information about viewing execution plans can be found by following this link.

Difference between pre-increment and post-increment in a loop?

There is more to ++i and i++ than loops and performance differences. ++i returns a l-value and i++ returns an r-value. Based on this, there are many things you can do to ( ++i ) but not to ( i++ ).

1- It is illegal to take the address of post increment result. Compiler won't even allow you.
2- Only constant references to post increment can exist, i.e., of the form const T&.
3- You cannot apply another post increment or decrement to the result of i++, i.e., there is no such thing as I++++. This would be parsed as ( i ++ ) ++ which is illegal.
4- When overloading pre-/post-increment and decrement operators, programmers are encouraged to define post- increment/decrement operators like:

T& operator ++ ( )
{
   // logical increment
   return *this;
}

const T operator ++ ( int )
{
    T temp( *this );
    ++*this;
    return temp;
}

UICollectionView Self Sizing Cells with Auto Layout

I did a dynamic cell height of collection view. Here is git hub repo.

And, dig out why preferredLayoutAttributesFittingAttributes is called more than once. Actually, it will be called at least 3 times.

The console log picture : enter image description here

1st preferredLayoutAttributesFittingAttributes:

(lldb) po layoutAttributes
<UICollectionViewLayoutAttributes: 0x7fa405c290e0> index path: (<NSIndexPath:    0xc000000000000016> 
{length = 2, path = 0 - 0}); frame = (15 12; 384 57.5); 

(lldb) po self.collectionView
<UICollectionView: 0x7fa40606c800; frame = (0 57.6667; 384 0);

The layoutAttributes.frame.size.height is current status 57.5.

2nd preferredLayoutAttributesFittingAttributes:

(lldb) po layoutAttributes
<UICollectionViewLayoutAttributes: 0x7fa405c16370> index path: (<NSIndexPath: 0xc000000000000016> 
{length = 2, path = 0 - 0}); frame = (15 12; 384 534.5); 

(lldb) po self.collectionView
<UICollectionView: 0x7fa40606c800; frame = (0 57.6667; 384 0);

The cell frame height changed to 534.5 as our expected. But, the collection view still zero height.

3rd preferredLayoutAttributesFittingAttributes:

(lldb) po layoutAttributes
<UICollectionViewLayoutAttributes: 0x7fa403d516a0> index path: (<NSIndexPath: 0xc000000000000016> 
{length = 2, path = 0 - 0}); frame = (15 12; 384 534.5); 

(lldb) po self.collectionView
<UICollectionView: 0x7fa40606c800; frame = (0 57.6667; 384 477);

You can see the collection view height was changed from 0 to 477.

The behavior is similar to handle scroll:

1. Before self-sizing cell

2. Validated self-sizing cell again after other cells recalculated.

3. Did changed self-sizing cell

At beginning, I thought this method only call once. So I coded as the following:

CGRect frame = layoutAttributes.frame;
frame.size.height = frame.size.height + self.collectionView.contentSize.height;
UICollectionViewLayoutAttributes* newAttributes = [layoutAttributes copy];
newAttributes.frame = frame;
return newAttributes;

This line:

frame.size.height = frame.size.height + self.collectionView.contentSize.height;

will cause system call infinite loop and App crash.

Any size changed, it will validate all cells' preferredLayoutAttributesFittingAttributes again and again until every cells' positions (i.e frames) are no more change.

Replace Line Breaks in a String C#

If your code is supposed to run in different environments, I would consider using the Environment.NewLine constant, since it is specifically the newline used in the specific environment.

line = line.Replace(Environment.NewLine, "newLineReplacement");

However, if you get the text from a file originating on another system, this might not be the correct answer, and you should replace with whatever newline constant is used on the other system. It will typically be \n or \r\n.

How to add/update child entities when updating a parent entity in EF

Because I hate repeating complex logic, here's a generic version of Slauma's solution.

Here's my update method. Note that in a detached scenario, sometimes your code will read data and then update it, so it's not always detached.

public async Task UpdateAsync(TempOrder order)
{
    order.CheckNotNull(nameof(order));
    order.OrderId.CheckNotNull(nameof(order.OrderId));

    order.DateModified = _dateService.UtcNow;

    if (_context.Entry(order).State == EntityState.Modified)
    {
        await _context.SaveChangesAsync().ConfigureAwait(false);
    }
    else // Detached.
    {
        var existing = await SelectAsync(order.OrderId!.Value).ConfigureAwait(false);
        if (existing != null)
        {
            order.DateModified = _dateService.UtcNow;
            _context.TrackChildChanges(order.Products, existing.Products, (a, b) => a.OrderProductId == b.OrderProductId);
            await _context.SaveChangesAsync(order, existing).ConfigureAwait(false);
        }
    }
}

CheckNotNull is defined here.

Create these extension methods.

/// <summary>
/// Tracks changes on childs models by comparing with latest database state.
/// </summary>
/// <typeparam name="T">The type of model to track.</typeparam>
/// <param name="context">The database context tracking changes.</param>
/// <param name="childs">The childs to update, detached from the context.</param>
/// <param name="existingChilds">The latest existing data, attached to the context.</param>
/// <param name="match">A function to match models by their primary key(s).</param>
public static void TrackChildChanges<T>(this DbContext context, IList<T> childs, IList<T> existingChilds, Func<T, T, bool> match)
    where T : class
{
    context.CheckNotNull(nameof(context));
    childs.CheckNotNull(nameof(childs));
    existingChilds.CheckNotNull(nameof(existingChilds));

    // Delete childs.
    foreach (var existing in existingChilds.ToList())
    {
        if (!childs.Any(c => match(c, existing)))
        {
            existingChilds.Remove(existing);
        }
    }

    // Update and Insert childs.
    var existingChildsCopy = existingChilds.ToList();
    foreach (var item in childs.ToList())
    {
        var existing = existingChildsCopy
            .Where(c => match(c, item))
            .SingleOrDefault();

        if (existing != null)
        {
            // Update child.
            context.Entry(existing).CurrentValues.SetValues(item);
        }
        else
        {
            // Insert child.
            existingChilds.Add(item);
            // context.Entry(item).State = EntityState.Added;
        }
    }
}

/// <summary>
/// Saves changes to a detached model by comparing it with the latest data.
/// </summary>
/// <typeparam name="T">The type of model to save.</typeparam>
/// <param name="context">The database context tracking changes.</param>
/// <param name="model">The model object to save.</param>
/// <param name="existing">The latest model data.</param>
public static void SaveChanges<T>(this DbContext context, T model, T existing)
    where T : class
{
    context.CheckNotNull(nameof(context));
    model.CheckNotNull(nameof(context));

    context.Entry(existing).CurrentValues.SetValues(model);
    context.SaveChanges();
}

/// <summary>
/// Saves changes to a detached model by comparing it with the latest data.
/// </summary>
/// <typeparam name="T">The type of model to save.</typeparam>
/// <param name="context">The database context tracking changes.</param>
/// <param name="model">The model object to save.</param>
/// <param name="existing">The latest model data.</param>
/// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
/// <returns></returns>
public static async Task SaveChangesAsync<T>(this DbContext context, T model, T existing, CancellationToken cancellationToken = default)
    where T : class
{
    context.CheckNotNull(nameof(context));
    model.CheckNotNull(nameof(context));

    context.Entry(existing).CurrentValues.SetValues(model);
    await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

How to use java.String.format in Scala?

Also note that Scala extends String with a number of methods (via implicit conversion to a WrappedString brought in by Predef) so you could also do the following:

val formattedString = "Hello %s, isn't %s cool?".format("Ivan", "Scala")

How to execute a Python script from the Django shell?

came here with the same question as the OP, and I found my favourite answer precisely in the mistake within the question, which works also in Python 3:

./manage.py shell <<EOF
import my_script
my_script.main()
EOF

MySQL: Can't create table (errno: 150)

I had same issue. It was related to table's column Collation and Character Set. Make sure Character Set and Collation must be same for both columns on two tables. If you want to set a foreign key on that. Example- If you put foreign key on userID column of userImage table referencing userID column of users table.Then Collation must be same that is utf8_general_ci and Character set utf8 for both columns of tables. Generally when you create a table mysql takes these two configuration from server settings.

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

How do I get video durations with YouTube API version 3?

I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):

class Youtube
{
    static $api_key = '<API_KEY>';
    static $api_base = 'https://www.googleapis.com/youtube/v3/videos';
    static $thumbnail_base = 'https://i.ytimg.com/vi/';

    // $vid - video id in youtube
    // returns - video info
    public static function getVideoInfo($vid)
    {
        $params = array(
            'part' => 'contentDetails',
            'id' => $vid,
            'key' => self::$api_key,
        );

        $api_url = Youtube::$api_base . '?' . http_build_query($params);
        $result = json_decode(@file_get_contents($api_url), true);

        if(empty($result['items'][0]['contentDetails']))
            return null;
        $vinfo = $result['items'][0]['contentDetails'];

        $interval = new DateInterval($vinfo['duration']);
        $vinfo['duration_sec'] = $interval->h * 3600 + $interval->i * 60 + $interval->s;

        $vinfo['thumbnail']['default']       = self::$thumbnail_base . $vid . '/default.jpg';
        $vinfo['thumbnail']['mqDefault']     = self::$thumbnail_base . $vid . '/mqdefault.jpg';
        $vinfo['thumbnail']['hqDefault']     = self::$thumbnail_base . $vid . '/hqdefault.jpg';
        $vinfo['thumbnail']['sdDefault']     = self::$thumbnail_base . $vid . '/sddefault.jpg';
        $vinfo['thumbnail']['maxresDefault'] = self::$thumbnail_base . $vid . '/maxresdefault.jpg';

        return $vinfo;
    }
}

Please note that you'll need API_KEY to use the YouTube API:

  1. Create a new project here: https://console.developers.google.com/project
  2. Enable "YouTube Data API" under "APIs & auth" -> APIs
  3. Create a new server key under "APIs & auth" -> Credentials

Determining the current foreground application from a background task or service

With regards to "2. How my background application can know what the application currently running in the foreground is."

Do NOT use the getRunningAppProcesses() method as this returns all sorts of system rubbish from my experience and you'll get multiple results which have RunningAppProcessInfo.IMPORTANCE_FOREGROUND. Use getRunningTasks() instead

This is the code I use in my service to identify the current foreground application, its really easy:

ActivityManager am = (ActivityManager) AppService.this.getSystemService(ACTIVITY_SERVICE);
// The first in the list of RunningTasks is always the foreground task.
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

Thats it, then you can easily access details of the foreground app/activity:

String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();
PackageManager pm = AppService.this.getPackageManager();
PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

This requires an additional permission in activity menifest and works perfectly.

<uses-permission android:name="android.permission.GET_TASKS" />

How to generate keyboard events?

macOS

Here is the more complete version of @Phylliida answer in form of class with code example:

#!/usr/bin/python
# Script simulating keyboard events in macOS.
# See: https://stackoverflow.com/q/13564851/55075

import sys
import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGHIDEventTap
#from Quartz.CoreGraphics import CFRelease # Python releases things automatically.

class Keyboard():
    shiftChars = {
        '~': '`',
        '!': '1',
        '@': '2',
        '#': '3',
        '$': '4',
        '%': '5',
        '^': '6',
        '&': '7',
        '*': '8',
        '(': '9',
        ')': '0',
        '_': '-',
        '+': '=',
        '{': '[',
        '}': ']',
        '|': '\\',
        ':': ';',
        '"': '\'',
        '<': ',',
        '>': '.',
        '?': '/'
    }


    keyCodeMap = {
        'a'              : 0x00,
        's'              : 0x01,
        'd'              : 0x02,
        'f'              : 0x03,
        'h'              : 0x04,
        'g'              : 0x05,
        'z'              : 0x06,
        'x'              : 0x07,
        'c'              : 0x08,
        'v'              : 0x09,
        'b'              : 0x0B,
        'q'              : 0x0C,
        'w'              : 0x0D,
        'e'              : 0x0E,
        'r'              : 0x0F,
        'y'              : 0x10,
        't'              : 0x11,
        '1'              : 0x12,
        '2'              : 0x13,
        '3'              : 0x14,
        '4'              : 0x15,
        '6'              : 0x16,
        '5'              : 0x17,
        '='              : 0x18,
        '9'              : 0x19,
        '7'              : 0x1A,
        '-'              : 0x1B,
        '8'              : 0x1C,
        '0'              : 0x1D,
        ']'              : 0x1E,
        'o'              : 0x1F,
        'u'              : 0x20,
        '['              : 0x21,
        'i'              : 0x22,
        'p'              : 0x23,
        'l'              : 0x25,
        'j'              : 0x26,
        '\''             : 0x27,
        'k'              : 0x28,
        ';'              : 0x29,
        '\\'             : 0x2A,
        ','              : 0x2B,
        '/'              : 0x2C,
        'n'              : 0x2D,
        'm'              : 0x2E,
        '.'              : 0x2F,
        '`'              : 0x32,
        'k.'             : 0x41,
        'k*'             : 0x43,
        'k+'             : 0x45,
        'kclear'         : 0x47,
        'k/'             : 0x4B,
        'k\n'            : 0x4C,
        'k-'             : 0x4E,
        'k='             : 0x51,
        'k0'             : 0x52,
        'k1'             : 0x53,
        'k2'             : 0x54,
        'k3'             : 0x55,
        'k4'             : 0x56,
        'k5'             : 0x57,
        'k6'             : 0x58,
        'k7'             : 0x59,
        'k8'             : 0x5B,
        'k9'             : 0x5C,

        # keycodes for keys that are independent of keyboard layout
        '\n'             : 0x24,
        '\t'             : 0x30,
        ' '              : 0x31,
        'del'            : 0x33,
        'delete'         : 0x33,
        'esc'            : 0x35,
        'escape'         : 0x35,
        'cmd'            : 0x37,
        'command'        : 0x37,
        'shift'          : 0x38,
        'caps lock'      : 0x39,
        'option'         : 0x3A,
        'ctrl'           : 0x3B,
        'control'        : 0x3B,
        'right shift'    : 0x3C,
        'rshift'         : 0x3C,
        'right option'   : 0x3D,
        'roption'        : 0x3D,
        'right control'  : 0x3E,
        'rcontrol'       : 0x3E,
        'fun'            : 0x3F,
        'function'       : 0x3F,
        'f17'            : 0x40,
        'volume up'      : 0x48,
        'volume down'    : 0x49,
        'mute'           : 0x4A,
        'f18'            : 0x4F,
        'f19'            : 0x50,
        'f20'            : 0x5A,
        'f5'             : 0x60,
        'f6'             : 0x61,
        'f7'             : 0x62,
        'f3'             : 0x63,
        'f8'             : 0x64,
        'f9'             : 0x65,
        'f11'            : 0x67,
        'f13'            : 0x69,
        'f16'            : 0x6A,
        'f14'            : 0x6B,
        'f10'            : 0x6D,
        'f12'            : 0x6F,
        'f15'            : 0x71,
        'help'           : 0x72,
        'home'           : 0x73,
        'pgup'           : 0x74,
        'page up'        : 0x74,
        'forward delete' : 0x75,
        'f4'             : 0x76,
        'end'            : 0x77,
        'f2'             : 0x78,
        'page down'      : 0x79,
        'pgdn'           : 0x79,
        'f1'             : 0x7A,
        'left'           : 0x7B,
        'right'          : 0x7C,
        'down'           : 0x7D,
        'up'             : 0x7E
    }

    # See: https://stackoverflow.com/q/3202629/55075
    def toKeyCode(self, c):
        shiftKey = False
        # Letter
        if c.isalpha():
            if not c.islower():
                shiftKey = True
                c = c.lower()
        if c in Keyboard.shiftChars:
            shiftKey = True
            c = Keyboard.shiftChars[c]
        if c in Keyboard.keyCodeMap:
            keyCode = Keyboard.keyCodeMap[c]
        else:
            keyCode = ord(c)
        return keyCode, shiftKey

    def KeyDown(self, k):
        keyCode, shiftKey = self.toKeyCode(k)

        time.sleep(0.0001)

        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
            time.sleep(0.0001)

        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
        time.sleep(0.0001)

        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
            time.sleep(0.0001)

    def KeyUp(self, k):
        keyCode, shiftKey = self.toKeyCode(k)

        time.sleep(0.0001)

        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
        time.sleep(0.0001)

    def KeyPress(self, k):
        keyCode, shiftKey = self.toKeyCode(k)

        time.sleep(0.0001)

        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
            time.sleep(0.0001)

        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
        time.sleep(0.0001)

        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
        time.sleep(0.0001)

        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
            time.sleep(0.0001)

    def Type(self, text):
        for key in text:
            self.KeyDown(key)
            self.KeyUp(key)

Here is the demo code using above class:

# DEMO
if __name__ == '__main__':
    keyboard = Keyboard()
    if sys.platform == "darwin":
        keyboard.Type('Hello World!')
    elif sys.platform == "win32":
        print("Error: Platform not supported!")

which will simulate typing Hello World! text on the current window.

You can run above code as a shell script. Check the link to the keyboard.py file.

Android read text raw resource file

Here is a simple method to read the text file from the raw folder:

public static String readTextFile(Context context,@RawRes int id){
    InputStream inputStream = context.getResources().openRawResource(id);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    byte buffer[] = new byte[1024];
    int size;
    try {
        while ((size = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, size);
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {

    }
    return outputStream.toString();
}

How to figure out the SMTP server host?

You could send yourself an email an look in the email header (In Outlook: Open the mail, View->Options, there is 'Internet headers)

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

Here is the complete set of JS and CSS required for the export table plugin to work perfectly.

Hope it will save your time

   <!--Import jQuery before export.js-->
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>


    <!--Data Table-->
    <script type="text/javascript"  src=" https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript"  src=" https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>

    <!--Export table buttons-->
    <script type="text/javascript"  src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
    <script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/pdfmake.min.js" ></script>
    <script type="text/javascript"  src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/vfs_fonts.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.2.1/js/buttons.print.min.js"></script>

<!--Export table button CSS-->

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.2.4/css/buttons.dataTables.min.css">

javascript to add export buttons on the table with id = tbl

  $('#tbl').DataTable({
                        dom: 'Bfrtip',
                        buttons: [
                            'copy', 'csv', 'excel', 'pdf', 'print'
                        ]
                    });

Result :-

enter image description here

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

In python, it's called slicing. Here is an example of python's slice notation:

>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']

Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

Do it like this:

SSLSocket socket = (SSLSocket) sslFactory.createSocket(host, port);
socket.setEnabledProtocols(new String[]{"SSLv3", "TLSv1"});

How to set the timezone in Django?

I found this question looking to change the timezone in my Django project's settings.py file to the United Kingdom.

Using the tz database in jfs' solution I found the answer:

    TIME_ZONE = 'Europe/London'

Ignore mapping one property with Automapper

Hello All Please Use this it's working fine... for auto mapper use multiple .ForMember in C#

        if (promotionCode.Any())
        {
            Mapper.Reset();
            Mapper.CreateMap<PromotionCode, PromotionCodeEntity>().ForMember(d => d.serverTime, o => o.MapFrom(s => s.promotionCodeId == null ? "date" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", DateTime.UtcNow.AddHours(7.0))))
                .ForMember(d => d.day, p => p.MapFrom(s => s.code != "" ? LeftTime(Convert.ToInt32(s.quantity), Convert.ToString(s.expiryDate), Convert.ToString(DateTime.UtcNow.AddHours(7.0))) : "Day"))
                .ForMember(d => d.subCategoryname, o => o.MapFrom(s => s.subCategoryId == 0 ? "" : Convert.ToString(subCategory.Where(z => z.subCategoryId.Equals(s.subCategoryId)).FirstOrDefault().subCategoryName)))
                .ForMember(d => d.optionalCategoryName, o => o.MapFrom(s => s.optCategoryId == 0 ? "" : Convert.ToString(optionalCategory.Where(z => z.optCategoryId.Equals(s.optCategoryId)).FirstOrDefault().optCategoryName)))
                .ForMember(d => d.logoImg, o => o.MapFrom(s => s.vendorId == 0 ? "" : Convert.ToString(vendorImg.Where(z => z.vendorId.Equals(s.vendorId)).FirstOrDefault().logoImg)))
                .ForMember(d => d.expiryDate, o => o.MapFrom(s => s.expiryDate == null ? "" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", s.expiryDate))); 
            var userPromotionModel = Mapper.Map<List<PromotionCode>, List<PromotionCodeEntity>>(promotionCode);
            return userPromotionModel;
        }
        return null;

Observable Finally on Subscribe

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

Simple example:

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

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

Simple example:

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

PHP - Redirect and send data via POST

It would involve the cURL PHP extension.

$ch = curl_init('http://www.provider.com/process.jsp');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John");
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);  // RETURN THE CONTENTS OF THE CALL
$resp = curl_exec($ch);

How to insert data using wpdb

Just use wpdb->insert(tablename, coloumn, format) and wp will prepare that's query

<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
   "name" => $name,
   "email" => $email,
   "phone" => $phone,
   "country" => $country,
   "course" => $course,
   "message" => $message,
   "datesent" => $now ,
));
?>

How to scanf only integer?

If you're set on using scanf, you can do something like the following:

int val;
char follow;  
int read = scanf( "%d%c", &val, &follow );

if ( read == 2 )
{
  if ( isspace( follow ) )
  {
    // input is an integer followed by whitespace, accept
  }
  else
  {
    // input is an integer followed by non-whitespace, reject
  }
}
else if ( read == 1 )
{
  // input is an integer followed by EOF, accept
}
else
{
  // input is not an integer, reject
}

Best way to check if an PowerShell Object exist?

I had the same Problem. This solution works for me.

$Word = $null
$Word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('word.application')
if ($Word -eq $null)
{
    $Word = new-object -ComObject word.application
}

https://msdn.microsoft.com/de-de/library/system.runtime.interopservices.marshal.getactiveobject(v=vs.110).aspx

How can I specify a display?

The way that X works is the same as the way any network program works. You have a server of some description (in this case, the X display server) which runs on a specific machine, and you have X clients (like firefox) that try to connect to that server to get their information displayed.

Often (on "home" machines), the client and server run on the same box and there's only one server, but X is powerful enough that this doesn't need to happen. It was built with the server/client separation built in from the start.

This allows you to do such wondrous things such as log on to your box (in text mode) halfway around the planet, tell it that the display server is the box you're currently on and, voila, the windows suddenly start appearing locally.

In order for a client to interact with a user, it needs to know how to find the server. There are a number of ways to do this. Many clients allow the -display or --displayoption to specify it:

xeyes -display paxbox1.paxco.com:0.0

Many will use the DISPLAY environment variable if a display isn't specifically given. You can set this variable like any other:

DISPLAY=paxbox1.paxco.com:0.0; export DISPLAY # in .profile
export DISPLAY=paxbox1.paxco.com:0.0 # in your shell
DISPLAY=paxbox1.paxco.com:0.0 firefox & # for that command (shell permitting)

The first part of the DISPLAY variable is just the address of the display server machine. It follows the same rule as any other IP address; it can be a resolvable DNS name (including localhost) or a specific IP address (such as 192.168.10.55).

The second part is X-specific. It gives the X "display" (X server) number and screen number to use. The first (display number) generally refers to a group of devices containing one or more screens but with a single keyboard and mouse (i.e., one input stream). The screen number generally gives the specific screen within that group.

An example would be:

+----------------------------------------+
|paxbox1.paxco.com|                      |
+-----------------+                      |
|                                        |
|  +----------+----+  +----------+----+  |
|  |Display :0|    |  |Display :1|    |  |
|  +----------+    |  +----------+    |  |
|  |               |  |               |  |
|  | +-----------+ |  |               |  |
|  | |Screen :0.0| |  |               |  |
|  | +-----------+ |  |               |  |
|  | +-----------+ |  |               |  |
|  | |Screen :0.1| |  |               |  |
|  | +-----------+ |  |               |  |
|  | +-----------+ |  | +-----------+ |  |
|  | |Screen :0.2| |  | |Screen :1.0| |  |
|  | +-----------+ |  | +-----------+ |  |
|  | +-----------+ |  | +-----------+ |  |
|  | |Screen :0.3| |  | |Screen :1.1| |  |
|  | +-----------+ |  | +-----------+ |  |
|  | +-----------+ |  | +-----------+ |  |
|  | | Keyboard  | |  | |  Keyboard | |  |
|  | +-----------+ |  | +-----------+ |  |
|  | +-----------+ |  | +-----------+ |  |
|  | |   Mouse   | |  | |   Mouse   | |  |
|  | +-----------+ |  | +-----------+ |  |
|  +---------------+  +---------------+  |
|                                        |
+----------------------------------------+

Here you have a single machine (paxbox1.paxco.com) with two display servers. The first has four screens and the second has two. The possibilities are then:

DISPLAY=paxbox1.paxco.com:0.0
DISPLAY=paxbox1.paxco.com:0.1
DISPLAY=paxbox1.paxco.com:0.2
DISPLAY=paxbox1.paxco.com:0.3
DISPLAY=paxbox1.paxco.com:1.0
DISPLAY=paxbox1.paxco.com:1.1

depending on where you want your actual windows to appear and which input devices you want to use.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

The new URL for the repository is now http://download.eclipse.org/tools/pdt/updates/release. In Eclipse: open Help -> install new sofware -> add. Then paste this URL in the location.

Mark the check boxes you want and click next.

How do I initialise all entries of a matrix with a specific value?

The ones method is much faster than using repmat:

>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds. 

And, in my opinion, makes for much more readable code.

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

After a long reserch and digging too deep i found the solution of certificate pinning in android and yes its different from iOS where we need a certificate itself but in android we just need a hash pin and that's it.

How to get hash pin for certificate?

Initially just use a wrong hash pin and your java class will throw an error with correct hash pins or pin chain, just copy and paste into your code thats it.

This solution fixed my problem : https://stackoverflow.com/a/45853669/3448003

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Numpy converting array from float to strings

If the main problem is the loss of precision when converting from a float to a string, one possible way to go is to convert the floats to the decimalS: http://docs.python.org/library/decimal.html.

In python 2.7 and higher you can directly convert a float to a decimal object.

Origin is not allowed by Access-Control-Allow-Origin

This might be handy for anyone who needs to an exception for both 'www' and 'non-www' versions of a referrer:

 $referrer = $_SERVER['HTTP_REFERER'];
 $parts = parse_url($referrer);
 $domain = $parts['host'];

 if($domain == 'google.com')
 {
         header('Access-Control-Allow-Origin: http://google.com');
 }
 else if($domain == 'www.google.com')
 {
         header('Access-Control-Allow-Origin: http://www.google.com');
 }

Change the Textbox height?

Some of you were close but changing designer code like that is annoying because you always have to go back and change it again.

The original OP was likely using an older version of .net because version 4 autosizes the textbox height to fit the font, but does not size comboboxes and textboxes the same which is a completely different problem but drew me here.

This is the problem I faced when placing textboxes next to comboboxes on a form. This is a bit irritating because who wants two controls side-by-side with different heights? Or different fonts to force heights? Step it up Microsoft, this should be simple!

I'm using .net framework 4 in VS2012 and the following was the simplest solution for me.

In the form load event (or anywhere as long as fired after InitializeComponent): textbox.AutoSize = false Then set the height to whatever you want. For me I wanted my text boxes and combo boxes to be the same height so textbox.height = combobox.height did the trick for me.

Notes:

1) The designer will not be affected so it will require you to start your project to see the end result, so there may be some trial and error.

2) Align the tops of your comboboxes and textboxes if you want them to be aligned properly after the resize because the textboxes will grow down.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

Interesting enough, this error also occurs, at time of opening when the .XLS? file is incorrectly formed or require repairs.

A hard to find error is to many rows on a .xls (old excel) file.

Test it: manually open the affected file with excel desktop .

I use automation to process a few hundred files daily, when this error show up, I notify the owner via mail and save the unprocessed file on a temporary location.

Using BigDecimal to work with currencies

1) If you are limited to the double precision, one reason to use BigDecimals is to realize operations with the BigDecimals created from the doubles.

2) The BigDecimal consists of an arbitrary precision integer unscaled value and a non-negative 32-bit integer scale, while the double wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double

3) It should make no difference

You should have no difficulties with the $ and precision. One way to do it is using System.out.printf

Bootstrap Modal before form Submit

You can use browser default prompt window. Instead of basic <input type="submit" (...) > try:

<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>

Purpose of installing Twitter Bootstrap through npm?

If you NPM those modules you can serve them using static redirect.

First install the packages:

npm install jquery
npm install bootstrap

Then on the server.js:

var express = require('express');
var app = express();

// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap

Then, finally, at the .html:

<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>

I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.

Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.

how to make a cell of table hyperlink

Try this:

HTML:

<table width="200" border="1" class="table">
    <tr>
        <td><a href="#">&nbsp;</a></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
</table>

CSS:

.table a
{
    display:block;
    text-decoration:none;
}

I hope it will work fine.

Accessing Arrays inside Arrays In PHP

If $a is the array that's passed, $a[76][0]['id'] should give '76' and $a[76][1]['id'] should give '81', but I can't test as I don't have PHP installed on this machine.

Java: Best way to iterate through a Collection (here ArrayList)

There is additionally collections’ stream() util with Java 8

collection.forEach((temp) -> {
            System.out.println(temp);
});

or

collection.forEach(System.out::println);

More information about Java 8 stream and collections for wonderers link

How do I run Visual Studio as an administrator by default?

Windows 10

  1. Right click "Visual Studio" and select "Open file location Right click "Visual Studio" and select "Open file location"
  2. Right click "Visual Studio" and select "Properties" Right click "Visual Studio" and select "Properties"
  3. Click "Advanced" and check "Run as administrator" Click "Advanced" and check "Run as administrator"

How can I make space between two buttons in same div?

Another way to achieve this is to add a class .btn-space in your buttons

  <button type="button" class="btn btn-outline-danger btn-space"
  </button>
  <button type="button" class="btn btn-outline-primary btn-space"
  </button>

and define this class as follows

.btn-space {
    margin-right: 15px;
}

Rename computer and join to domain in one step with PowerShell

This solution is working:

  • Enter the computer in the Active Directory domain with authentication (no Restart)
  • Rename the computer with authentication (no Restart)
  • after, Restart

In code:

# get the credential 
$cred = get-credential

# enter the computer in the right place
Add-Computer -DomainName EPFL -Credential $cred -OUPath "...,DC=epfl,DC=ch"

# rename the computer with credential (because we are in the domain)
$Computer = Get-WmiObject Win32_ComputerSystem
$r = $Computer.Rename("NewComputerName", $cred.GetNetworkCredential().Password, $cred.Username)

How to fix "Referenced assembly does not have a strong name" error?

I was running into this with a ServiceStack dll I had installed with nuget. Turns out there was another set of dlls available that were labeled signed. Not going to be the answer for everyone, but you may just need to check for an existing signed version of your assembly. ServiceStack.Signed

How to overwrite the output directory in spark

If you are willing to use your own custom output format, you would be able to get the desired behaviour with RDD as well.

Have a look at the following classes: FileOutputFormat, FileOutputCommitter

In file output format you have a method named checkOutputSpecs, which is checking whether the output directory exists. In FileOutputCommitter you have the commitJob which is usually transferring data from the temporary directory to its final place.

I wasn't able to verify it yet (would do it, as soon as I have few free minutes) but theoretically: If I extend FileOutputFormat and override checkOutputSpecs to a method that doesn't throw exception on directory already exists, and adjust the commitJob method of my custom output committer to perform which ever logic that I want (e.g. Override some of the files, append others) than I may be able to achieve the desired behaviour with RDDs as well.

The output format is passed to: saveAsNewAPIHadoopFile (which is the method saveAsTextFile called as well to actually save the files). And the Output committer is configured at the application level.

How can I select from list of values in SQL Server

Select user id from list of user id:

SELECT * FROM my_table WHERE user_id IN (1,3,5,7,9,4);

How to autosize a textarea using Prototype?

Using ASP.NET, just simply do this:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Automatic Resize TextBox</title>
        <script type="text/javascript">
            function setHeight(txtarea) {
                txtarea.style.height = txtdesc.scrollHeight + "px";
            }
        </script>
    </head>

    <body>
        <form id="form1" runat="server">
            <asp:TextBox ID="txtarea" runat= "server" TextMode="MultiLine"  onkeyup="setHeight(this);" onkeydown="setHeight(this);" />
        </form>
    </body>
</html>

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

What you can do is set your default database using the sp_defaultdb system stored procedure. Log in as you have done and then click the New Query button. After that simply run the sp_defaultdb command as follows:

Exec sp_defaultdb @loginame='login', @defdb='master' 

Is there a way to override class variables in Java?

Just Call super.variable in sub class constructor

public abstract class Beverage {

int cost;


int getCost() {

    return cost;

}

}`

public class Coffee extends Beverage {


int cost = 10;
Coffee(){
    super.cost = cost;
}


}`

public class Driver {

public static void main(String[] args) {

    Beverage coffee = new Coffee();

    System.out.println(coffee.getCost());

}

}

Output is 10.

How to color System.out.println output?

Escape sequences must be interpreted by SOMETHING to be converted to color. The standard CMD.EXE used by java when started from the command line, doesn't support this so therefore Java does not.

AngularJS - difference between pristine/dirty and touched/untouched

AngularJS Developer Guide - CSS classes used by AngularJS

  • @property {boolean} $untouched True if control has not lost focus yet.
  • @property {boolean} $touched True if control has lost focus.
  • @property {boolean} $pristine True if user has not interacted with the control yet.
  • @property {boolean} $dirty True if user has already interacted with the control.

How to detect if CMD is running as Administrator/has elevated privileges?

Works for Win7 Enterprise and Win10 Enterprise

@if DEFINED SESSIONNAME (
    @echo.
    @echo You must right click to "Run as administrator"
    @echo Try again
    @echo.
    @pause
    @goto :EOF
)

Got a NumberFormatException while trying to parse a text file for objects

I changed Scanner fin = new Scanner(file); to Scanner fin = new Scanner(new File(file)); and it works perfectly now. I didn't think the difference mattered but there you go.

How do I change the number of open files limit in Linux?

1) Add the following line to /etc/security/limits.conf

webuser hard nofile 64000

then login as webuser

su - webuser

2) Edit following two files for webuser

append .bashrc and .bash_profile file by running

echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile

3) Log out, then log back in and verify that the changes have been made correctly:

$ ulimit -a | grep open
open files                      (-n) 64000

Thats it and them boom, boom boom.

How to get the changes on a branch in Git

To see the log of the current branch since branching off master:

git log master...

If you are currently on master, to see the log of a different branch since it branched off master:

git log ...other-branch

Check a radio button with javascript

Do not mix CSS/JQuery syntax (# for identifier) with native JS.

Native JS solution:

document.getElementById("_1234").checked = true;

JQuery solution:

$("#_1234").prop("checked", true);

How to avoid the "divide by zero" error in SQL?

In case you want to return zero, in case a zero devision would happen, you can use:

SELECT COALESCE(dividend / NULLIF(divisor,0), 0) FROM sometable

For every divisor that is zero, you will get a zero in the result set.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This configuration to your nginx.conf should help you.

https://gist.github.com/baskaran-md/e46cc25ccfac83f153bb

server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    error_page  404     /404.html;
    error_page  403     /403.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    # ...
}

How to split elements of a list?

Try iterating through each element of the list, then splitting it at the tab character and adding it to a new list.

for i in list:
    newList.append(i.split('\t')[0])

Padding characters in printf

Bash + seq to allow parameter expansion

Similar to @Dennis Williamson answer, but if seq is available, the length of the pad string need not be hardcoded. The following code allows for passing a variable to the script as a positional parameter:

COLUMNS="${COLUMNS:=80}"
padlength="${1:-$COLUMNS}"
pad=$(printf '\x2D%.0s' $(seq "$padlength") )

string2='bbbbbbb'
for string1 in a aa aaaa aaaaaaaa
do
     printf '%s' "$string1"
     printf '%*.*s' 0 $(("$padlength" - "${#string1}" - "${#string2}" )) "$pad"
     printf '%s\n' "$string2"
     string2=${string2:1}
done

The ASCII code "2D" is used instead of the character "-" to avoid the shell interpreting it as a command flag. Another option is "3D" to use "=".

In absence of any padlength passed as an argument, the code above defaults to the 80 character standard terminal width.

To take advantage of the the bash shell variable COLUMNS (i.e., the width of the current terminal), the environment variable would need to be available to the script. One way is to source all the environment variables by executing the script preceded by . ("dot" command), like this:

. /path/to/script

or (better) explicitly pass the COLUMNS variable when executing, like this:

/path/to/script $COLUMNS

Changing the interval of SetInterval while it's running

I like this question - inspired a little timer object in me:

window.setVariableInterval = function(callbackFunc, timing) {
  var variableInterval = {
    interval: timing,
    callback: callbackFunc,
    stopped: false,
    runLoop: function() {
      if (variableInterval.stopped) return;
      var result = variableInterval.callback.call(variableInterval);
      if (typeof result == 'number')
      {
        if (result === 0) return;
        variableInterval.interval = result;
      }
      variableInterval.loop();
    },
    stop: function() {
      this.stopped = true;
      window.clearTimeout(this.timeout);
    },
    start: function() {
      this.stopped = false;
      return this.loop();
    },
    loop: function() {
      this.timeout = window.setTimeout(this.runLoop, this.interval);
      return this;
    }
  };

  return variableInterval.start();
};

Example use

var vi = setVariableInterval(function() {
  // this is the variableInterval - so we can change/get the interval here:
  var interval = this.interval;

  // print it for the hell of it
  console.log(interval);

  // we can stop ourselves.
  if (interval>4000) this.stop();

  // we could return a new interval after doing something
  return interval + 100;
}, 100);  

// we can change the interval down here too
setTimeout(function() {
  vi.interval = 3500;
}, 1000);

// or tell it to start back up in a minute
setTimeout(function() {
  vi.interval = 100;
  vi.start();
}, 60000);

Find Active Tab using jQuery and Twitter Bootstrap

Twitter Bootstrap assigns the active class to the li element that represents the active tab:

$("ul#sampleTabs li.active")

An alternative is to bind the shown event of each tab, and save the active tab:

var activeTab = null;
$('a[data-toggle="tab"]').on('shown', function (e) {
  activeTab = e.target;
})

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

Adding a Time to a DateTime in C#

Combine both. The Date-Time-Picker does support picking time, too.

You just have to change the Format-Property and maybe the CustomFormat-Property.

How to use refs in React with Typescript

If you're using React.FC, add the HTMLDivElement interface:

const myRef = React.useRef<HTMLDivElement>(null);

And use it like the following:

return <div ref={myRef} />;

How to add a file to the last commit in git?

Yes, there's a command git commit --amend which is used to "fix" last commit.

In your case it would be called as:

git add the_left_out_file
git commit --amend --no-edit

The --no-edit flag allow to make amendment to commit without changing commit message.

EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

All answers mentioned here are too old and lengthy.The best and short solution that work with latest Navigationview is

@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
    super.onDrawerSlide(drawerView, slideOffset);

    try {
        //int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
            // Do something for lollipop and above versions

        Window window = getWindow();

        // clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        // finally change the color to any color with transparency

         window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDarktrans));}

    } catch (Exception e) {

        Crashlytics.logException(e);

    }
}

this is going to change your status bar color to transparent when you open the drawer

Now when you close the drawer you need to change status bar color again to dark.So you can do it in this way.

        public void onDrawerClosed(View drawerView) {
        super.onDrawerClosed(drawerView);
        try {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    // Do something for lollipop and above versions

    Window window = getWindow();

    // clear FLAG_TRANSLUCENT_STATUS flag:
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

    // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

    // finally change the color again to dark
    window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));}
    } catch (Exception e) {
    Crashlytics.logException(e);
                    }
                    }

and then in main layout add a single line i.e

            android:fitsSystemWindows="true"

and your drawer layout will look like

            <android.support.v4.widget.DrawerLayout     
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/drawer_layout"
            android:fitsSystemWindows="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

and your navigation view will look like

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/navigation_header"
        app:menu="@menu/drawer"
        />

I have tested it and its fully working.Hope it helps someone.This may not be the best approach but it works smoothly and is simple to implement. Mark it up if it helps.Happy coding :)

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

How to get certain commit from GitHub project

Instead of navigating through the commits, you can also hit the y key (Github Help, Keyboard Shortcuts) to get the "permalink" for the current revision / commit.
This will change the URL from https://github.com/<user>/<repository> (master / HEAD) to https://github.com/<user>/<repository>/tree/<commit id>.

In order to download the specific commit, you'll need to reload the page from that URL, so the Clone or Download button will point to the "snapshot" https://github.com/<user>/<repository>/archive/<commit id>.zip instead of the latest https://github.com/<user>/<repository>/archive/master.zip.

How to read multiple Integer values from a single line of input in Java?

I use it all the time on hackerrank/leetcode

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String  lines = br.readLine();    
        
    String[] strs = lines.trim().split("\\s+");
            
    for (int i = 0; i < strs.length; i++) {
    a[i] = Integer.parseInt(strs[i]);
    }

How to write a cron that will run a script every day at midnight?

Sometimes you'll need to specify PATH and GEM_PATH using crontab with rvm.

Like this:

# top of crontab file
PATH=/home/user_name/.rvm/gems/ruby-2.2.0/bin:/home/user_name/.rvm/gems/ruby-2.2.0@global/bin:/home/user_name/.rvm/rubies/ruby-2.2.$
GEM_PATH=/home/user_name/.rvm/gems/ruby-2.2.0:/home/user_name/.rvm/gems/ruby-2.2.0@global

# jobs
00 00 * * * ruby path/to/your/script.rb
00 */4 * * * ruby path/to/your/script2.rb
00 8,12,22 * * * ruby path/to/your/script3.rb

How can I pass a parameter to a setTimeout() callback?

setTimeout is part of the DOM defined by WHAT WG.

https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html

The method you want is:—

handle = self.setTimeout( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

setTimeout(postinsql, 4000, topicId);

Apparently, extra arguments are supported in IE10. Alternatively, you can use setTimeout(postinsql.bind(null, topicId), 4000);, however passing extra arguments is simpler, and that's preferable.

Historical factoid: In days of VBScript, in JScript, setTimeout's third parameter was the language, as a string, defaulting to "JScript" but with the option to use "VBScript". https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa741500(v%3Dvs.85)

How to take screenshot of a div with JavaScript?

As far as I know its not possible with javascript.

What you can do for every result create a screenshot, save it somewhere and point the user when clicked on save result. (I guess no of result is only 10 so not a big deal to create 10 jpeg image of results)

How to use a link to call JavaScript?

I think you can use the onclick event, something like this:

<a onclick="jsFunction();">

Select entries between dates in doctrine 2

I believe the correct way of doing it would be to use query builder expressions:

$now = new DateTimeImmutable();
$thirtyDaysAgo = $now->sub(new \DateInterval("P30D"));
$qb->select('e')
   ->from('Entity','e')
   ->add('where', $qb->expr()->between(
            'e.datefield',
            ':from',
            ':to'
        )
    )
   ->setParameters(array('from' => $thirtyDaysAgo, 'to' => $now));

http://docs.doctrine-project.org/en/latest/reference/query-builder.html#the-expr-class

Edit: The advantage this method has over any of the other answers here is that it's database software independent - you should let Doctrine handle the date type as it has an abstraction layer for dealing with this sort of thing.

If you do something like adding a string variable in the form 'Y-m-d' it will break when it goes to a database platform other than MySQL, for example.

Iterating each character in a string using Python

Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.

i = 0
while i < len(str):
    print str[i]
    i += 1

But then again, why do that when strings are inherently iterable?

for i in str:
    print i

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

I was struggling with this as well. I used an interceptor, it captures the response headers, then clone the headers(since headers are immutable objects) and then sends the modified headers. https://angular.io/guide/http#intercepting-requests-and-responses

Get path of executable

This is probably the most natural way to do it, while covering most major desktop platforms. I am not certain, but I believe this should work with all the BSD's, not just FreeBSD, if you change the platform macro check to cover all of them. If I ever get around to installing Solaris, I'll be sure to add that platform to the supported list.

Features full UTF-8 support on Windows, which not everyone cares enough to go that far.

procinfo/win32/procinfo.cpp

#ifdef _WIN32
#include "../procinfo.h"
#include <windows.h>
#include <tlhelp32.h>
#include <cstddef>
#include <vector>
#include <cwchar>

using std::string;
using std::wstring;
using std::vector;
using std::size_t;

static inline string narrow(wstring wstr) {
  int nbytes = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.length(), NULL, 0, NULL, NULL);
  vector<char> buf(nbytes);
  return string{ buf.data(), (size_t)WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.length(), buf.data(), nbytes, NULL, NULL) };
}

process_t ppid_from_pid(process_t pid) {        
  process_t ppid;       
  HANDLE hp = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);      
  PROCESSENTRY32 pe = { 0 };        
  pe.dwSize = sizeof(PROCESSENTRY32);       
  if (Process32First(hp, &pe)) {        
    do {        
      if (pe.th32ProcessID == pid) {        
        ppid = pe.th32ParentProcessID;      
        break;      
      }     
    } while (Process32Next(hp, &pe));       
  }     
  CloseHandle(hp);      
  return ppid;      
}

string path_from_pid(process_t pid) {
  string path;
  HANDLE hm = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
  MODULEENTRY32W me = { 0 };
  me.dwSize = sizeof(MODULEENTRY32W);
  if (Module32FirstW(hm, &me)) {
    do {
      if (me.th32ProcessID == pid) {
        path = narrow(me.szExePath);
        break;
      }
    } while (Module32NextW(hm, &me));
  }
  CloseHandle(hm);
  return path;
}
#endif

procinfo/macosx/procinfo.cpp

#if defined(__APPLE__) && defined(__MACH__)
#include "../procinfo.h"
#include <libproc.h>

using std::string;

string path_from_pid(process_t pid) {
  string path;
  char buffer[PROC_PIDPATHINFO_MAXSIZE];
  if (proc_pidpath(pid, buffer, sizeof(buffer)) > 0) {
    path = string(buffer) + "\0";
  }
  return path;
}
#endif

procinfo/linux/procinfo.cpp

#ifdef __linux__
#include "../procinfo.h"
#include <cstdlib>

using std::string;
using std::to_string;

string path_from_pid(process_t pid) {
  string path;
  string link = string("/proc/") + to_string(pid) + string("/exe");
  char *buffer = realpath(link.c_str(), NULL);
  path = buffer ? : "";
  free(buffer);
  return path;
}
#endif

procinfo/freebsd/procinfo.cpp

#ifdef __FreeBSD__
#include "../procinfo.h"
#include <sys/sysctl.h>
#include <cstddef>

using std::string;
using std::size_t;

string path_from_pid(process_t pid) {
  string path;
  size_t length;
  // CTL_KERN::KERN_PROC::KERN_PROC_PATHNAME(pid)
  int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, pid };
  if (sysctl(mib, 4, NULL, &length, NULL, 0) == 0) {
    path.resize(length, '\0');
    char *buffer = path.data();
    if (sysctl(mib, 4, buffer, &length, NULL, 0) == 0) {
      path = string(buffer) + "\0";
    }
  }
  return path;
}
#endif

procinfo/procinfo.cpp

#include "procinfo.h"
#ifdef _WiN32
#include <process.h>
#endif
#include <unistd.h>
#include <cstddef>

using std::string;
using std::size_t;

process_t pid_from_self() {
  #ifdef _WIN32
  return _getpid();
  #else
  return getpid();
  #endif
}

process_t ppid_from_self() {
  #ifdef _WIN32
  return ppid_from_pid(pid_from_self());
  #else
  return getppid();
  #endif
}

string dir_from_pid(process_t pid) {
  string fname = path_from_pid(pid);
  size_t fp = fname.find_last_of("/\\");
  return fname.substr(0, fp + 1);
}

string name_from_pid(process_t pid) {
  string fname = path_from_pid(pid);
  size_t fp = fname.find_last_of("/\\");
  return fname.substr(fp + 1);
}

procinfo/procinfo.h

#ifdef _WiN32
#include <windows.h>
typedef DWORD process_t;
#else
#include <sys/types.h>
typedef pid_t process_t;
#endif
#include <string>

/* windows-only helper function */
process_t ppid_from_pid(process_t pid);

/* get current process process id */
process_t pid_from_self();

/* get parent process process id */
process_t ppid_from_self();

/* std::string possible_result = "C:\\path\\to\\file.exe"; */
std::string path_from_pid(process_t pid);

/* std::string possible_result = "C:\\path\\to\\"; */
std::string dir_from_pid(process_t pid);

/* std::string possible_result = "file.exe"; */
std::string name_from_pid(process_t pid);

This allows getting the full path to the executable of pretty much any process id, except on Windows there are some process's with security attributes which simply will not allow it, so wysiwyg, this solution is not perfect.

To address what the question was asking more precisely, you may do this:

procinfo.cpp

#include "procinfo/procinfo.h"
#include <iostream>

using std::string;
using std::cout;
using std::endl;

int main() {
  cout << dir_from_pid(pid_from_self()) << endl;
  return 0;
}

Build the above file structure with this command:

procinfo.sh

cd "${0%/*}"
g++ procinfo.cpp procinfo/procinfo.cpp procinfo/win32/procinfo.cpp procinfo/macosx/procinfo.cpp procinfo/linux/procinfo.cpp procinfo/freebsd/procinfo.cpp -o procinfo.exe

For downloading a copy of the files listed above:

git clone git://github.com/time-killer-games/procinfo.git

For more cross-platform process-related goodness:

https://github.com/time-killer-games/enigma-dev

See the readme for a list of most of the functions included.

How do I style (css) radio buttons and labels?

The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.

Getting the Label Near the Radio Button

I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float: territory):

  • Use <br />s to split the options apart and some CSS to vertically align them:
<style type='text/css'>
    .input input
    {
        width: 20px;
    }
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

Applying a Style to the Currently Selected Label + Radio Button

Styling the <label> is why you'll need to resort to Javascript. A library like jQuery is perfect for this:

<style type='text/css'>
    .input label.focused
    {
        background-color: #EEEEEE;
        font-style: italic;
    }
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
    $(document).ready(function() {
        $('.input :radio').focus(updateSelectedStyle);
        $('.input :radio').blur(updateSelectedStyle);
        $('.input :radio').change(updateSelectedStyle);
    })

    function updateSelectedStyle() {
        $('.input :radio').removeClass('focused').next().removeClass('focused');
        $('.input :radio:checked').addClass('focused').next().addClass('focused');
    }
</script>

The focus and blur hooks are needed to make this work in IE.

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Binding objects defined in code-behind

You can try x:Reference trick

<Window ... x:Name="myWindow"><ListBox ItemsSource="{Binding Items, Source={x:Reference myWindow}}" /></Window>

How to check if all inputs are not empty with jQuery

You can do it.here is code

<!DOCTYPE html>
<html lang="en">
 <head>
 <meta charset="UTF-8">
 <title></title>
 <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
    border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;

$(".bs-example input").each(function(){
    if ($.trim($(this).val()).length == 0){
        $(this).addClass("highlight");
        isFormValid = false;
        $(this).focus();
    }
    else{
        $(this).removeClass("highlight");
    }
});

if (!isFormValid) { 
    alert("Please fill in all the required fields (indicated by *)");
}

  return isFormValid;
 }  
 </script>
</head>
 <body>
 <div class="bs-example">
<form onsubmit="return test()">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="text" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
   </form>
  </div>
 </body>
 </html> 

Loading custom configuration files

the articles posted by Ricky are very good, but unfortunately they don't answer your question.

To solve your problem you should try this piece of code:

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

If need to access a value within the config you can use the index operator:

config.AppSettings.Settings["test"].Value;

How to prevent a background process from being stopped after closing SSH client in Linux

On systemd/Linux, systemd-run is a nice tool to launch session-independent processes.

ALTER COLUMN in sqlite

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.

  1. BEGIN TRANSACTION;
  2. CREATE TEMPORARY TABLE t1_backup(a,b);
  3. INSERT INTO t1_backup SELECT a,b FROM t1;
  4. DROP TABLE t1;
  5. CREATE TABLE t1(a,b);
  6. INSERT INTO t1 SELECT a,b FROM t1_backup;
  7. DROP TABLE t1_backup;
  8. COMMIT

For more detail you can refer the link.

How can I tail a log file in Python?

Using the sh module (pip install sh):

from sh import tail
# runs forever
for line in tail("-f", "/var/log/some_log_file.log", _iter=True):
    print(line)

[update]

Since sh.tail with _iter=True is a generator, you can:

import sh
tail = sh.tail("-f", "/var/log/some_log_file.log", _iter=True)

Then you can "getNewData" with:

new_data = tail.next()

Note that if the tail buffer is empty, it will block until there is more data (from your question it is not clear what you want to do in this case).

[update]

This works if you replace -f with -F, but in Python it would be locking. I'd be more interested in having a function I could call to get new data when I want it, if that's possible. – Eli

A container generator placing the tail call inside a while True loop and catching eventual I/O exceptions will have almost the same effect of -F.

def tail_F(some_file):
    while True:
        try:
            for line in sh.tail("-f", some_file, _iter=True):
                yield line
        except sh.ErrorReturnCode_1:
            yield None

If the file becomes inaccessible, the generator will return None. However it still blocks until there is new data if the file is accessible. It remains unclear for me what you want to do in this case.

Raymond Hettinger approach seems pretty good:

def tail_F(some_file):
    first_call = True
    while True:
        try:
            with open(some_file) as input:
                if first_call:
                    input.seek(0, 2)
                    first_call = False
                latest_data = input.read()
                while True:
                    if '\n' not in latest_data:
                        latest_data += input.read()
                        if '\n' not in latest_data:
                            yield ''
                            if not os.path.isfile(some_file):
                                break
                            continue
                    latest_lines = latest_data.split('\n')
                    if latest_data[-1] != '\n':
                        latest_data = latest_lines[-1]
                    else:
                        latest_data = input.read()
                    for line in latest_lines[:-1]:
                        yield line + '\n'
        except IOError:
            yield ''

This generator will return '' if the file becomes inaccessible or if there is no new data.

[update]

The second to last answer circles around to the top of the file it seems whenever it runs out of data. – Eli

I think the second will output the last ten lines whenever the tail process ends, which with -f is whenever there is an I/O error. The tail --follow --retry behavior is not far from this for most cases I can think of in unix-like environments.

Perhaps if you update your question to explain what is your real goal (the reason why you want to mimic tail --retry), you will get a better answer.

The last answer does not actually follow the tail and merely reads what's available at run time. – Eli

Of course, tail will display the last 10 lines by default... You can position the file pointer at the end of the file using file.seek, I will left a proper implementation as an exercise to the reader.

IMHO the file.read() approach is far more elegant than a subprocess based solution.

Where is svcutil.exe in Windows 7?

If you are using vs 2010 then you can get it in

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools

Invalid http_host header

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']

and then restart your apache. in ubuntu:

/etc/init.d/apache2 restart

How to remove all white spaces in java

String a="string with                multi spaces ";

String b= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//it work fine with any spaces

Add CSS class to a div in code behind

Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.

public static void RemoveCssClass(this WebControl control, String css) {
  control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}

public static void AddCssClass(this WebControl control, String css) {
  control.RemoveCssClass(css);
  css += " " + control.CssClass;
  control.CssClass = css;
}

Usage: hlCreateNew.AddCssClass("disabled");

Usage: hlCreateNew.RemoveCssClass("disabled");

How can I change the Java Runtime Version on Windows (7)?

Go to control panel --> Java You can select the active version here

Int to byte array

This may be OT but if you are serializing a lot of primitive types or POD structures, Google Protocol Buffers for .Net might be useful to you. This addresses the endianness issue @Marc raised above, among other useful features.

MySQL set current date in a DATETIME field on insert

Since MySQL 5.6.X you can do this:

ALTER TABLE `schema`.`users` 
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;

That way your column will be updated with the current timestamp when a new row is inserted, or updated.

If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP in the DEFAULT value field, like so:

enter image description here

http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html

Why is enum class preferred over plain enum?

C++ has two kinds of enum:

  1. enum classes
  2. Plain enums

Here are a couple of examples on how to declare them:

 enum class Color { red, green, blue }; // enum class
 enum Animal { dog, cat, bird, human }; // plain enum 

What is the difference between the two?

  • enum classes - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum or int)

  • Plain enums - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types

Example:

enum Color { red, green, blue };                    // plain enum 
enum Card { red_card, green_card, yellow_card };    // another plain enum 
enum class Animal { dog, deer, cat, bird, human };  // enum class
enum class Mammal { kangaroo, deer, human };        // another enum class

void fun() {

    // examples of bad use of plain enums:
    Color color = Color::red;
    Card card = Card::green_card;

    int num = color;    // no problem

    if (color == Card::red_card) // no problem (bad)
        cout << "bad" << endl;

    if (card == Color::green)   // no problem (bad)
        cout << "bad" << endl;

    // examples of good use of enum classes (safe)
    Animal a = Animal::deer;
    Mammal m = Mammal::deer;

    int num2 = a;   // error
    if (m == a)         // error (good)
        cout << "bad" << endl;

    if (a == Mammal::deer) // error (good)
        cout << "bad" << endl;

}

Conclusion:

enum classes should be preferred because they cause fewer surprises that could potentially lead to bugs.

jQuery if div contains this text, replace that part of the text

You can use the contains selector to search for elements containing a specific text

var elem = $('div.text_div:contains("This div contains some text")')?;
elem.text(elem.text().replace("contains", "Hello everyone"));

??????????????????????????????????????????

Encrypt Password in Configuration Files?

See what is available in Jetty for storing password (or hashes) in configuration files, and consider if the OBF encoding might be useful for you. Then see in the source how it is done.

http://www.eclipse.org/jetty/documentation/current/configuring-security-secure-passwords.html

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

  1. rename the new path to temp
  2. revert the new path (not temp!) so svn does not try to commit it
  3. commit the rest of your changes
  4. copy the path inside the repository: svn copy -m "copied path" -r
  5. update your working copy
  6. mv all files from temp to the new path, which comes from the update
  7. commit your local changes since revision
  8. Have a nice Day including history ;-)

C# how to use enum with switch

Since C# 8.0 introduced a new switch expression for enums you can do it even more elegant:

public double Calculate(int left, int right, Operator op) =>
            op switch 
        {
            Operator.PLUS => left + right,
            Operator.MINUS => left - right,
            Operator.MULTIPLY => left * right,
            Operator.DIVIDE => left / right,
            _    =>  0
        }

Ref. https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8

How do you properly return multiple values from a Promise?

Simply return a tuple:

    async add(dto: TDto): Promise<TDto> {
    console.log(`${this.storeName}.add(${dto})`);
    return firebase.firestore().collection(this.dtoName)
      .withConverter<TDto>(this.converter)
      .add(dto)
      .then(d => [d.update(this.id, d.id), d.id] as [any, string])
      .then(x => this.get(x[1]));
  }

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

Solved. I was getting same issue on ubuntu 18.04.01 LTS. No above options worked as I was using NVM (Node Version manager.) Solution is
before creating project,use command
nvm use 10
(my node version was 10.15.0, so I used "nvm use 10")
It will show you output-
Now using node v10.15.0 (npm v6.4.1)
Versions will vary as per individual systems. then create new project.

How to Convert JSON object to Custom C# object?

Another Really simple Solution is using the library Newtonsoft.Json:

User user = JsonConvert.DeserializeObject<User>(jsonString);