Programs & Examples On #Texinfo

Texinfo is a typesetting syntax used for generating documentation in both on-line and printed form (creating filetypes as dvi, html, pdf, etc., and its own hypertext format, info) with a single source file. It is a creation of the GNU Project, and used to produce documentation for GNU software (e.g. emacs, screen, glibc).

Can I use Homebrew on Ubuntu?

I just tried installing it using the ruby command but somehow the dependencies are not resolved hence brew does not completely install. But, try installing by cloning:

git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew

and then add the following to your .bash_profile:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

It should work..

How to get screen width without (minus) scrollbar?

.prop("clientWidth") and .prop("scrollWidth")

var actualInnerWidth = $("body").prop("clientWidth"); // El. width minus scrollbar width
var actualInnerWidth = $("body").prop("scrollWidth"); // El. width minus scrollbar width

in JavaScript:

var actualInnerWidth = document.body.clientWidth;     // El. width minus scrollbar width
var actualInnerWidth = document.body.scrollWidth;     // El. width minus scrollbar width

P.S: Note that to use scrollWidth reliably your element should not overflow horizontally

jsBin demo


You could also use .innerWidth() but this will work only on the body element

var innerWidth = $('body').innerWidth(); // Width PX minus scrollbar 

Url.Action parameters?

you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility. Then add the keys manually, HttpValueCollection do the encoding for you. And then just append the QueryString manually :

var qs = HttpUtility.ParseQueryString(""); 
qs.Add("name", "John")
qs.Add("contact", "calgary");
qs.Add("contact", "vancouver")

<a href="<%: Url.Action("GetByList", "Listing")%>?<%:qs%>">
    <span>People</span>
</a>

GCC fatal error: stdio.h: No such file or directory

I know my case is rare, but I'll still add it here for someone who troubleshoots it later. I had a Linux Kernel module target in my Makefile and I tried to compile my user space program together with the kernel module that doesn't have stdio. Making it a separate target solved the problem.

FFmpeg on Android

Inspired by many other FFmpeg on Android implementations out there (mainly the guadianproject), I found a solution (with Lame support also).

(lame and FFmpeg: https://github.com/intervigilium/liblame and http://bambuser.com/opensource)

to call FFmpeg:

new Thread(new Runnable() {

    @Override
    public void run() {

        Looper.prepare();

        FfmpegController ffmpeg = null;

        try {
            ffmpeg = new FfmpegController(context);
        } catch (IOException ioe) {
            Log.e(DEBUG_TAG, "Error loading ffmpeg. " + ioe.getMessage());
        }

        ShellDummy shell = new ShellDummy();
        String mp3BitRate = "192";

        try {
            ffmpeg.extractAudio(in, out, audio, mp3BitRate, shell);
        } catch (IOException e) {
            Log.e(DEBUG_TAG, "IOException running ffmpeg" + e.getMessage());
        } catch (InterruptedException e) {
            Log.e(DEBUG_TAG, "InterruptedException running ffmpeg" + e.getMessage());
        }

        Looper.loop();

    }

}).start();

and to handle the console output:

private class ShellDummy implements ShellCallback {

    @Override
    public void shellOut(String shellLine) {
        if (someCondition) {
            doSomething(shellLine);
        }
        Utils.logger("d", shellLine, DEBUG_TAG);
    }

    @Override
    public void processComplete(int exitValue) {
        if (exitValue == 0) {
            // Audio job OK, do your stuff: 

                            // i.e.             
                            // write id3 tags,
                            // calls the media scanner,
                            // etc.
        }
    }

    @Override
    public void processNotStartedCheck(boolean started) {
        if (!started) {
                            // Audio job error, as above.
        }
    }
}

jQuery - how can I find the element with a certain id?

This is one more option to find the element for above question

$("#tbIntervalos").find('td[id="'+horaInicial+'"]')

jQuery Datepicker with text input that doesn't allow user input

This question has a lot of older answers and readonly seems to be the generally accepted solution. I believe the better approach in modern browsers is to use the inputmode="none" in the HTML input tag:

<input type="text" ... inputmode="none" />

or, if you prefer to do it in script:

$(selector).attr('inputmode', 'none');

I haven't tested it extensively, but it is working well on the Android setups I have used it with.

Python time measure function

Timeit has two big flaws: it doesn't return the return value of the function, and it uses eval, which requires passing in extra setup code for imports. This solves both problems simply and elegantly:

def timed(f):
  start = time.time()
  ret = f()
  elapsed = time.time() - start
  return ret, elapsed

timed(lambda: database.foo.execute('select count(*) from source.apachelog'))
(<sqlalchemy.engine.result.ResultProxy object at 0x7fd6c20fc690>, 4.07547402381897)

DLL Load Library - Error Code 126

This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

Got that issue when .git folder is hidden and all files in it is hidden too. Make only .git folder hidden without recursive files update and it will work.

How to run a command in the background and get no output?

Use nohup if your background job takes a long time to finish or you just use SecureCRT or something like it login the server.

Redirect the stdout and stderr to /dev/null to ignore the output.

nohup /path/to/your/script.sh > /dev/null 2>&1 &

What is time_t ultimately a typedef to?

[root]# cat time.c

#include <time.h>

int main(int argc, char** argv)
{
        time_t test;
        return 0;
}

[root]# gcc -E time.c | grep __time_t

typedef long int __time_t;

It's defined in $INCDIR/bits/types.h through:

# 131 "/usr/include/bits/types.h" 3 4
# 1 "/usr/include/bits/typesizes.h" 1 3 4
# 132 "/usr/include/bits/types.h" 2 3 4

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

How to Set the Background Color of a JButton on the Mac OS

Have you tried setting JButton.setOpaque(true)?

JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);

How to remove all .svn directories from my application directories

If you don't like to see a lot of

find: `./.svn': No such file or directory

warnings, then use the -depth switch:

find . -depth -name .svn -exec rm -fr {} \;

Why do we need virtual functions in C++?

Here is a merged version of the C++ code for the first two answers.

#include        <iostream>
#include        <string>

using   namespace       std;

class   Animal
{
        public:
#ifdef  VIRTUAL
                virtual string  says()  {       return  "??";   }
#else
                string  says()  {       return  "??";   }
#endif
};

class   Dog:    public Animal
{
        public:
                string  says()  {       return  "woof"; }
};

string  func(Animal *a)
{
        return  a->says();
}

int     main()
{
        Animal  *a = new Animal();
        Dog     *d = new Dog();
        Animal  *ad = d;

        cout << "Animal a says\t\t" << a->says() << endl;
        cout << "Dog d says\t\t" << d->says() << endl;
        cout << "Animal dog ad says\t" << ad->says() << endl;

        cout << "func(a) :\t\t" <<      func(a) <<      endl;
        cout << "func(d) :\t\t" <<      func(d) <<      endl;
        cout << "func(ad):\t\t" <<      func(ad)<<      endl;
}

Two different results are:

Without #define virtual, it binds at compile time. Animal *ad and func(Animal *) all point to the Animal's says() method.

$ g++ virtual.cpp -o virtual
$ ./virtual 
Animal a says       ??
Dog d says      woof
Animal dog ad says  ??
func(a) :       ??
func(d) :       ??
func(ad):       ??

With #define virtual, it binds at run time. Dog *d, Animal *ad and func(Animal *) point/refer to the Dog's says() method as Dog is their object type. Unless [Dog's says() "woof"] method is not defined, it will be the one searched first in the class tree, i.e. derived classes may override methods of their base classes [Animal's says()].

$ g++ virtual.cpp -D VIRTUAL -o virtual
$ ./virtual 
Animal a says       ??
Dog d says      woof
Animal dog ad says  woof
func(a) :       ??
func(d) :       woof
func(ad):       woof

It is interesting to note that all class attributes (data and methods) in Python are effectively virtual. Since all objects are dynamically created at runtime, there is no type declaration or a need for keyword virtual. Below is Python's version of code:

class   Animal:
        def     says(self):
                return  "??"

class   Dog(Animal):
        def     says(self):
                return  "woof"

def     func(a):
        return  a.says()

if      __name__ == "__main__":

        a = Animal()
        d = Dog()
        ad = d  #       dynamic typing by assignment

        print("Animal a says\t\t{}".format(a.says()))
        print("Dog d says\t\t{}".format(d.says()))
        print("Animal dog ad says\t{}".format(ad.says()))

        print("func(a) :\t\t{}".format(func(a)))
        print("func(d) :\t\t{}".format(func(d)))
        print("func(ad):\t\t{}".format(func(ad)))

The output is:

Animal a says       ??
Dog d says      woof
Animal dog ad says  woof
func(a) :       ??
func(d) :       woof
func(ad):       woof

which is identical to C++'s virtual define. Note that d and ad are two different pointer variables referring/pointing to the same Dog instance. The expression (ad is d) returns True and their values are the same <main.Dog object at 0xb79f72cc>.

Apache shutdown unexpectedly

If you are using the latest Skype, go to:

Tools -> Options -> Advanced -> connection.

Disable the 'Use port 80 and 443 for alternatve.. '
Sign Out and Close all Skype windows. Try restart your Apache again.

Java logical operator short-circuiting

if(demon!=0&& num/demon>10)

Since the short-circuit form of AND(&&) is used, there is no risk of causing a run-time exception when demon is zero.

Ref. Java 2 Fifth Edition by Herbert Schildt

How do you detect where two line segments intersect?

Many answers have wrapped up all the calculations into a single function. If you need to calculate the line slopes, y-intercepts, or x-intercepts for use elsewhere in your code, you'll be making those calculations redundantly. I have separated out the respective functions, used obvious variable names, and commented my code to make it easier to follow. I needed to know if lines intersect infinitely beyond their endpoints, so in JavaScript:

http://jsfiddle.net/skibulk/evmqq00u/

var point_a = {x:0, y:10},
    point_b = {x:12, y:12},
    point_c = {x:10, y:0},
    point_d = {x:0, y:0},
    slope_ab = slope(point_a, point_b),
    slope_bc = slope(point_b, point_c),
    slope_cd = slope(point_c, point_d),
    slope_da = slope(point_d, point_a),
    yint_ab = y_intercept(point_a, slope_ab),
    yint_bc = y_intercept(point_b, slope_bc),
    yint_cd = y_intercept(point_c, slope_cd),
    yint_da = y_intercept(point_d, slope_da),
    xint_ab = x_intercept(point_a, slope_ab, yint_ab),
    xint_bc = x_intercept(point_b, slope_bc, yint_bc),
    xint_cd = x_intercept(point_c, slope_cd, yint_cd),
    xint_da = x_intercept(point_d, slope_da, yint_da),
    point_aa = intersect(slope_da, yint_da, xint_da, slope_ab, yint_ab, xint_ab),
    point_bb = intersect(slope_ab, yint_ab, xint_ab, slope_bc, yint_bc, xint_bc),
    point_cc = intersect(slope_bc, yint_bc, xint_bc, slope_cd, yint_cd, xint_cd),
    point_dd = intersect(slope_cd, yint_cd, xint_cd, slope_da, yint_da, xint_da);

console.log(point_a, point_b, point_c, point_d);
console.log(slope_ab, slope_bc, slope_cd, slope_da);
console.log(yint_ab, yint_bc, yint_cd, yint_da);
console.log(xint_ab, xint_bc, xint_cd, xint_da);
console.log(point_aa, point_bb, point_cc, point_dd);

function slope(point_a, point_b) {
  var i = (point_b.y - point_a.y) / (point_b.x - point_a.x);
  if (i === -Infinity) return Infinity;
  if (i === -0) return 0;
  return i;
}

function y_intercept(point, slope) {
    // Horizontal Line
    if (slope == 0) return point.y;
  // Vertical Line
    if (slope == Infinity)
  {
    // THE Y-Axis
    if (point.x == 0) return Infinity;
    // No Intercept
    return null;
  }
  // Angled Line
  return point.y - (slope * point.x);
}

function x_intercept(point, slope, yint) {
    // Vertical Line
    if (slope == Infinity) return point.x;
  // Horizontal Line
    if (slope == 0)
  {
    // THE X-Axis
    if (point.y == 0) return Infinity;
    // No Intercept
    return null;
  }
  // Angled Line
  return -yint / slope;
}

// Intersection of two infinite lines
function intersect(slope_a, yint_a, xint_a, slope_b, yint_b, xint_b) {
  if (slope_a == slope_b)
  {
    // Equal Lines
    if (yint_a == yint_b && xint_a == xint_b) return Infinity;
    // Parallel Lines
    return null;
  }
  // First Line Vertical
    if (slope_a == Infinity)
  {
    return {
        x: xint_a,
      y: (slope_b * xint_a) + yint_b
    };
  }
  // Second Line Vertical
    if (slope_b == Infinity)
  {
    return {
        x: xint_b,
      y: (slope_a * xint_b) + yint_a
    };
  }
  // Not Equal, Not Parallel, Not Vertical
  var i = (yint_b - yint_a) / (slope_a - slope_b);
  return {
    x: i,
    y: (slope_a * i) + yint_a
  };
}

How to construct a std::string from a std::vector<char>?

I think you can just do

std::string s( MyVector.begin(), MyVector.end() );

where MyVector is your std::vector.

Integrity constraint violation: 1452 Cannot add or update a child row:

First delete the constraint "fk_comments_projects1" and also its index. After that recreate it.

Sending email in .NET through Gmail

I had the same issue, but it was resolved by going to gmail's security settings and Allowing Less Secure apps. The Code from Domenic & Donny works, but only if you enabled that setting

If you are signed in (to Google) you can follow this link and toggle "Turn on" for "Access for less secure apps"

How to initailize byte array of 100 bytes in java with all 0's

byte[] bytes = new byte[100];

Initializes all byte elements with default values, which for byte is 0. In fact, all elements of an array when constructed, are initialized with default values for the array element's type.

Installation of SQL Server Business Intelligence Development Studio

I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.

I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.

I hope this helps.

Git will not init/sync/update new submodules

I had this same problem - it turned out that the .gitmodules file was committed, but the actual submodule commit (i.e. the record of the submodule's commit ID) wasn't.

Adding it manually seemed to do the trick - e.g.:

git submodule add http://github.com/sciyoshi/pyfacebook.git external/pyfacebook

(Even without removing anything from .git/config or .gitmodules.)

Then commit it to record the ID properly.

Adding some further comments to this working answer: If the git submodule init or git submodule update does'nt work, then as described above git submodule add url should do the trick. One can cross check this by

 git config --list

and one should get an entry of the submodule you want to pull in the result of the git config --list command. If there is an entry of your submodule in the config result, then now the usual git submodule update --init should pull your submodule. To test this step, you can manually rename the submodule and then updating the submodule.

 mv yourmodulename yourmodulename-temp
 git submodule update --init

To find out if you have local changes in the submodule, it can be seen via git status -u ( if you want to see changes in the submodule ) or git status --ignore-submodules ( if you dont want to see the changes in the submodule ).

Excel VBA function to print an array to the workbook

As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:

  1. Convert your 1D array into a 2D array first, then print it on sheet (as a Range).
  2. Convert your 1D array into a string and print it in a single cell (as a String).

Here is an example depicting both options:

Sub PrintArrayIn1Cell(myArr As Variant, cell As Range)
    cell = Join(myArr, ",")
End Sub
Sub PrintArrayAsRange(myArr As Variant, cell As Range)
    cell.Resize(UBound(myArr, 1), UBound(myArr, 2)) = myArr
End Sub
Sub TestPrintArrayIntoSheet()  '2dArrayToSheet
    Dim arr As Variant
    arr = Split("a  b  c", "  ")

    'Printing in ONE-CELL: To print all array-elements as a single string separated by comma (a,b,c):
    PrintArrayIn1Cell arr, [A1]

    'Printing in SEPARATE-CELLS: To print array-elements in separate cells:
    Dim arr2D As Variant
    arr2D = Application.WorksheetFunction.Transpose(arr) 'convert a 1D array into 2D array
    PrintArrayAsRange arr2D, Range("B1:B3")
End Sub

Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.

HTH

type checking in javascript

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false

Wpf control size to content?

I had a user control which sat on page in a free form way, not constrained by another container, and the contents within the user control would not auto size but expand to the full size of what the user control was handed.

To get the user control to simply size to its content, for height only, I placed it into a grid with on row set to auto size such as this:

<Grid Margin="0,60,10,200">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <controls1:HelpPanel x:Name="HelpInfoPanel"
                         Visibility="Visible"
                         Width="570"
                         HorizontalAlignment="Right"
                         ItemsSource="{Binding HelpItems}"
                         Background="#FF313131" />
</Grid>

How to pass in a react component into another react component to transclude the first component's content?

Actually, your question is how to write a Higher Order Component (HOC). The main goal of using HOC is preventing copy-pasting. You can write your HOC as a purely functional component or as a class here is an example:

    class Child extends Component {
    render() {
        return (
            <div>
                Child
            </div>
        );
    }
}

If you want to write your parent component as a class-based component:

    class Parent extends Component {
    render() {
        return (
            <div>
                {this.props.children}
            </div>
        );
    }
}

If you want to write your parent as a functional component:

    const Parent=props=>{
    return(
        <div>
            {props.children}
        </div>
    )
}

Correct use for angular-translate in controllers

EDIT: Please see the answer from PascalPrecht (the author of angular-translate) for a better solution.


The asynchronous nature of the loading causes the problem. You see, with {{ pageTitle | translate }}, Angular will watch the expression; when the localization data is loaded, the value of the expression changes and the screen is updated.

So, you can do that yourself:

.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.$watch(
        function() { return $filter('translate')('HELLO_WORLD'); },
        function(newval) { $scope.pageTitle = newval; }
    );
});

However, this will run the watched expression on every digest cycle. This is suboptimal and may or may not cause a visible performance degradation. Anyway it is what Angular does, so it cant be that bad...

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

IE.Document.getElementById("dgTime").getElementsByTagName("a")(0).Click

EDIT: to loop through the collection (items should appear in the same order as they are in the source document)

Dim links, link 

Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")

'For Each loop
For Each link in links
    link.Click
Next link

'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
    links(i).click
Next I

Read user input inside a loop

I have found this parameter -u with read.

"-u 1" means "read from stdin"

while read -r newline; do
    ((i++))
    read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
    echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

Simplest way to have a configuration file in a Windows Forms C# application

What version of .NET and Visual Studio are you using?

When you created the new project, you should have a file in your solution called app.config. That is the default configuration file.

How can I use Ruby to colorize the text output to a terminal?

While the other answers will do the job fine for most people, the "correct" Unix way of doing this should be mentioned. Since all types of text terminals do not support these sequences, you can query the terminfo database, an abstraction over the capabilites of various text terminals. This might seem mostly of historical interest – software terminals in use today generally support the ANSI sequences – but it does have (at least) one practical effect: it is sometimes useful to be able to set the environment variable TERM to dumb to avoid all such styling, for example when saving the output to a text file. Also, it feels good to do things right. :-)

You can use the ruby-terminfo gem. It needs some C compiling to install; I was able to install it under my Ubuntu 14.10 system with:

$ sudo apt-get install libncurses5-dev
$ gem install ruby-terminfo --user-install

Then you can query the database like this (see the terminfo man page for a list of what codes are available):

require 'terminfo' 
TermInfo.control("bold")
puts "Bold text"
TermInfo.control("sgr0")
puts "Back to normal."
puts "And now some " + TermInfo.control_string("setaf", 1) + 
     "red" + TermInfo.control_string("sgr0") + " text."

Here's a little wrapper class I put together to make things a little more simple to use.

require 'terminfo'

class Style
  def self.style() 
    @@singleton ||= Style.new
  end

  colors = %w{black red green yellow blue magenta cyan white}
  colors.each_with_index do |color, index|
    define_method(color) { get("setaf", index) }
    define_method("bg_" + color) { get("setab", index) }
  end

  def bold()  get("bold")  end
  def under() get("smul")  end
  def dim()   get("dim")   end
  def clear() get("sgr0")  end

  def get(*args)
    begin
      TermInfo.control_string(*args)
    rescue TermInfo::TermInfoError
      ""
    end
  end
end

Usage:

c = Style.style
C = c.clear
puts "#{c.red}Warning:#{C} this is #{c.bold}way#{C} #{c.bg_red}too much #{c.cyan + c.under}styling#{C}!"
puts "#{c.dim}(Don't you think?)#{C}"

Output of above Ruby script

(edit) Finally, if you'd rather not require a gem, you can rely on the tput program, as described here – Ruby example:

puts "Hi! " + `tput setaf 1` + "This is red!" + `tput sgr0`

Create Elasticsearch curl query for not null and not empty("")

Elastic search Get all record where condition not empty.

const searchQuery = {
      body: {
        query: {
          query_string: {
            default_field: '*.*',
            query: 'feildName: ?*',
          },
        },
      },
      index: 'IndexName'
    };

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

For LINQ -> SQL:

SingleOrDefault

  • will generate query like "select * from users where userid = 1"
  • Select matching record, Throws exception if more than one records found
  • Use if you are fetching data based on primary/unique key column

FirstOrDefault

  • will generate query like "select top 1 * from users where userid = 1"
  • Select first matching rows
  • Use if you are fetching data based on non primary/unique key column

Visual Studio : short cut Key : Duplicate Line

Here's a macro based on the one in the link posted by Wael, but improved in the following areas:

  • slightly shorter
  • slightly faster
  • comments :)
  • behaves for lines starting with "///"
  • can be undone with a single undo
Imports System
Imports EnvDTE
Imports EnvDTE80

Public Module Module1

    Sub DuplicateLine()
        Dim sel As TextSelection = DTE.ActiveDocument.Selection
        sel.StartOfLine(0) '' move to start
        sel.EndOfLine(True) '' select to end
        Dim line As String = sel.Text
        sel.EndOfLine(False) '' move to end
        sel.Insert(ControlChars.NewLine + line, vsInsertFlags.vsInsertFlagsCollapseToEnd)
    End Sub

End Module

Writing outputs to log file and console

I tried joonty's answer, but I also got the

exec: 1: not found

error. This is what works best for me (confirmed to work in zsh also):

#!/bin/bash
LOG_FILE=/tmp/both.log
exec > >(tee ${LOG_FILE}) 2>&1
echo "this is stdout"
chmmm 77 /makeError

The file /tmp/both.log afterwards contains

this is stdout
chmmm command not found 

The /tmp/both.log is appended unless you remove the -a from tee.

Hint: >(...) is a process substitution. It lets the exec to the tee command as if it were a file.

What method in the String class returns only the first N characters?

The .NET Substring method is fraught with peril. I developed extension methods that handle a wide variety of scenarios. The nice thing is it preserves the original behavior, but when you add an additional "true" parameter, it then resorts to the extension method to handle the exception, and returns the most logical values, based on the index and length. For example, if length is negative, and counts backward. You can look at the test results with wide variety of values on the fiddle at: https://dotnetfiddle.net/m1mSH9. This will give you a clear idea on how it resolves substrings.

I always add these methods to all my projects, and never have to worry about code breaking, because something changed and the index is invalid. Below is the code.

    public static String Substring(this String val, int startIndex, bool handleIndexException)
    {
        if (!handleIndexException)
        { //handleIndexException is false so call the base method
            return val.Substring(startIndex);
        }
        if (string.IsNullOrEmpty(val))
        {
            return val;
        }
        return val.Substring(startIndex < 0 ? 0 : startIndex > (val.Length - 1) ? val.Length : startIndex);
    }

    public static String Substring(this String val, int startIndex, int length, bool handleIndexException)
    {
        if (!handleIndexException)
        { //handleIndexException is false so call the base method
            return val.Substring(startIndex, length);
        }
        if (string.IsNullOrEmpty(val))
        {
            return val;
        }
        int newfrom, newlth, instrlength = val.Length;
        if (length < 0) //length is negative
        {
            newfrom = startIndex + length;
            newlth = -1 * length;
        }
        else //length is positive
        {
            newfrom = startIndex;
            newlth = length;
        }
        if (newfrom + newlth < 0 || newfrom > instrlength - 1)
        {
            return string.Empty;
        }
        if (newfrom < 0)
        {
            newlth = newfrom + newlth;
            newfrom = 0;
        }
        return val.Substring(newfrom, Math.Min(newlth, instrlength - newfrom));
    }

I blogged about this back in May 2010 at: http://jagdale.blogspot.com/2010/05/substring-extension-method-that-does.html

how to hide the content of the div in css

There are many ways to do it:
One way:

#mybox:hover {
   display:none;
}

Another way:

#mybox:hover {
   visibility: hidden;
}

Or you could just do:

#mybox:hover {
   background:transparent;
   color:transparent;
}

Returning a boolean from a Bash function

Use 0 for true and 1 for false.

Sample:

#!/bin/bash

isdirectory() {
  if [ -d "$1" ]
  then
    # 0 = true
    return 0 
  else
    # 1 = false
    return 1
  fi
}


if isdirectory $1; then echo "is directory"; else echo "nopes"; fi

Edit

From @amichair's comment, these are also possible

isdirectory() {
  if [ -d "$1" ]
  then
    true
  else
    false
  fi
}


isdirectory() {
  [ -d "$1" ]
}

How to delete rows in tables that contain foreign keys to other tables

Need to set the foreign key option as on delete cascade... in tables which contains foreign key columns.... It need to set at the time of table creation or add later using ALTER table

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

I had a similar issue with 50,000 rdf/xml files in 5,000 directories (the Project Gutenberg catalog file). I solved it with riot (in the jena distribution)

the directory is cache/epub/NN/nn.rdf (where NN is a number)

in the directory above the directory where all the files are, i.e. in cache

riot epub/*/*.rdf --output=turtle > allTurtle.ttl

This produces possibly many warnings but the result is in a format which can be loaded into jena (using the fuseki web interface).

surprisingly simple (at least in this case).

What does [STAThread] do?

The STAThreadAttribute is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.

MSDN explains the reason in slightly more detail:

STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.

This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).

This application has no explicit mapping for /error

I was facing this issue and then later realized that I was missing the @Configuration annotation in the MvcConfig class which basically does the mapping for ViewControllers and setViewNames.

Here is the content of the file :

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
**@Configuration**
public class MvcConfig implements WebMvcConfigurer{
   public void addViewControllers(ViewControllerRegistry registry)
   {
      registry.addViewController("/").setViewName("login");
      registry.addViewController("/login").setViewName("login");
      registry.addViewController("/dashboard").setViewName("dashboard");
   }
}

Hope this helps somebody!!

How to set the title of UIButton as left alignment?

UIButton *btn;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

In a javascript array, how do I get the last 5 elements, excluding the first element?

You can call:

arr.slice(Math.max(arr.length - 5, 1))

If you don't want to exclude the first element, use

arr.slice(Math.max(arr.length - 5, 0))

handle textview link click in my android app

Just to share an alternative solution using a library I created. With Textoo, this can be achieved like:

TextView locNotFound = Textoo
    .config((TextView) findViewById(R.id.view_location_disabled))
    .addLinksHandler(new LinksHandler() {
        @Override
        public boolean onClick(View view, String url) {
            if ("internal://settings/location".equals(url)) {
                Intent locSettings = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(locSettings);
                return true;
            } else {
                return false;
            }
        }
    })
    .apply();

Or with dynamic HTML source:

String htmlSource = "Links: <a href='http://www.google.com'>Google</a>";
Spanned linksLoggingText = Textoo
    .config(htmlSource)
    .parseHtml()
    .addLinksHandler(new LinksHandler() {
        @Override
        public boolean onClick(View view, String url) {
            Log.i("MyActivity", "Linking to google...");
            return false; // event not handled.  Continue default processing i.e. link to google
        }
    })
    .apply();
textView.setText(linksLoggingText);

Is jQuery $.browser Deprecated?

"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."

From http://api.jquery.com/jQuery.browser/

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

For users with two-factor authentication, you can use bennedich's solution, but you just need to add the X-Github-OTP header for the first command. Replace CODE with the code that you get from the two-factor authentication provider. Replace USER and REPO with the username and name of the repository, as you would in his solution.

curl -u 'USER' -H "X-GitHub-OTP: CODE" -d '{"name":"REPO"}' https://api.github.com/user/repos
git remote add origin [email protected]:USER/REPO.git
git push origin master

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

It fails "when trying to execute the function manually" because you have a different 'this'. This will refer not to the thing you have in mind when invoking the method manually, but something else, probably the window object, or whatever context object you have when invoking manually.

Using HTML data-attribute to set CSS background-image url

For those who want a dumb down answer like me

Something like how to steps as 1, 2, 3

Here it is what I did

First create the HTML markup

<div class="thumb" data-image-src="images/img.jpg"></div>

Then before your ending body tag, add this script

I included the ending body on the code below as an example

So becareful when you copy

<script>
var list = document.getElementsByClassName('thumb');

for (var i = 0; i < list.length; i++) {
  var src = list[i].getAttribute('data-image-src');
  list[i].style.backgroundImage="url('" + src + "')";
}
</script>

</body>

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

Search input with an icon Bootstrap 4

you can also do in this way using input-group

<div class="input-group">
  <input class="form-control"
         placeholder="I can help you to find anything you want!">
  <div class="input-group-addon" ><i class="fa fa-search"></i></div>
</div>

codeply

jquery AJAX and json format

You aren't actually sending JSON. You are passing an object as the data, but you need to stringify the object and pass the string instead.

Your dataType: "json" only tells jQuery that you want it to parse the returned JSON, it does not mean that jQuery will automatically stringify your request data.

Change to:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({
            first_name: $("#namec").val(),
            last_name: $("#surnamec").val(),
            email: $("#emailc").val(),
            mobile: $("#numberc").val(),
            password: $("#passwordc").val()
        }),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
});

Show hidden div on ng-click within ng-repeat

Remove the display:none, and use ng-show instead:

<ul class="procedures">
    <li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
        <h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="showDetails">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Here's the fiddle: http://jsfiddle.net/asmKj/


You can also use ng-class to toggle a class:

<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">

I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/

Simple two column html layout without using tables

a few small changes to make it responsive

<style type="text/css">
#wrap {
    width: 100%;
    margin: 0 auto;
    display: table;
}
#left_col {
   float:left;
   width:50%;
}
#right_col {
   float:right;
   width:50%;
}
@media only screen and (max-width: 480px){
    #left_col {
       width:100%;
    }
    #right_col {
       width:100%;
    }
}
</style>

<div id="wrap">
    <div id="left_col">
        ...
    </div>
    <div id="right_col">
        ...
    </div>
</div>

How can I change all input values to uppercase using Jquery?

$('#id-submit').click(function () {
    $("input").val(function(i,val) {
        return val.toUpperCase();
    });
});

FIDDLE

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

Change image onmouseover

jQuery has .mouseover() and .html(). You can tie the mouseover event to a function:

  1. Hides the current image.
  2. Replaces the current html image with the one you want to toggle.
  3. Shows the div that you hid.

The same thing can be done when you get the mouseover event indicating that the cursor is no longer hanging over the div.

importing jar libraries into android-studio

In the project right click

-> new -> module
-> import jar/AAR package
-> import select the jar file to import
-> click ok -> done

You can follow the screenshots below:

1:

Step 1

2:

enter image description here

3:

enter image description here

You will see this:

enter image description here

Update Item to Revision vs Revert to Revision

To understand how the state of your working copy is different in both scenarios, you must understand the concept of the BASE revision:

BASE

The revision number of an item in a working copy. If the item has been locally modified, this refers to the way the item appears without those local modifications.

Your working copy contains a snapshot of each file (hidden in a .svn folder) in this BASE revision, meaning as it was when last retrieved from the repository. This explains why working copies take 2x the space and how it is possible that you can examine and even revert local modifications without a network connection.

Update item to Revision changes this base revision, making BASE out of date. When you try to commit local modifications, SVN will notice that your BASE does not match the repository HEAD. The commit will be refused until you do an update (and possibly a merge) to fix this.

Revert to revision does not change BASE. It is conceptually almost the same as manually editing the file to match an earlier revision.

Can we convert a byte array into an InputStream in Java?

Use ByteArrayInputStream:

InputStream is = new ByteArrayInputStream(decodedBytes);

Can I load a UIImage from a URL?

Local URL's are super simple, just use this :

UIImage(contentsOfFile: url.path)

How to trim a string after a specific character in java

Use regex:

result = result.replaceAll("\n.*", "");

replaceAll() uses regex to find its target, which I have replaced with "nothing" - effectively deleting the target.

The target I've specified by the regex \n.* means "the newline char and everything after"

Bootstrap 4 navbar color

If you read the bootstrap 4 documentation, Color schemes, it will answer your questions.

Automatically deleting related rows in Laravel (Eloquent ORM)

As of Laravel 5.2, the documentation states that these kinds of event handlers should be registered in the AppServiceProvider:

<?php
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::deleting(function ($user) {
            $user->photos()->delete();
        });
    }

I even suppose to move them to separate classes instead of closures for better application structure.

Can a table have two foreign keys?

create table Table1
(
  id varchar(2),
  name varchar(2),
  PRIMARY KEY (id)
)


Create table Table1_Addr
(
  addid varchar(2),
  Address varchar(2),
  PRIMARY KEY (addid)
)

Create table Table1_sal
(
  salid varchar(2),`enter code here`
  addid varchar(2),
  id varchar(2),
  PRIMARY KEY (salid),
  index(addid),
  index(id),
  FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
  FOREIGN KEY (id) REFERENCES Table1(id)
)

Dead simple example of using Multiprocessing Queue, Pool and Locking

For everyone using editors like Komodo Edit (win10) add sys.stdout.flush() to:

def mp_worker((inputs, the_time)):
    print " Process %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs
    sys.stdout.flush()

or as first line to:

    if __name__ == '__main__':
       sys.stdout.flush()

This helps to see what goes on during the run of the script; in stead of having to look at the black command line box.

In plain English, what does "git reset" do?

Please be aware, this is a simplified explanation intended as a first step in seeking to understand this complex functionality.

May be helpful for visual learners who want to visualise what their project state looks like after each of these commands:


For those who use Terminal with colour turned on (git config --global color.ui auto):

git reset --soft A and you will see B and C's stuff in green (staged and ready to commit)

git reset --mixed A (or git reset A) and you will see B and C's stuff in red (unstaged and ready to be staged (green) and then committed)

git reset --hard A and you will no longer see B and C's changes anywhere (will be as if they never existed)


Or for those who use a GUI program like 'Tower' or 'SourceTree'

git reset --soft A and you will see B and C's stuff in the 'staged files' area ready to commit

git reset --mixed A (or git reset A) and you will see B and C's stuff in the 'unstaged files' area ready to be moved to staged and then committed

git reset --hard A and you will no longer see B and C's changes anywhere (will be as if they never existed)

Do standard windows .ini files allow comments?

I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.

Edit

The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.

How do I iterate over an NSArray?

The results of the test and source code are below (you can set the number of iterations in the app). The time is in milliseconds, and each entry is an average result of running the test 5-10 times. I found that generally it is accurate to 2-3 significant digits and after that it would vary with each run. That gives a margin of error of less than 1%. The test was running on an iPhone 3G as that's the target platform I was interested in.

numberOfItems   NSArray (ms)    C Array (ms)    Ratio
100             0.39            0.0025          156
191             0.61            0.0028          218
3,256           12.5            0.026           481
4,789           16              0.037           432
6,794           21              0.050           420
10,919          36              0.081           444
19,731          64              0.15            427
22,030          75              0.162           463
32,758          109             0.24            454
77,969          258             0.57            453
100,000         390             0.73            534

The classes provided by Cocoa for handling data sets (NSDictionary, NSArray, NSSet etc.) provide a very nice interface for managing information, without having to worry about the bureaucracy of memory management, reallocation etc. Of course this does come at a cost though. I think it's pretty obvious that say using an NSArray of NSNumbers is going to be slower than a C Array of floats for simple iterations, so I decided to do some tests, and the results were pretty shocking! I wasn't expecting it to be this bad. Note: these tests are conducted on an iPhone 3G as that's the target platform I was interested in.

In this test I do a very simple random access performance comparison between a C float* and NSArray of NSNumbers

I create a simple loop to sum up the contents of each array and time them using mach_absolute_time(). The NSMutableArray takes on average 400 times longer!! (not 400 percent, just 400 times longer! thats 40,000% longer!).

Header:

// Array_Speed_TestViewController.h

// Array Speed Test

// Created by Mehmet Akten on 05/02/2009.

// Copyright MSA Visuals Ltd. 2009. All rights reserved.

#import <UIKit/UIKit.h>

@interface Array_Speed_TestViewController : UIViewController {

    int                     numberOfItems;          // number of items in array

    float                   *cArray;                // normal c array

    NSMutableArray          *nsArray;               // ns array

    double                  machTimerMillisMult;    // multiplier to convert mach_absolute_time() to milliseconds



    IBOutlet    UISlider    *sliderCount;

    IBOutlet    UILabel     *labelCount;


    IBOutlet    UILabel     *labelResults;

}


-(IBAction) doNSArray:(id)sender;

-(IBAction) doCArray:(id)sender;

-(IBAction) sliderChanged:(id)sender;


@end

Implementation:

// Array_Speed_TestViewController.m

// Array Speed Test

// Created by Mehmet Akten on 05/02/2009.

// Copyright MSA Visuals Ltd. 2009. All rights reserved.

    #import "Array_Speed_TestViewController.h"
    #include <mach/mach.h>
    #include <mach/mach_time.h>

 @implementation Array_Speed_TestViewController



 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    NSLog(@"viewDidLoad");


    [super viewDidLoad];


    cArray      = NULL;

    nsArray     = NULL;


    // read initial slider value setup accordingly

    [self sliderChanged:sliderCount];


    // get mach timer unit size and calculater millisecond factor

    mach_timebase_info_data_t info;

    mach_timebase_info(&info);

    machTimerMillisMult = (double)info.numer / ((double)info.denom * 1000000.0);

    NSLog(@"machTimerMillisMult = %f", machTimerMillisMult);

}



// pass in results of mach_absolute_time()

// this converts to milliseconds and outputs to the label

-(void)displayResult:(uint64_t)duration {

    double millis = duration * machTimerMillisMult;


    NSLog(@"displayResult: %f milliseconds", millis);


    NSString *str = [[NSString alloc] initWithFormat:@"%f milliseconds", millis];

    [labelResults setText:str];

    [str release];

}




// process using NSArray

-(IBAction) doNSArray:(id)sender {

    NSLog(@"doNSArray: %@", sender);


    uint64_t startTime = mach_absolute_time();

    float total = 0;

    for(int i=0; i<numberOfItems; i++) {

        total += [[nsArray objectAtIndex:i] floatValue];

    }

    [self displayResult:mach_absolute_time() - startTime];

}




// process using C Array

-(IBAction) doCArray:(id)sender {

    NSLog(@"doCArray: %@", sender);


    uint64_t start = mach_absolute_time();

    float total = 0;

    for(int i=0; i<numberOfItems; i++) {

        total += cArray[i];

    }

    [self displayResult:mach_absolute_time() - start];

}



// allocate NSArray and C Array 

-(void) allocateArrays {

    NSLog(@"allocateArrays");


    // allocate c array

    if(cArray) delete cArray;

    cArray = new float[numberOfItems];


    // allocate NSArray

    [nsArray release];

    nsArray = [[NSMutableArray alloc] initWithCapacity:numberOfItems];



    // fill with random values

    for(int i=0; i<numberOfItems; i++) {

        // add number to c array

        cArray[i] = random() * 1.0f/(RAND_MAX+1);


        // add number to NSArray

        NSNumber *number = [[NSNumber alloc] initWithFloat:cArray[i]];

        [nsArray addObject:number];

        [number release];

    }


}



// callback for when slider is changed

-(IBAction) sliderChanged:(id)sender {

    numberOfItems = sliderCount.value;

    NSLog(@"sliderChanged: %@, %i", sender, numberOfItems);


    NSString *str = [[NSString alloc] initWithFormat:@"%i items", numberOfItems];

    [labelCount setText:str];

    [str release];


    [self allocateArrays];

}



//cleanup

- (void)dealloc {

    [nsArray release];

    if(cArray) delete cArray;


    [super dealloc];

}


@end

From : memo.tv

////////////////////

Available since the introduction of blocks, this allows to iterate an array with blocks. Its syntax isn't as nice as fast enumeration, but there is one very interesting feature: concurrent enumeration. If enumeration order is not important and the jobs can be done in parallel without locking, this can provide a considerable speedup on a multi-core system. More about that in the concurrent enumeration section.

[myArray enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
    [self doSomethingWith:object];
}];
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [self doSomethingWith:object];
}];

/////////// NSFastEnumerator

The idea behind fast enumeration is to use fast C array access to optimize iteration. Not only is it supposed to be faster than traditional NSEnumerator, but Objective-C 2.0 also provides a very concise syntax.

id object;
for (object in myArray) {
    [self doSomethingWith:object];
}

/////////////////

NSEnumerator

This is a form of external iteration: [myArray objectEnumerator] returns an object. This object has a method nextObject that we can call in a loop until it returns nil

NSEnumerator *enumerator = [myArray objectEnumerator];
id object;
while (object = [enumerator nextObject]) {
    [self doSomethingWith:object];
}

/////////////////

objectAtIndex: enumeration

Using a for loop which increases an integer and querying the object using [myArray objectAtIndex:index] is the most basic form of enumeration.

NSUInteger count = [myArray count];
for (NSUInteger index = 0; index < count ; index++) {
    [self doSomethingWith:[myArray objectAtIndex:index]];
}

////////////// From : darkdust.net

Increase max execution time for php

Add these lines of code in your htaccess file. I hope it will solve your problem.

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

Dynamically Add Variable Name Value Pairs to JSON Object

if my understanding of your initial JSON is correct, either of these solutions might help you loop through all ip ids & assign each one, a new object.

// initial JSON
var ips = {ipId1: {}, ipId2: {}};

// Solution1
Object.keys(ips).forEach(function(key) {
  ips[key] = {name: 'value', anotherName: 'another value'};
});

// Solution 2
Object.keys(ips).forEach(function(key) {
  Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});

To confirm:

console.log(JSON.stringify(ips, null, 2));

The above statement spits:

{
  "ipId1": {
    "name":"value",
    "anotherName":"another value"
  },
  "ipId2": {
    "name":"value",
    "anotherName":"another value"
  }
}

JS. How to replace html element with another element/text, represented in string?

idTABLE.parentElement.innerHTML =  '<span>123 element</span> 456';

while this works, it's still recommended to use getElementById: Do DOM tree elements with ids become global variables?

replaceChild would work fine if you want to go to the trouble of building up your replacement, element by element, using document.createElement and appendChild, but I don't see the point.

How to export collection to CSV in MongoDB?

@karoly-horvath has it right. Fields are required for csv.

According to this bug in the MongoDB issue tracker https://jira.mongodb.org/browse/SERVER-4224 you MUST provide the fields when exporting to a csv. The docs are not clear on it. That is the reason for the error.

Try this:

mongoexport --host localhost --db dbname --collection name --csv --out text.csv --fields firstName,middleName,lastName

UPDATE:

This commit: https://github.com/mongodb/mongo-tools/commit/586c00ef09c32c77907bd20d722049ed23065398 fixes the docs for 3.0.0-rc10 and later. It changes

Fields string `long:"fields" short:"f" description:"comma separated list of field names, e.g. -f name,age"`

to

Fields string `long:"fields" short:"f" description:"comma separated list of field names (required for exporting CSV) e.g. -f \"name,age\" "`

VERSION 3.0 AND ABOVE:

You should use --type=csv instead of --csv since it has been deprecated.

More details: https://docs.mongodb.com/manual/reference/program/mongoexport/#export-in-csv-format

Full command:

mongoexport --host localhost --db dbname --collection name --type=csv --out text.csv --fields firstName,middleName,lastName

Javascript Confirm popup Yes, No button instead of OK and Cancel

You can also use http://projectshadowlight.org/jquery-easy-confirm-dialog/ . It's very simple and easy to use. Just include jquery common library and one more file only:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/blitzer/jquery-ui.css" type="text/css" />
<script src="jquery.easy-confirm-dialog.js"></script>

Change Circle color of radio button

The question is old but i think my answer will help people. You can change the color of radio button's unchecked and checked state by using style in xml.

<RadioButton
    android:id="@+id/rb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/RadioButtonStyle" />

In style.xml

<style name="RadioButtonStyle" parent="Theme.AppCompat.Light">
        <item name="colorAccent">@android:color/white</item>
        <item name="android:textColorSecondary">@android:color/white</item>
</style>

You can set the desired colors in this style.

JavaScript/jQuery - "$ is not defined- $function()" error

You must not have made jQuery available to your script.

Add this to the top of your file:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

This issue is related to the jQuery/JavaScript file not added to the PHP/JSP/ASP file properly. This goes out and gets the jQuery code from the source. You could download that and reference it locally on the server which would be faster.

Or either one can directly link it to jQuery or GoogleCDN or MicrosoftCDN.

How do add jQuery to your webpage

How to clear browser cache with php?

You can delete the browser cache by setting these headers:

<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

mkdir's "-p" option

PATH: Answered long ago, however, it maybe more helpful to think of -p as "Path" (easier to remember), as in this causes mkdir to create every part of the path that isn't already there.

mkdir -p /usr/bin/comm/diff/er/fence

if /usr/bin/comm already exists, it acts like: mkdir /usr/bin/comm/diff mkdir /usr/bin/comm/diff/er mkdir /usr/bin/comm/diff/er/fence

As you can see, it saves you a bit of typing, and thinking, since you don't have to figure out what's already there and what isn't.

Set Canvas size using javascript

You can set the width like this :

function draw() {
  var ctx = (a canvas context);
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  //...drawing code...
}

I can’t find the Android keytool

If you're using Android Studio for Windows to create a release keystore and signed .apk, just follow these steps:

1) Build > Generate Signed APK

2) Choose "Create New...", choose the path to the keystore, and enter all the required data

3) After your keystore (your_keystore_name.jks) has been created, you will then use it to create your first signed apk at a destination of your choosing

I haven't seen a need to use the command tool if you have an IDE like Android Studio.

Get a list of all functions and procedures in an Oracle database

SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')

The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.

Express: How to pass app-instance to routes from a different file?

Like I said in the comments, you can use a function as module.exports. A function is also an object, so you don't have to change your syntax.

app.js

var controllers = require('./controllers')({app: app});

controllers.js

module.exports = function(params)
{
    return require('controllers/index')(params);
}

controllers/index.js

function controllers(params)
{
  var app = params.app;

  controllers.posts = require('./posts');

  controllers.index = function(req, res) {
    // code
  };
}

module.exports = controllers;

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

I guess that your git remote url has been set as SSH. You can set it as HTTPS:

git remote set-url origin https://github.com/YOUR_USERNAME/YOUR_REPOSITORY.git

Retry this command and there is prompt to enter username and password:

git pull

What is the difference between dynamic and static polymorphism in Java?

Polymorphism refers to the ability of an object to behave differently for the same trigger.

Static polymorphism (Compile-time Polymorphism)

  • Static Polymorphism decides which method to execute during compile time.
  • Method Overloading is an example of static polymorphism, and it is requred to happens static polymorphism.
  • Static Polymorphism achieved through static binding.
  • Static Polymorphism happens in the same class.
  • Object assignment is not required for static polymorphism.
  • Inheritance not involved for static polymorphism.

Dynamic Polymorphism (Runtime Polymorphism)

  • Dynamic Polymorphism decides which method to execute in runtime.
  • Method Overriding is an example of dynamic polymorphism, and it is requred to happens dynamic polymorphism.
  • Dynamic Polymorphism achieved through dynamic binding.
  • Dynamic Polymorphism happens between different classes.
  • It is required where a subclass object is assigned to super class object for dynamic polymorphism.
  • Inheritance involved for dynamic polymorphism.

How to handle back button in activity

This is a simple way of doing something.

    @Override
        public void onBackPressed() {
            // do what you want to do when the "back" button is pressed.
            startActivity(new Intent(Activity.this, MainActivity.class));
            finish();
        }

I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.

Hexadecimal to Integer in Java

you can use this method : https://stackoverflow.com/a/31804061/3343174 it's converting perfectly any hexadecimal number (presented as a string) to a decimal number

How do I allow HTTPS for Apache on localhost?

here is simplest way to do this

first copy these server.crt & server.key files (find in attachment ) into your apache/conf/ssl directory

then open httpd.conf file & add following line

Listen 80
Listen 443

NameVirtualHost *:80
NameVirtualHost *:443

<VirtualHost *:443>
    DocumentRoot "d:/wamp/www"  #your wamp www root dir
    ServerName localhost
    SSLEngine on
    SSLCertificateFile "d:/wamp/bin/apache/Apache2.4.4/conf/ssl/server.crt"
    SSLCertificateKeyFile "d:/wamp/bin/apache/Apache2.4.4/conf/ssl/server.key"
</VirtualHost>

What is the difference between mocking and spying when using Mockito?

If there is an object with 8 methods and you have a test where you want to call 7 real methods and stub one method you have two options:

  1. Using a mock you would have to set it up by invoking 7 callRealMethod and stub one method
  2. Using a spy you have to set it up by stubbing one method

The official documentation on doCallRealMethod recommends using a spy for partial mocks.

See also javadoc spy(Object) to find out more about partial mocks. Mockito.spy() is a recommended way of creating partial mocks. The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.

The application was unable to start correctly (0xc000007b)

Just solved this problem for my personal project (thanks to Dries for that). For me it was because the project path was too long. After saving the .sln to a shorter path (C:/MyProjects) and compiling from there it ran without the error.

Importing packages in Java

For the second class file, add "package Dan;" like the first one, so as to make sure they are in the same package; modify "import Dan.Vik.disp;" to be "import Dan.Vik;"

MultipartException: Current request is not a multipart request

i was facing the same issue with misspelled enctype="multipart/form-data", i was fix this exception by doing correct spelling . Current request is not a multipart request client side error so please check your form.

JavaScript: How to find out if the user browser is Chrome?

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

Count textarea characters

_x000D_
_x000D_
var maxchar = 10;_x000D_
$('#message').after('<span id="count" class="counter"></span>');_x000D_
$('#count').html(maxchar+' of '+maxchar);_x000D_
$('#message').attr('maxlength', maxchar);_x000D_
$('#message').parent().addClass('wrap-text');_x000D_
$('#message').on("keydown", function(e){_x000D_
 var len =  $('#message').val().length;_x000D_
 if (len >= maxchar && e.keyCode != 8)_x000D_
     e.preventDefault();_x000D_
 else if(len <= maxchar && e.keyCode == 8){_x000D_
  if(len <= maxchar && len != 0)_x000D_
      $('#count').html(maxchar+' of '+(maxchar - len +1));_x000D_
     else if(len == 0)_x000D_
      $('#count').html(maxchar+' of '+(maxchar - len));_x000D_
 }else_x000D_
   $('#count').html(maxchar+' of '+(maxchar - len-1)); _x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="message" name="text"></textarea>
_x000D_
_x000D_
_x000D_

File path for project files?

I was facing a similar issue, I had a file on my project, and wanted to test a class which had to deal with loading files from the FS and process them some way. What I did was:

  • added the file test.txt to my test project
  • on the solution explorer hit alt-enter (file properties)
  • there I set BuildAction to Content and Copy to Output Directory to Copy if newer, I guess Copy always would have done it as well

then on my tests I just had to Path.Combine(Environment.CurrentDirectory, "test.txt") and that's it. Whenever the project is compiled it will copy the file (and all it's parent path, in case it was in, say, a folder) to the bin\Debug (or whatever configuration you are using) folder.

Hopes this helps someone

JavaScript: replace last occurrence of text in a string

You can use String#lastIndexOf to find the last occurrence of the word, and then String#substring and concatenation to build the replacement string.

n = str.lastIndexOf(list[i]);
if (n >= 0 && n + list[i].length >= str.length) {
    str = str.substring(0, n) + "finish";
}

...or along those lines.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Its already answered above. I will summarise the steps to check above.

run git remote -v in project dir. If the output shows remote url starting with https://abc then you may need username password everytime.

So to change the remote url run git remote set-url origin {ssh remote url address starts with mostly [email protected]:}.

Now run git remote -v to verify the changed remote url.

Refer : https://help.github.com/articles/changing-a-remote-s-url/

Install / upgrade gradle on Mac OS X

I had downloaded it from http://gradle.org/gradle-download/. I use Homebrew, but I missed installing gradle using it.

To save some MBs by downloading it over again using Homebrew, I symlinked the gradle binary from the downloaded (and extracted) zip archive in the /usr/local/bin/. This is the same place where Homebrew symlinks all other binaries.

cd /usr/local/bin/
ln -s ~/Downloads/gradle-2.12/bin/gradle

Now check whether it works or not:

gradle -v

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

disable a hyperlink using jQuery

$('.my-link').click(function(e) { e.preventDefault(); }); 

You could use:

$('.my-link').click(function(e) { return false; }); 

But I don't like to use this myself as it is more cryptic, even though it is used extensively throughout much jQuery code.

What does %~dp0 mean, and how does it work?

Great example from Strawberry Perl's portable shell launcher:

set drive=%~dp0
set drivep=%drive%
if #%drive:~-1%# == #\# set drivep=%drive:~0,-1%

set PATH=%drivep%\perl\site\bin;%drivep%\perl\bin;%drivep%\c\bin;%PATH%

not sure what the negative 1's doing there myself, but it works a treat!

Map a 2D array onto a 1D array

using row major example:

A(i,j) = a[i + j*ld]; // where ld is the leading dimension
                      // (commonly same as array dimension in i)

// matrix like notation using preprocessor hack, allows to hide indexing
#define A(i,j) A[(i) + (j)*ld]

double *A = ...;
size_t ld = ...;
A(i,j) = ...;
... = A(j,i);

JQuery create new select option

How about

$('#county').append(
    $('<option />')
        .text('Select a city / town in Sweden')
        .val(''),
    $('<option />')
        .text('Melbourne')
        .val('Melbourne')
);

Java File - Open A File And Write To It

To expand upon Mr. Eels comment, you can do it like this:

    File file = new File("C:\\A.txt");
    FileWriter writer;
    try {
        writer = new FileWriter(file, true);
        PrintWriter printer = new PrintWriter(writer);
        printer.append("Sue");
        printer.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Don't say we ain't good to ya!

Simple way to transpose columns and rows in SQL?

Based on this solution from bluefeet here is a stored procedure that uses dynamic sql to generate the transposed table. It requires that all the fields are numeric except for the transposed column (the column that will be the header in the resulting table):

/****** Object:  StoredProcedure [dbo].[SQLTranspose]    Script Date: 11/10/2015 7:08:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Paco Zarate
-- Create date: 2015-11-10
-- Description: SQLTranspose dynamically changes a table to show rows as headers. It needs that all the values are numeric except for the field using for     transposing.
-- Parameters: @TableName - Table to transpose
--             @FieldNameTranspose - Column that will be the new headers
-- Usage: exec SQLTranspose <table>, <FieldToTranspose>
-- =============================================
ALTER PROCEDURE [dbo].[SQLTranspose] 
  -- Add the parameters for the stored procedure here
  @TableName NVarchar(MAX) = '', 
  @FieldNameTranspose NVarchar(MAX) = ''
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  DECLARE @colsUnpivot AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX),
  @queryPivot  AS NVARCHAR(MAX),
  @colsPivot as  NVARCHAR(MAX),
  @columnToPivot as NVARCHAR(MAX),
  @tableToPivot as NVARCHAR(MAX), 
  @colsResult as xml

  select @tableToPivot = @TableName;
  select @columnToPivot = @FieldNameTranspose


  select @colsUnpivot = stuff((select ','+quotename(C.name)
       from sys.columns as C
       where C.object_id = object_id(@tableToPivot) and
             C.name <> @columnToPivot 
       for xml path('')), 1, 1, '')

  set @queryPivot = 'SELECT @colsResult = (SELECT  '','' 
                    + quotename('+@columnToPivot+')
                  from '+@tableToPivot+' t
                  where '+@columnToPivot+' <> ''''
          FOR XML PATH(''''), TYPE)'

  exec sp_executesql @queryPivot, N'@colsResult xml out', @colsResult out

  select @colsPivot = STUFF(@colsResult.value('.', 'NVARCHAR(MAX)'),1,1,'')

  set @query 
    = 'select name, rowid, '+@colsPivot+'
        from
        (
          select '+@columnToPivot+' , name, value, ROW_NUMBER() over (partition by '+@columnToPivot+' order by '+@columnToPivot+') as rowid
          from '+@tableToPivot+'
          unpivot
          (
            value for name in ('+@colsUnpivot+')
          ) unpiv
        ) src
        pivot
        (
          sum(value)
          for '+@columnToPivot+' in ('+@colsPivot+')
        ) piv
        order by rowid'
  exec(@query)
END

You can test it with the table provided with this command:

exec SQLTranspose 'yourTable', 'color'

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

Convert char array to a int number in C

It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.

char *buff;
size_t buff_size = 100;
int choice;
do{
    buff = (char *)malloc(buff_size *sizeof(char));
    getline(&buff, &buff_size, stdin);
    choice = atoi(buff);
    free(buff);
                    
}while((choice<1)&&(choice>9));

Excel is not updating cells, options > formula > workbook calculation set to automatic

In short

creating or moving some/all reference containing worksheets (out and) into your workbook may solve it.

More details

I had this issue after copying some sheets from "template" sheets/workbooks to some new "destination" workbook (the templates were provided by other users!):

I got:

  • workbook WbTempl1
    • with sheet WsTempl1RefDef (defining the references used e.g. in WsTempl2RefUsr below, e.g. project on A1)
  • workbook WbTempl2 (above references do not exist, because WsTempl1RefDef is not contained nor externally referenced, e.g. like WbTempl2.Names("project").refersTo="C:\WbTempl1.xls]'WsTempl1RefDef!A1")
    • contains sheet WsTempl2RefUsr (uses inexisting global references, e.g. =project)

and wanted to create a WbDst to copy WsTempl1RefDef and WsTempl2RefUsr into it.


The following did not work:

  1. create workbook WbDst
  2. copy sheet WsTempl1RefDef into it (references were locally created)
  3. copy sheet WsTempl2RefUsr into it

Here as well the Ctrl(SHIFT)ALTF9 nor Application.CalculateFullRebuild worked on WbDst.


The following worked:

  1. create workbook WbDst
  2. move (not copy) sheet WsTempl1RefDef into WbTempl2
    • (we do not have to save them)
  3. copy sheet WsTempl1RefDef into WbDst
  4. copy sheet WsTempl2RefUsr into WbDst

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

SQL Server - In clause with a declared variable

First, create a quick function that will split a delimited list of values into a table, like this:

CREATE FUNCTION dbo.udf_SplitVariable
(
    @List varchar(8000),
    @SplitOn varchar(5) = ','
)

RETURNS @RtnValue TABLE
(
    Id INT IDENTITY(1,1),
    Value VARCHAR(8000)
)

AS
BEGIN

--Account for ticks
SET @List = (REPLACE(@List, '''', ''))

--Account for 'emptynull'
IF LTRIM(RTRIM(@List)) = 'emptynull'
BEGIN
    SET @List = ''
END

--Loop through all of the items in the string and add records for each item
WHILE (CHARINDEX(@SplitOn,@List)>0)
BEGIN

    INSERT INTO @RtnValue (value)
    SELECT Value = LTRIM(RTRIM(SUBSTRING(@List, 1, CHARINDEX(@SplitOn, @List)-1)))  

    SET @List = SUBSTRING(@List, CHARINDEX(@SplitOn,@List) + LEN(@SplitOn), LEN(@List))

END

INSERT INTO @RtnValue (Value)
SELECT Value = LTRIM(RTRIM(@List))

RETURN

END 

Then call the function like this...

SELECT * 
FROM A
LEFT OUTER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value
WHERE f.Id IS NULL

This has worked really well on our project...

Of course, the opposite could also be done, if that was the case (though not your question).

SELECT * 
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value

And this really comes in handy when dealing with reports that have an optional multi-select parameter list. If the parameter is NULL you want all values selected, but if it has one or more values you want the report data filtered on those values. Then use SQL like this:

SELECT * 
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value OR @ExcludeList IS NULL

This way, if @ExcludeList is a NULL value, the OR clause in the join becomes a switch that turns off filtering on this value. Very handy...

How to load all modules in a folder?

When from . import * isn't good enough, this is an improvement over the answer by ted. Specifically, the use of __all__ is not necessary with this approach.

"""Import all modules that exist in the current directory."""
# Ref https://stackoverflow.com/a/60861023/
from importlib import import_module
from pathlib import Path

for f in Path(__file__).parent.glob("*.py"):
    module_name = f.stem
    if (not module_name.startswith("_")) and (module_name not in globals()):
        import_module(f".{module_name}", __package__)
    del f, module_name
del import_module, Path

Note that module_name not in globals() is intended to avoid reimporting the module if it's already imported, as this can risk cyclic imports.

Returning multiple objects in an R function

You could use for() with assign() to create many objects. See the example from assign():

for(i in 1:6) { #-- Create objects  'r.1', 'r.2', ... 'r.6' --
    nam <- paste("r", i, sep = ".")
    assign(nam, 1:i)

Looking the new objects

ls(pattern = "^r..$")

Getting time and date from timestamp with php

Works for me:

select DATE( FROM_UNIXTIME( columnname ) ) from tablename;

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

I was getting the same error when I used this code to update the record:

@mysqli_query($dbc,$query or die()))

After removing or die, it started working properly.

How to create module-wide variables in Python?

Steveha's answer was helpful to me, but omits an important point (one that I think wisty was getting at). The global keyword is not necessary if you only access but do not assign the variable in the function.

If you assign the variable without the global keyword then Python creates a new local var -- the module variable's value will now be hidden inside the function. Use the global keyword to assign the module var inside a function.

Pylint 1.3.1 under Python 2.7 enforces NOT using global if you don't assign the var.

module_var = '/dev/hello'

def readonly_access():
    connect(module_var)

def readwrite_access():
    global module_var
    module_var = '/dev/hello2'
    connect(module_var)

.NET HttpClient. How to POST string value?

Below is example to call synchronously but you can easily change to async by using await-sync:

var pairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("login", "abc")
            };

var content = new FormUrlEncodedContent(pairs);

var client = new HttpClient {BaseAddress = new Uri("http://localhost:6740")};

    // call sync
var response = client.PostAsync("/api/membership/exist", content).Result; 
if (response.IsSuccessStatusCode)
{
}

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

What does the exclamation mark do before the function?

Exclamation mark makes any function always return a boolean.
The final value is the negation of the value returned by the function.

!function bool() { return false; }() // true
!function bool() { return true; }() // false

Omitting ! in the above examples would be a SyntaxError.

function bool() { return true; }() // SyntaxError

However, a better way to achieve this would be:

(function bool() { return true; })() // true

Configuring Hibernate logging using Log4j XML config file?

You can configure your log4j file with the category tag like this (with a console appender for the example):

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yy-MM-dd HH:mm:ss} %p %c - %m%n" />
    </layout>
</appender>
<category name="org.hibernate">
    <priority value="WARN" />
</category>
<root>
    <priority value="INFO" />
    <appender-ref ref="console" />
</root>

So every warning, error or fatal message from hibernate will be displayed, nothing more. Also, your code and library code will be in info level (so info, warn, error and fatal)

To change log level of a library, just add a category, for example, to desactive spring info log:

<category name="org.springframework">
    <priority value="WARN" />
</category>

Or with another appender, break the additivity (additivity default value is true)

<category name="org.springframework" additivity="false">
    <priority value="WARN" />
    <appender-ref ref="anotherAppender" />
</category>

And if you don't want that hibernate log every query, set the hibernate property show_sql to false.

How do you get the currently selected <option> in a <select> via JavaScript?

This will do it for you:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

Mockito: Trying to spy on method is calling the original method

I've found yet another reason for spy to call the original method.

Someone had the idea to mock a final class, and found about MockMaker:

As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line: mock-maker-inline

Source: https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#mock-the-unmockable-opt-in-mocking-of-final-classesmethods

After I merged and brought that file to my machine, my tests failed.

I just had to remove the line (or the file), and spy() worked.

What issues should be considered when overriding equals and hashCode in Java?

Logically we have:

a.getClass().equals(b.getClass()) && a.equals(b) ? a.hashCode() == b.hashCode()

But not vice-versa!

MySQL, Concatenate two columns

You can use the CONCAT function like this:

SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`

Update:

To get that result you can try this:

SET @rn := 0;

SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(@rn := @rn+1,3,'0'))
FROM `table`

Adding and reading from a Config file

  1. Right click on the project file -> Add -> New Item -> Application Configuration File. This will add an app.config (or web.config) file to your project.

  2. The ConfigurationManager class would be a good start. You can use it to read different configuration values from the configuration file.

I suggest you start reading the MSDN document about Configuration Files.

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

convert strtotime to date time format in php

FORMAT DATE STRTOTIME OR TIME STRING TO DATE FORMAT
$unixtime = 1307595105;
function formatdate($unixtime) 
{ 
        return $time = date("m/d/Y h:i:s",$unixtime);
} 

Pass Javascript variable to PHP via ajax

Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):

data: { userID : userID }

And in your PHP do this:

if(isset($_POST['userID']))
{
    $uid = $_POST['userID'];

    // Do whatever you want with the $uid
}

isset() function's purpose is to check wheter the given variable exists, not to get its value.

How to use a TRIM function in SQL Server

TRIM all SPACE's TAB's and ENTER's:

DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
          '

DECLARE @NewStr VARCHAR(MAX) = ''
DECLARE @WhiteChars VARCHAR(4) =
      CHAR(13) + CHAR(10) -- ENTER
    + CHAR(9) -- TAB
    + ' ' -- SPACE

;WITH Split(Chr, Pos) AS (
    SELECT
          SUBSTRING(@Str, 1, 1) AS Chr
        , 1 AS Pos
    UNION ALL
    SELECT
          SUBSTRING(@Str, Pos, 1) AS Chr
        , Pos + 1 AS Pos
    FROM Split
    WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
    Pos >= (
        SELECT MIN(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )
    AND Pos <= (
        SELECT MAX(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )

SELECT '"' + @NewStr + '"'

As Function

CREATE FUNCTION StrTrim(@Str VARCHAR(MAX)) RETURNS VARCHAR(MAX) BEGIN
    DECLARE @NewStr VARCHAR(MAX) = NULL

    IF (@Str IS NOT NULL) BEGIN
        SET @NewStr = ''

        DECLARE @WhiteChars VARCHAR(4) =
              CHAR(13) + CHAR(10) -- ENTER
            + CHAR(9) -- TAB
            + ' ' -- SPACE

        IF (@Str LIKE ('%[' + @WhiteChars + ']%')) BEGIN

            ;WITH Split(Chr, Pos) AS (
                SELECT
                      SUBSTRING(@Str, 1, 1) AS Chr
                    , 1 AS Pos
                UNION ALL
                SELECT
                      SUBSTRING(@Str, Pos, 1) AS Chr
                    , Pos + 1 AS Pos
                FROM Split
                WHERE Pos <= LEN(@Str)
            )
            SELECT @NewStr = @NewStr + Chr
            FROM Split
            WHERE
                Pos >= (
                    SELECT MIN(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
                AND Pos <= (
                    SELECT MAX(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
        END
    END

    RETURN @NewStr
END

Example

-- Test
DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
              '

SELECT 'Str', '"' + dbo.StrTrim(@Str) + '"'
UNION SELECT 'EMPTY', '"' + dbo.StrTrim('') + '"'
UNION SELECT 'EMTPY', '"' + dbo.StrTrim('      ') + '"'
UNION SELECT 'NULL', '"' + dbo.StrTrim(NULL) + '"'

Result

+-------+----------------+
| Test  | Result         |
+-------+----------------+
| EMPTY | ""             |
| EMTPY | ""             |
| NULL  | NULL           |
| Str   | "[   Foo    ]" |
+-------+----------------+

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

Font-awesome, input type 'submit'

use button type="submit" instead of input

<button type="submit" class="btn btn-success">
    <i class="fa fa-arrow-circle-right fa-lg"></i> Next
</button>

for Font Awesome 3.2.0 use

<button type="submit" class="btn btn-success">
    <i class="icon-circle-arrow-right icon-large"></i> Next
</button>

import sun.misc.BASE64Encoder results in error compiled in Eclipse

Go to Window-->Preferences-->Java-->Compiler-->Error/Warnings.
Select Deprecated and Restricted API. Change it to warning.
Change forbidden and Discouraged Reference and change it to warning. (or as your need.)

Passing parameters to click() & bind() event in jquery?

An alternative for the bind() method.

Use the click() method, do something like this:

commentbtn.click({id: 10, name: "João"}, onClickCommentBtn);

function onClickCommentBtn(event)
{
  alert("Id=" + event.data.id + ", Name = " + event.data.name);
}

Or, if you prefer:

commentbtn.click({id: 10, name: "João"},  function (event) {
  alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});

It will show an alert box with the following infos:

Id = 10, Name = João

An unhandled exception was generated during the execution of the current web request

In my case, I created a new project and when I ran it the first time, it gave me the following error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package

Problem solved!!

How to fix System.NullReferenceException: Object reference not set to an instance of an object

If the problem is 100% here

EffectSelectorForm effectSelectorForm = new EffectSelectorForm(Effects);

There's only one possible explanation: property/variable "Effects" is not initialized properly... Debug your code to see what you pass to your objects.

EDIT after several hours

There were some problems:

  • MEF attribute [Import] didn't work as expected, so we replaced it for the time being with a manually populated List<>. While the collection was null, it was causing exceptions later in the code, when the method tried to get the type of the selected item and there was none.

  • several event handlers weren't wired up to control events

Some problems are still present, but I believe OP's original problem has been fixed. Other problems are not related to this one.

docker cannot start on windows

If none of the other answers work for you, try this: Open up a terminal and run:

wsl -l -v 

If you notice that there's a docker-desktop left hanging in the 'Installing' state, close Docker, run powershell as adminstrator and unregister docker-desktop:

PS C:\WINDOWS\system32> .\wslconfig.exe /u docker-desktop

Restart docker and hopefully it works. If it doesn't, try uninstalling docker first, then unregistering docker-desktop, and re-installing Docker.

Source: https://github.com/docker/for-win/issues/7295#issuecomment-645989416

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

Remove scrollbar from iframe

If anyone here is having a problem with disabling scrollbars on the iframe, it could be because the iframe's content has scrollbars on elements below the html element!

Some layouts set html and body to 100% height, and use a #wrapper div with overflow: auto; (or scroll), thereby moving the scrolling to the #wrapper element.

In such a case, nothing you do will prevent the scrollbars from showing up except editing the other page's content.

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

The following will do.

string datestring = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

How to pass variable number of arguments to printf/sprintf

I should have read more on existing questions in stack overflow.

C++ Passing Variable Number of Arguments is a similar question. Mike F has the following explanation:

There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.

The generally used solution is to always provide an alternate form of vararg functions, so printf has vprintf which takes a va_list in place of the .... The ... versions are just wrappers around the va_list versions.

This is exactly what I was looking for. I performed a test implementation like this:

void Error(const char* format, ...)
{
    char dest[1024 * 16];
    va_list argptr;
    va_start(argptr, format);
    vsprintf(dest, format, argptr);
    va_end(argptr);
    printf(dest);
}

How to clear radio button in Javascript?

If you have a radio button with same id, then you can clear the selection

Radio Button definition :

<input type="radio" name="paymentType" id="paymentType" value="CASH" /> CASH
<input type="radio" name="paymentType" id="paymentType" value="CHEQUE" /> CHEQUE
<input type="radio" name="paymentType" id="paymentType" value="DD" /> DD

Clearing all values of radio button:

document.formName.paymentType[0].checked = false;
document.formName.paymentType[1].checked = false;
document.formName.paymentType[2].checked = false;
...

Change location of log4j.properties

Yes, define log4j.configuration property

java -Dlog4j.configuration=file:/path/to/log4j.properties myApp

Note, that property value must be a URL.

For more read section 'Default Initialization Procedure' in Log4j manual.

How to run multiple Python versions on Windows

Using a batch file to switch, easy and efficient on windows 7. I use this:

In the environment variable dialog (C:\Windows\System32\SystemPropertiesAdvanced.exe),

In the section user variables

  1. added %pathpython% to the path environment variable

  2. removed any references to python pathes

In the section system variables

  1. removed any references to python pathes

I created batch files for every python installation (exmple for 3.4 x64

Name = SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-) just to remember.

Content of the file =

     Set PathPython=C:\Python36AMD64\Scripts\;C:\Python36AMD64\;C:\Tcl\bin

     setx PathPython %PathPython%

To switch between versions, I execute the batch file in admin mode.

!!!!! The changes are effective for the SUBSEQUENT command prompt windows OPENED. !!!

So I have exact control on it.

How do I use JDK 7 on Mac OSX?

As of April 27th there is an offical Oracle release of Java SE 7u4. Download the disk image and run the installer - then see the Mac readme.

ORA-01882: timezone region not found

If this problem is in JDeveloper: Change the project properties for both the model and the view project -> run/debug -> default profile -> edit add the following run option: -Duser.timezone=Asia/Calcutta

Make sure that the above time zone value is fetched from your database as follows:

select TZNAME from V$TIMEZONE_NAMES;

Along with that you'd want to check the time zone settings in your jdev.conf as well as in the JDeveloper -> Application Menu -> Default Project Propertes -> Run/Debug -> Default Profile -> Run Options.

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

In my case I did deploy my tomcat folder (the one having all files in it) into an other place.

Then when I started eclipse and tried to run my project with jsp's and servlets I got this same error.

I tried all the answers here but it still didn't change anything. The solution for me was to put all tomcat JAR files into the project librarie like so:

  1. Go to Eclipse
  2. Right click on the project you work on > Build Path > Configure Build Path... > Libraries > Add External JARs
  3. select all JAR files from the Tomcat/bin and Tomcat/lib
  4. Press "Ok"

Now you should find them in the Libraries folder of your project and then it should work.

How to comment multiple lines with space or indent

One way to do it would be:

  1. Select the text, Press CTRL + K, C to comment (CTRL+E+C )
  2. Move the cursor to the first line after the delimiter // and before the Code text.
  3. Press Alt + Shift and use arrow keys to make selection. (Remember to make line selection(using down, up arrow keys), not the text selection - See Box Selection and Multi line editing)
  4. Once the selection is done, press space bar to enter a single space.

Notice the vertical blue line in the below image( that will appear once the selection is made, then you can insert any number of characters in between them)

enter image description here

I couldn't find a direct way to do that. The interesting thing is that it is mentioned in the C# Coding Conventions (C# Programming Guide) under Commenting Conventions.

Insert one space between the comment delimiter (//) and the comment text

But the default implementation of commenting in visual studio doesn't insert any space

Why does the C++ STL not provide any "tree" containers?

There are two reasons you could want to use a tree:

You want to mirror the problem using a tree-like structure:
For this we have boost graph library

Or you want a container that has tree like access characteristics For this we have

Basically the characteristics of these two containers is such that they practically have to be implemented using trees (though this is not actually a requirement).

See also this question: C tree Implementation

How to append to a file in Node?

I offer this suggestion only because control over open flags is sometimes useful, for example, you may want to truncate it an existing file first and then append a series of writes to it - in which case use the 'w' flag when opening the file and don't close it until all the writes are done. Of course appendFile may be what you're after :-)

  fs.open('log.txt', 'a', function(err, log) {
    if (err) throw err;
    fs.writeFile(log, 'Hello Node', function (err) {
      if (err) throw err;
      fs.close(log, function(err) {
        if (err) throw err;
        console.log('It\'s saved!');
      });
    });
  });

no module named urllib.parse (How should I install it?)

For python 3 pip install urllib

find the utils.py in %PYTHON_HOME%\Lib\site-packages\solrcloudpy\utils.py

change the import urlparse to

from urllib import parse as urlparse

Could not load file or assembly 'Microsoft.Web.Infrastructure,

Very easy solution:

In Visual Studio, go to Tools/Library Package Manager/Package Manager Console

<PM> Install-Package Microsoft.Web.InfraStructure

Have a nice time

Create a custom event in Java

You probably want to look into the observer pattern.

Here's some sample code to get yourself started:

import java.util.*;

// An interface to be implemented by everyone interested in "Hello" events
interface HelloListener {
    void someoneSaidHello();
}

// Someone who says "Hello"
class Initiater {
    private List<HelloListener> listeners = new ArrayList<HelloListener>();

    public void addListener(HelloListener toAdd) {
        listeners.add(toAdd);
    }

    public void sayHello() {
        System.out.println("Hello!!");

        // Notify everybody that may be interested.
        for (HelloListener hl : listeners)
            hl.someoneSaidHello();
    }
}

// Someone interested in "Hello" events
class Responder implements HelloListener {
    @Override
    public void someoneSaidHello() {
        System.out.println("Hello there...");
    }
}

class Test {
    public static void main(String[] args) {
        Initiater initiater = new Initiater();
        Responder responder = new Responder();

        initiater.addListener(responder);

        initiater.sayHello();  // Prints "Hello!!!" and "Hello there..."
    }
}

Related article: Java: Creating a custom event

Using StringWriter for XML Serialization

public static T DeserializeFromXml<T>(string xml)
{
    T result;
    XmlSerializerFactory serializerFactory = new XmlSerializerFactory();
    XmlSerializer serializer =serializerFactory.CreateSerializer(typeof(T));

    using (StringReader sr3 = new StringReader(xml))
    {
        XmlReaderSettings settings = new XmlReaderSettings()
        {
            CheckCharacters = false // default value is true;
        };

        using (XmlReader xr3 = XmlTextReader.Create(sr3, settings))
        {
            result = (T)serializer.Deserialize(xr3);
        }
    }

    return result;
}

how to kill the tty in unix

I had the same question as you but I wanted to kill the gnome terminal which I was in. I read the manual on "who" and found that you can list all of the sessions logged into your computer with the '-a' option and then the '-l' option prints the system login processes.

who -la

What who gave me You should get something like this. Then all you have to do is kill the process with the 'kill' command.

kill <PID>

converting list to json format - quick and easy way

If you are using WebApi, HttpResponseMessage is a more elegant way to do it

public HttpResponseMessage Get()
{
    return Request.CreateResponse(HttpStatusCode.OK, ListOfMyObject);
}

C++ String Concatenation operator<<

nametext = "Your name is" + name;

I think this should do

Type of expression is ambiguous without more context Swift

This might not be very applicable to others, but my problem was that the changes I made was NOT saved yet! Press CMD + S and save your work before building on top of it.

curl -GET and -X GET

The use of -X [WHATEVER] merely changes the request's method string used in the HTTP request. This is easier to understand with two examples — one with -X [WHATEVER] and one without — and the associated HTTP request headers for each:

# curl -XPANTS -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.224.86.126) port 80 (#0)
> PANTS / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*

# curl -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.33.50.167) port 80 (#0)
> GET / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*

How to use ADB in Android Studio to view an SQLite DB

Easiest way for me is using Android Device Monitor to get the database file and SQLite DataBase Browser to view the file while still using Android Studio to program android.

1) Run and launch database app with Android emulator from Android Studio. (I inserted some data to database app to verify)

2) Run Android Device Monitor. How to run?; Go to [your_folder] > sdk >tools. You can see monitor.bat in that folder. shift + right click inside the folder and select "Open command window here". This action will launch command prompt. type monitor and Android Device Monitor will be launched.

3) Select the emulator that you are currently running. Then Go to data>data>[your_app_name]>databases

4) Click on the icon (located at top right corner) (hover on the icon and you will see "pull a file from the device") and save anywhere you like

5) Launch SQLite DataBase Browser. Drag and drop the file that you just saved into that Browser.

6) Go to Browse Data tab and select your table to view.

enter image description here enter image description here

Python copy files to a new directory and rename if file name already exists

For me shutil.copy is the best:

import shutil

#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)

You can change the path of the files as you want.

Detect all changes to a <input type="text"> (immediately) using JQuery

Unfortunately, I think setInterval wins the prize:

<input type=text id=input_id />
<script>
setInterval(function() { ObserveInputValue($('#input_id').val()); }, 100);
</script>

It's the cleanest solution, at only 1 line of code. It's also the most robust, since you don't have to worry about all the different events/ways an input can get a value.

The downsides of using 'setInterval' don't seem to apply in this case:

  • The 100ms latency? For many applications, 100ms is fast enough.
  • Added load on the browser? In general, adding lots of heavy-weight setIntervals on your page is bad. But in this particular case, the added page load is undetectable.
  • It doesn't scale to many inputs? Most pages don't have more than a handful of inputs, which you can sniff all in the same setInterval.

What are good grep tools for Windows?

GrepWin Free and open source (GPL)

enter image description hereI've been using grepWin which was written by one of the tortoisesvn guys. Does the job on Windows...

http://stefanstools.sourceforge.net/grepWin.html

How to make the tab character 4 spaces instead of 8 spaces in nano?

For future viewers, there is a line in my /etc/nanorc file close to line 153 that says "set tabsize 8". The word might need to be tabsize instead of tabspace. After I replaced 8 with 4 and uncommented the line, it solved my problem.

Stylesheet not loaded because of MIME-type

I faced similar error and found that the error was adding '/' at the end of style.css link href.

Replacing <link rel="stylesheet" href="style.css/"> to <link rel="stylesheet" href="style.css"> fixed the issue.

MySQL 'Order By' - sorting alphanumeric correctly

Just do this:

SELECT * FROM table ORDER BY column `name`+0 ASC

Appending the +0 will mean that:

0, 10, 11, 2, 3, 4

becomes :

0, 2, 3, 4, 10, 11

How to dump raw RTSP stream to file?

You can use mplayer.

mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi

The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.

In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.

Handling click events on a drawable within an EditText

Better to have ImageButton on Right of edit text and give negative layout margin to overlap with edit text. Set listener on ImageButton and perform operations.

TypeError: Router.use() requires middleware function but got a Object

If your are using express above 2.x, you have to declare app.router like below code. Please try to replace your code

app.use('/', routes);

with

app.use(app.router);
routes.initialize(app);

Please click here to get more details about app.router

Note:

app.router is depreciated in express 3.0+. If you are using express 3.0+, refer to Anirudh's answer below.

Where is database .bak file saved from SQL Server Management Studio?

...\Program Files\Microsoft SQL Server\MSSQL 1.0\MSSQL\Backup

Creating and playing a sound in swift

Let us see a more updated approach to this question:

Import AudioToolbox

func noteSelector(noteNumber: String) {

    if let soundURL = Bundle.main.url(forResource: noteNumber, withExtension: "wav") {
        var mySound: SystemSoundID = 0
        AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
        AudioServicesPlaySystemSound(mySound)
}

UITableViewCell Selected Background Color on Multiple Selection

By adding a custom view with the background color of your own you can have a custom selection style in table view.

let customBGColorView = UIView()
customBGColorView.backgroundColor = UIColor(hexString: "#FFF900")
cellObj.selectedBackgroundView = customBGColorView

Add this 3 line code in cellForRowAt method of TableView. I have used an extension in UIColor to add color with hexcode. Put this extension code at the end of any Class(Outside the class's body).

extension UIColor {    
convenience init(hexString: String) {
    let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
    var int = UInt32()
    Scanner(string: hex).scanHexInt32(&int)
    let a, r, g, b: UInt32
    switch hex.characters.count {
    case 3: // RGB (12-bit)
        (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
    case 6: // RGB (24-bit)
        (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
    case 8: // ARGB (32-bit)
        (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
    default:
        (a, r, g, b) = (255, 0, 0, 0)
    }
    self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
  }
}

How I can get web page's content and save it into the string variable

You can use the WebClient

Using System.Net;
    
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.gooogle.com");

How do I make this file.sh executable via double click?

Remove the extension altogether and then double-click it. Most system shell scripts are like this. As long as it has a shebang it will work.

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

If your environment is using both Guice and Spring and using the constructor @Inject, for example, with Play Framework, you will also run into this issue if you have mistakenly auto-completed the import with an incorrect choice of:

import com.google.inject.Inject;

Then you get the same missing default constructor error even though the rest of your source with @Inject looks exactly the same way as other working components in your project and compile without an error.

Correct that with:

import javax.inject.Inject;

Do not write a default constructor with construction time injection.

Vim for Windows - What do I type to save and exit from a file?

Instead of telling you how you could execute a certain command (Esc:wq), I can provide you two links that may help you with VIM:

However, the best way to learn Vim is not only using it for Git commits, but as a regular editor for your everyday work.

If you're not going to switch to Vim, it's nonsense to keep its commands in mind. In that case, go and set up your favourite editor to use with Git.

How does the keyword "use" work in PHP and can I import classes with it?

Can I use it to import classes?

You can't do it like that besides the examples above. You can also use the keyword use inside classes to import traits, like this:

trait Stuff {
    private $baz = 'baz';
    public function bar() {
        return $this->baz;
    }
}

class Cls {
    use Stuff;  // import traits like this
}

$foo = new Cls;
echo $foo->bar(); // spits out 'baz'

Setting Camera Parameters in OpenCV/Python

If anyone is still wondering what the value in CV_CAP_PROP_EXPOSURE might be:

Depends. For my cheap webcam I have to enter the desired value directly, e.g. 0.1 for 1/10s. For my expensive industrial camera I have to enter -5 to get an exposure time of 2^-5s = 1/32s.

Does :before not work on img elements?

Try this code

.button:after {
    content: ""
    position: absolute
    width: 70px
    background-image: url('../../images/frontapp/mid-icon.svg')
    display: inline-block
    background-size: contain
    background-repeat: no-repeat
    right: 0
    bottom: 0
}

Save Dataframe to csv directly to s3 Python

You can also use the AWS Data Wrangler:

import awswrangler as wr
    
wr.s3.to_csv(
    df=df,
    path="s3://...",
)

Note that it will handle multipart upload for you to make the upload faster.

Critical t values in R

Josh's comments are spot on. If you are not super familiar with critical values I'd suggest playing with qt, reading the manual (?qt) in conjunction with looking at a look up table (LINK). When I first moved from SPSS to R I created a function that made critical t value look up pretty easy (I'd never use this now as it takes too much time and with the p values that are generally provided in the output it's a moot point). Here's the code for that:

critical.t <- function(){
    cat("\n","\bEnter Alpha Level","\n")
    alpha<-scan(n=1,what = double(0),quiet=T)
    cat("\n","\b1 Tailed or 2 Tailed:\nEnter either 1 or 2","\n")
    tt <- scan(n=1,what = double(0),quiet=T)
    cat("\n","\bEnter Number of Observations","\n")
    n <- scan(n=1,what = double(0),quiet=T)
    cat("\n\nCritical Value =",qt(1-(alpha/tt), n-2), "\n")
}

critical.t()

How to check if mysql database exists

Using the INFORMATION_SCHEMA or show databases is not reliable when you do not have enough permissions to see the database. It will seem that the DB does not exist when you just don't have access to it. The creation would then fail afterwards. Another way to have a more precise check is to use the output of the use command, even though I do not know how solid this approach could be (text output change in future versions / other languages...) so be warned.

CHECK=$(mysql -sNe "use DB_NAME" 2>&1)
if [ $? -eq 0 ]; then
  # database exists and is accessible
elif [ ! -z "$(echo $CHECK | grep 'Unknown database')" ]; then
  # database does not exist
elif [ ! -z "$(echo $CHECK | grep 'Access denied')" ]; then
  # cannot tell if database exists (not enough permissions)"
else
  # unexpected output
fi

jquery - How to determine if a div changes its height or any css attribute?

Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.

https://github.com/marcj/css-element-queries

It contains a ResizeSensor class you can use for that purpose.

new ResizeSensor(jQuery('#mainContent'), function(){ 
    console.log('main content dimension changed');
});

Disclaimer: I wrote this library

C# create simple xml file

You could use XDocument:

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

If the file you want to create is very big and cannot fit into memory you might use XmlWriter.

Restore the mysql database from .frm files

Copy all file and replace to /var/lib/mysql , after that you must change owner of files to mysql this is so important if mariadb.service restart has been faild

chown -R mysql:mysql /var/lib/mysql/*

and

chmod -R 700 /var/lib/mysql/*

UTF-8 all the way through

First of all if you are in < 5.3PHP then no. You've got a ton of problems to tackle.

I am surprised that none has mentioned the intl library, the one that has good support for unicode, graphemes, string operations , localisation and many more, see below.

I will quote some information about unicode support in PHP by Elizabeth Smith's slides at PHPBenelux'14

INTL

Good:

  • Wrapper around ICU library
  • Standardised locales, set locale per script
  • Number formatting
  • Currency formatting
  • Message formatting (replaces gettext)
  • Calendars, dates, timezone and time
  • Transliterator
  • Spoofchecker
  • Resource bundles
  • Convertors
  • IDN support
  • Graphemes
  • Collation
  • Iterators

Bad:

  • Does not support zend_multibite
  • Does not support HTTP input output conversion
  • Does not support function overloading

mb_string

  • Enables zend_multibyte support
  • Supports transparent HTTP in/out encoding
  • Provides some wrappers for funtionallity such as strtoupper

ICONV

  • Primary for charset conversion
  • Output buffer handler
  • mime encoding functionality
  • conversion
  • some string helpers (len, substr, strpos, strrpos)
  • Stream Filter stream_filter_append($fp, 'convert.iconv.ISO-2022-JP/EUC-JP')

DATABASES

  • mysql: Charset and collation on tables and on connection (not the collation). Also don't use mysql - msqli or PDO
  • postgresql: pg_set_client_encoding
  • sqlite(3): Make sure it was compiled with unicode and intl support

Some other Gotchas

  • You cannot use unicode filenames with PHP and windows unless you use a 3rd part extension.
  • Send everything in ASCII if you are using exec, proc_open and other command line calls
  • Plain text is not plain text, files have encodings
  • You can convert files on the fly with the iconv filter

I ll update this answer in case things change features added and so on.

Python - IOError: [Errno 13] Permission denied:

For me, this was a permissions issue.

Use the 'Take Ownership' application on that specific folder. However, this sometimes seems to work only temporarily and is not a permanent solution.

Is System.nanoTime() completely useless?

This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.

In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.

[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.

Java List.contains(Object with field value equal to x)

Map

You could create a Hashmap<String, Object> using one of the values as a key, and then seeing if yourHashMap.keySet().contains(yourValue) returns true.

How to download python from command-line?

wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz  
cd Python-2.7.11

Now read the README file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.

./configure  
make  
sudo make install  

For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

For other versions and the most up to date download links:
http://www.python.org/getit/

How to apply style classes to td classes?

You can use :nth-child(N) CSS selector like :

table td:first-child {}  //1
table td:nth-child(2) {} //2
table td:nth-child(3) {} //3
table td:last-child {}   //4

How to quickly test some javascript code?

If you want to edit some complex javascript I suggest you use JsFiddle. Alternatively, for smaller pieces of javascript you can just run it through your browser URL bar, here's an example:

javascript:alert("hello world");

And, as it was already suggested both Firebug and Chrome developer tools have Javascript console, in which you can type in your javascript to execute. So do Internet Explorer 8+, Opera, Safari and potentially other modern browsers.

What does the @Valid annotation indicate in Spring?

IIRC @Valid isn't a Spring annotation but a JSR-303 annotation (which is the Bean Validation standard). What it does is it basically checks if the data that you send to the method is valid or not (it will validate the scriptFile for you).

align right in a table cell with CSS

Use

text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

See

text-align

<td class='alnright'>text to be aligned to right</td>

<style>
    .alnright { text-align: right; }
</style>

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

How do I check if a string contains a specific word?

A string can be checked with the below function:

function either_String_existor_not($str, $character) {
    if (strpos($str, $character) !== false) {
        return true;
    }
    return false;
}