Programs & Examples On #Levenshtein distance

A metric for measuring the amount of difference between two sequences.

Getting the closest string match

Here you can have a golang POC for calculate the distances between the given words. You can tune the minDistance and difference for other scopes.

Playground: https://play.golang.org/p/NtrBzLdC3rE

package main

import (
    "errors"
    "fmt"
    "log"
    "math"
    "strings"
)

var data string = `THE RED COW JUMPED OVER THE GREEN CHICKEN-THE RED COW JUMPED OVER THE RED COW-THE RED FOX JUMPED OVER THE BROWN COW`

const minDistance float64 = 2
const difference float64 = 1

type word struct {
    data    string
    letters map[rune]int
}

type words struct {
    words []word
}

// Print prettify the data present in word
func (w word) Print() {
    var (
        lenght int
        c      int
        i      int
        key    rune
    )
    fmt.Printf("Data: %s\n", w.data)
    lenght = len(w.letters) - 1
    c = 0
    for key, i = range w.letters {
        fmt.Printf("%s:%d", string(key), i)
        if c != lenght {
            fmt.Printf(" | ")
        }
        c++
    }
    fmt.Printf("\n")
}

func (ws words) fuzzySearch(data string) ([]word, error) {
    var (
        w      word
        err    error
        founds []word
    )
    w, err = initWord(data)
    if err != nil {
        log.Printf("Errors: %s\n", err.Error())
        return nil, err
    }
    // Iterating all the words
    for i := range ws.words {
        letters := ws.words[i].letters
        //
        var similar float64 = 0
        // Iterating the letters of the input data
        for key := range w.letters {
            if val, ok := letters[key]; ok {
                if math.Abs(float64(val-w.letters[key])) <= minDistance {
                    similar += float64(val)
                }
            }
        }

        lenSimilarity := math.Abs(similar - float64(len(data)-strings.Count(data, " ")))
        log.Printf("Comparing %s with %s i've found %f similar letter, with weight %f", data, ws.words[i].data, similar, lenSimilarity)
        if lenSimilarity <= difference {
            founds = append(founds, ws.words[i])
        }
    }

    if len(founds) == 0 {
        return nil, errors.New("no similar found for data: " + data)
    }

    return founds, nil
}

func initWords(data []string) []word {
    var (
        err   error
        words []word
        word  word
    )
    for i := range data {
        word, err = initWord(data[i])
        if err != nil {
            log.Printf("Error in index [%d] for data: %s", i, data[i])
        } else {
            words = append(words, word)
        }
    }
    return words

}

func initWord(data string) (word, error) {
    var word word

    word.data = data
    word.letters = make(map[rune]int)
    for _, r := range data {
        if r != 32 { // avoid to save the whitespace
            word.letters[r]++
        }

    }
    return word, nil
}
func main() {
    var ws words
    words := initWords(strings.Split(data, "-"))
    for i := range words {
        words[i].Print()
    }
    ws.words = words

    solution, _ := ws.fuzzySearch("THE BROWN FOX JUMPED OVER THE RED COW")
    fmt.Println("Possible solutions: ", solution)

}

"Could not find the main class" error when running jar exported by Eclipse

For netbeans user that having this problem is as simply:

1.Go to your Project and Right Click and Select Properties

2.Click Run and also click browser.

3.Select your frames you want to first appear.

Set size on background image with CSS?

If your users use only Opera 9.5+, Safari 3+, Internet Explorer 9+ and Firefox 3.6+ then the answer is yes. Otherwise, no.

The background-size property is part of CSS 3, but it won't work on most browsers.

For your purposes just make the actual image larger.

c# open file with default application and parameters

Please add Settings under Properties for the Project and make use of them this way you have clean and easy configurable settings that can be configured as default

How To: Create a New Setting at Design Time

Update: after comments below

  1. Right + Click on project
  2. Add New Item
  3. Under Visual C# Items -> General
  4. Select Settings File

Dynamically load JS inside JS

You can do it using JQuery:

$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
  console.log(data); //data returned
  console.log(textStatus); //success
  console.log(jqxhr.status); //200
  console.log('Load was performed.');
});

this link should help: http://api.jquery.com/jQuery.getScript/

Remote debugging a Java application

Steps:

  1. Start your remote java application with debugging options as said in above post.
  2. Configure Eclipse for remote debugging by specifying host and port.
  3. Start remote debugging in Eclipse and wait for connection to succeed.
  4. Setup breakpoint and debug.
  5. If you want to debug from start of application use suspend=y , this will keep remote application suspended until you connect from eclipse.

See Step by Step guide on Java remote debugging for full details.

How to create a date object from string in javascript

var d = new Date(2011,10,30);

as months are indexed from 0 in js.

rand() returns the same number each time the program is run

For what its worth you are also only generating numbers between 0 and 99 (inclusive). If you wanted to generate values between 0 and 100 you would need.

rand() % 101

in addition to calling srand() as mentioned by others.

What is the easiest way to parse an INI File in C++?

Have you tried libconfig; very JSON-like syntax. I prefer it over XML configuration files.

Count number of matches of a regex in Javascript

how about like this

function isint(str){
    if(str.match(/\d/g).length==str.length){
        return true;
    }
    else {
         return false
    }
}

"Operation must use an updateable query" error in MS Access

UPDATE [GS] INNER JOIN [Views] ON 
([Views].Hostname = [GS].Hostname) 
AND ([GS].APPID = [Views].APPID) <------------ This is the difference 
SET 
    [GS].APPID = [Views].APPID, 
    [GS].[Name] = [Views].[Name], 
    [GS].Hostname = [Views].Hostname, 
    [GS].[Date] = [Views].[Date], 
    [GS].[Unit] = [Views].[Unit], 
    [GS].[Owner] = [Views].[Owner];

HTML Button Close Window

When in the onclick attribute you do not need to specify that it is Javascript.

<button type="button" 
        onclick="window.open('', '_self', ''); window.close();">Discard</button>

This should do it. In order to close it your page needs to be opened by the script, hence the window.open. Here is an article explaining this in detail:

Click Here

If all else fails, you should also add a message asking the user to manually close the window, as there is no cross-browser solution for this, especially with older browsers such as IE 8.

Include CSS,javascript file in Yii Framework

I liked to answer this question.

Their are many places where we have css & javascript files, like in css folder which is outside the protected folder, css & js files of extension & widgets which we need to include externally sometime when use ajax a lot, js & css files of core framework which also we need to include externally sometime. So their are some ways to do this.

Include core js files of framework like jquery.js, jquery.ui.js

<?php 
Yii::app()->clientScript->registerCoreScript('jquery');     
Yii::app()->clientScript->registerCoreScript('jquery.ui'); 
?>

Include files from css folder outside of protected folder.

<?php 
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/example.css');
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/css/example.js');
?>

Include css & js files from extension or widgets.

Here fancybox is an extension which is placed under protected folder. Files we including has path : /protected/extensions/fancybox/assets/

<?php
// Fancybox stuff.
$assetUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.fancybox.assets'));
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.fancybox-1.3.4.pack.js'); 
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.mousewheel-3.0.4.pack.js'); 
?>  

Also we can include core framework files: Example : I am including CListView js file.

<?php
$baseScriptUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets'));
Yii::app()->clientScript->registerScriptFile($baseScriptUrl.'/listview/jquery.yiilistview.js',CClientScript::POS_END);  
?>
  • We need to include js files of zii widgets or extension externally sometimes when we use them in rendered view which are received from ajax call, because loading each time new ajax file create conflict in calling js functions.

For more detail Look at my blog article

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

C char array initialization

The relevant part of C11 standard draft n1570 6.7.9 initialization says:

14 An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

and

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c; would be initialized within a function.

Finally,

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

[--]

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;

[--]

Thus, char being an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.

How to force deletion of a python object?

  1. Add an exit handler that closes all the bars.
  2. __del__() gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.
  3. If __init__() raises an exception then the object is assumed to be incomplete and __del__() won't be invoked.

How to install Jdk in centos

Try the following to see if you have the proper repository installed:

# yum search java | grep 'java-'

This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:

http://dag.wieers.com/rpm/FAQ.php#B

After you've got it installed try yum search again... This time you'll have a bunch of java stuff.

# yum search java | grep 'java-'

This will return the list of the available java packages. You can install one like this:

# yum install java-1.7.0-openjdk.x86_64

How to use Java property files?

  • You can store the file anywhere you like. If you want to keep it in your jar file, you'll want to use Class.getResourceAsStream() or ClassLoader.getResourceAsStream() to access it. If it's on the file system it's slightly easier.

  • Any extension is fine, although .properties is more common in my experience

  • Load the file using Properties.load, passing in an InputStream or a StreamReader if you're using Java 6. (If you are using Java 6, I'd probably use UTF-8 and a Reader instead of the default ISO-8859-1 encoding for a stream.)

  • Iterate through it as you'd iterate through a normal Hashtable (which Properties derives from), e.g. using keySet(). Alternatively, you can use the enumeration returned by propertyNames().

How to disable logging on the standard error stream in Python?

No need to divert stdout. Here is better way to do it:

import logging
class MyLogHandler(logging.Handler):
    def emit(self, record):
        pass

logging.getLogger().addHandler(MyLogHandler())

An even simpler way is:

logging.getLogger().setLevel(100)

How to show current time in JavaScript in the format HH:MM:SS?

This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.

var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.

Markdown and including multiple files

IMHO, You can get your result by concatenating your input *.md files like:

$ pandoc -s -o outputDoc.pdf inputDoc1.md inputDoc2.md outputDoc3.md

How can I make my custom objects Parcelable?

Android parcable has some unique things. Those are given bellow:

  1. You have to read Parcel as the same order where you put data on parcel.
  2. Parcel will empty after read from parcel. That is if you have 3 data on your parcel. Then after read 3 times parcel will be empty.

Example: To make a class Parceble it must be implement Parceble. Percable has 2 method:

int describeContents();
void writeToParcel(Parcel var1, int var2);

Suppose you have a Person class and it has 3 field, firstName,lastName and age. After implementing Parceble interface. this interface is given bellow:

import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable{
    private String firstName;
    private String lastName;
    private int age;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(firstName);
        parcel.writeString(lastName);
        parcel.writeInt(age);
    }

}

Here writeToParcel method we are writing/adding data on Parcel in an order. After this we have to add bellow code for reading data from parcel:

protected Person(Parcel in) {
        firstName = in.readString();
        lastName = in.readString();
        age = in.readInt();
    }

    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

Here, Person class is taking a parcel and getting data in same an order during writing.

Now during intent getExtra and putExtra code is given bellow:

Put in Extra:

Person person=new Person();
                person.setFirstName("First");
                person.setLastName("Name");
                person.setAge(30);

                Intent intent = new Intent(getApplicationContext(), SECOND_ACTIVITY.class);
                intent.putExtra()
                startActivity(intent); 

Get Extra:

Person person=getIntent().getParcelableExtra("person");

Full Person class is given bellow:

import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable{
    private String firstName;
    private String lastName;
    private int age;



    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(firstName);
        parcel.writeString(lastName);
        parcel.writeInt(age);
    }

    protected Person(Parcel in) {
        firstName = in.readString();
        lastName = in.readString();
        age = in.readInt();
    }

    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

}

Hope this will help you 
Thanks :)

SQlite - Android - Foreign key syntax

As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!

Saving a select count(*) value to an integer (SQL Server)

select @myInt = COUNT(*) from myTable

How to format column to number format in Excel sheet?

If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe

Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value

But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version

Sub CommandClick()

    Dim rCell As Range
    Dim rNext As Range

    For Each rCell In Sheet2.Range("C1:C30000").Cells
        If rCell.Value >= 100 And rCell.Value < 1000 Then
            Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
            rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
        End If
    Next rCell

End Sub

Is Safari on iOS 6 caching $.ajax results?

We found that older iPhones and iPads, running iOS versions 9 & 10, occasionally return bogus blank AJAX results, perhaps due to Apple's turning down CPU speed. When returning the blank result, iOS does not call the server, as if returning a result from cache. Frequency varies widely, from roughly 10% to 30% of AJAX calls return blank.

The solution is hard to believe. Just wait 1s and call again. In our testing, only one repeat was all that was ever needed, but we wrote the code to call up to 4 times. We're not sure if the 1s wait is required, but we didn't want to risk burdening our server with bursts of repeated calls.

We found the problem happened with two different AJAX calls, calling on different API files with different data. But I'm concerned it could happen on any AJAX call. We just don't know because we don't inspect every AJAX result and we don't test every call multiple times on old devices.

Both problem AJAX calls were using: POST, Asynchronously = true, setRequestHeader = ('Content-Type', 'application/x-www-form-urlencoded')

When the problem happens, there's usually only one AJAX call going on. So it's not due to overlapping AJAX calls. Sometimes the problem happens when the device is busy, but sometimes not, and without DevTools we don't really know what's happening at the time.

iOS 13 doesn't do this, nor Chrome or Firefox. We don't have any test devices running iOS 11 or 12. Perhaps someone else could test those?

I'm noting this here because this question is the top Google result when searching for this problem.

How can I enter latitude and longitude in Google Maps?

First is latitude, second longitude. Different than many constructors in mapbox.

Here are examples of formats that work:

  • Degrees, minutes, and seconds (DMS): 41°24'12.2"N 2°10'26.5"E
  • Degrees and decimal minutes (DMM): 41 24.2028, 2 10.4418
  • Decimal degrees (DD): 41.40338, 2.17403

Tips for formatting your coordinates

  • Use the degree symbol instead of “d”.
  • Use periods as decimals, not commas.
    • Incorrect: 41,40338, 2,17403.
    • Correct: 41.40338, 2.17403.
  • List your latitude coordinates before longitude coordinates.
  • Check that the first number in your latitude coordinate is between -90 and 90 and the first number in your longitude coordinate is between -180 and 180.

https://support.google.com/maps/answer/18539

How do I do an OR filter in a Django query?

There is Q objects that allow to complex lookups. Example:

from django.db.models import Q

Item.objects.filter(Q(creator=owner) | Q(moderated=False))

$_POST not working. "Notice: Undefined index: username..."

first of all,

be sure that there is a post

if(isset($_POST['username'])) { 
    // check if the username has been set
}

second, and most importantly, sanitize the data, meaning that

$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";

is deadly dangerous, instead use

$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";

and please research the subject sql injection

FB OpenGraph og:image not pulling images (possibly https?)

For me this worked:

<meta property="og:url" content="http://yoursiteurl" />
    <meta property="og:image" content="link_to_first_image_if_you_want" />
    <meta property="og:image" content="link_to_second_image_if_you_want" />
    <meta property="og:image:type" content="image/jpeg" /> 
    <meta property="og:image:width" content="400" /> 
    <meta property="og:image:height" content="300" />
    <meta property="og:title" content="your title" />
    <meta property="og:description"  content="your text about homepage"/> 

ScriptManager.RegisterStartupScript code not working - why?

Try this code...

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);

Where UpdatePanel1 is the id for Updatepanel on your page

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

You could add the following VBA code to your sheet:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") > 0.5 Then
        MsgBox "Discount too high"
    End If
End Sub

Every time a cell is changed on the sheet, it will check the value of cell A1.

Notes:

  • if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
  • the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.

Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):

  • Pros: his method will work if A1's value is linked to cells located in other sheets.
  • Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.

Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I have the same issue. It looks like it's unable to find the libmysqlclient library. A temporary fix that has worked for me is the following:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/

I am not sure where the config is specifying the load path or what it's set to but my mysql install did not appear to be in it. I'll post again if I find a more permanent solution.

Edit: Actually this fix appears to more accurately address the problem.

Count the number of occurrences of each letter in string

Like this:

int counts[26];
memset(counts, 0, sizeof(counts));
char *p = string;
while (*p) {
    counts[tolower(*p++) - 'a']++;
}

This code assumes that the string is null-terminated, and that it contains only characters a through z or A through Z, inclusive.

To understand how this works, recall that after conversion tolower each letter has a code between a and z, and that the codes are consecutive. As the result, tolower(*p) - 'a' evaluates to a number from 0 to 25, inclusive, representing the letter's sequential number in the alphabet.

This code combines ++ and *p to shorten the program.

Node.js throws "btoa is not defined" error

Here's a concise universal solution for base64 encoding:

const nodeBtoa = (b) => Buffer.from(b).toString('base64');
export const base64encode = typeof btoa !== 'undefined' ? btoa : nodeBtoa;

How can I throw CHECKED exceptions from inside Java 8 streams?

I agree with the comments above, in using Stream.map you are limited to implementing Function which doesn't throw Exceptions.

You could however create your own FunctionalInterface that throws as below..

@FunctionalInterface
public interface UseInstance<T, X extends Throwable> {
  void accept(T instance) throws X;
}

then implement it using Lambdas or references as shown below.

import java.io.FileWriter;
import java.io.IOException;

//lambda expressions and the execute around method (EAM) pattern to
//manage resources

public class FileWriterEAM  {
  private final FileWriter writer;

  private FileWriterEAM(final String fileName) throws IOException {
    writer = new FileWriter(fileName);
  }
  private void close() throws IOException {
    System.out.println("close called automatically...");
    writer.close();
  }
  public void writeStuff(final String message) throws IOException {
    writer.write(message);
  }
  //...

  public static void use(final String fileName, final UseInstance<FileWriterEAM, IOException> block) throws IOException {

    final FileWriterEAM writerEAM = new FileWriterEAM(fileName);    
    try {
      block.accept(writerEAM);
    } finally {
      writerEAM.close();
    }
  }

  public static void main(final String[] args) throws IOException {

    FileWriterEAM.use("eam.txt", writerEAM -> writerEAM.writeStuff("sweet"));

    FileWriterEAM.use("eam2.txt", writerEAM -> {
        writerEAM.writeStuff("how");
        writerEAM.writeStuff("sweet");      
      });

    FileWriterEAM.use("eam3.txt", FileWriterEAM::writeIt);     

  }


 void writeIt() throws IOException{
     this.writeStuff("How ");
     this.writeStuff("sweet ");
     this.writeStuff("it is");

 }

}

Maximize a window programmatically and prevent the user from changing the windows state

To stop the window being resizeable once you've maximised it you need to change the FormBorderStyle from Sizable to one of the fixed constants:

FixedSingle
Fixed3D
FixedDialog

From the MSDN Page Remarks section:

The border style of the form determines how the outer edge of the form appears. In addition to changing the border display for a form, certain border styles prevent the form from being sized. For example, the FormBorderStyle.FixedDialog border style changes the border of the form to that of a dialog box and prevents the form from being resized. The border style can also affect the size or availability of the caption bar section of a form.

It will change the appearance of the form if you pick Fixed3D for example, and you'll probably have to do some work if you want the form to restore to non-maximised and be resizeable again.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

I found to delete this section from the project file fix the problem.

<ItemGroup>
<Reference Include="Newtonsoft.Json">
  <HintPath>..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>

How to get html table td cell value by JavaScript?

This is my solution

var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
    console.log("My contents is \"" + cells[i].innerHTML + "\"");
}

How can I use a local image as the base image with a dockerfile?

Verified: it works well in Docker 1.7.0.

Don't specify --pull=true when running the docker build command

From this thread on reference locally-built image using FROM at dockerfile:

If you want use the local image as the base image, pass without the option --pull=true
--pull=true will always attempt to pull a newer version of the image.

How to specify an alternate location for the .m2 folder or settings.xml permanently?

You need to add this line into your settings.xml (or uncomment if it's already there).

<localRepository>C:\Users\me\.m2\repo</localRepository>

Also it's possible to run your commands with mvn clean install -gs C:\Users\me\.m2\settings.xml - this parameter will force maven to use different settings.xml then the default one (which is in $HOME/.m2/settings.xml)

Unsupported major.minor version 52.0 in my app

Sorry for the late reply.Hope it helps someone else

This problem is related with your SDK, not with your JDK. You can check your version information from

Help > About > Show Details

You will get something like

Xamarin.Android Version: 6.0.2.1 (Starter Edition) Android SDK: X:\Android\android-sdk

Supported Android versions:

4.0.3 (API level 15)

4.4 (API level 19)

6.0 (API level 23)

SDK Tools Version: 24.4.1

SDK Platform Tools Version: 23.0.1

SDK Build Tools Version: 24 rc2

Java SDK: X:\Program Files (x86)\Java\jdk1.7.0_71

java version "1.7.0_71"

Java(TM) SE Runtime Environment (build 1.7.0_71-b14)

Java HotSpot(TM) Client VM (build 24.71-b01, mixed mode, sharing)

If you are using preview tools for building ,then you will get similar errors all over.

What to do now?

goto

Tools -> SDK manager

  1. Select all items in preview channels including Android SDK build tools with rev 24rc2 or 24rc4(latest)

  2. Click on Delete 'n' packages

How to turn off preview channel

  1. In SDK manager, select

    Tools > options

  2. Uncheck Enable preview tools

And what

Back to your code Clean all and rebuild (In rare cases, you have to select build-tools from project settings page)

JQuery addclass to selected div, remove class if another div is selected

In this mode you can find all element which has class active and remove it

try this

$(document).ready(function() {
        $(this.attr('id')).click(function () {
           $(document).find('.active').removeClass('active');
           var DivId = $(this).attr('id');
           alert(DivId);
           $(this).addClass('active');
        });
  });

Removing Java 8 JDK from Mac

Use /usr/libexec/java_home ; I found these alias and function to be pretty useful in my ~/.profile:

alias java_ls='/usr/libexec/java_home -V 2>&1 | cut -s -d , -f 1 | cut -c 5-'
function java_use() {
    export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    java -version
}

Linq Query Group By and Selecting First Items

var result = list.GroupBy(x => x.Category).Select(x => x.First())

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

If your data file is structured like this

col1, col2, col3
   1,    2,    3
  10,   20,   30
 100,  200,  300

then numpy.genfromtxt can interpret the first line as column headers using the names=True option. With this you can access the data very conveniently by providing the column header:

data = np.genfromtxt('data.txt', delimiter=',', names=True)
print data['col1']    # array([   1.,   10.,  100.])
print data['col2']    # array([   2.,   20.,  200.])
print data['col3']    # array([   3.,   30.,  300.])

Since in your case the data is formed like this

row1,   1,  10, 100
row2,   2,  20, 200
row3,   3,  30, 300

you can achieve something similar using the following code snippet:

labels = np.genfromtxt('data.txt', delimiter=',', usecols=0, dtype=str)
raw_data = np.genfromtxt('data.txt', delimiter=',')[:,1:]
data = {label: row for label, row in zip(labels, raw_data)}

The first line reads the first column (the labels) into an array of strings. The second line reads all data from the file but discards the first column. The third line uses dictionary comprehension to create a dictionary that can be used very much like the structured array which numpy.genfromtxt creates using the names=True option:

print data['row1']    # array([   1.,   10.,  100.])
print data['row2']    # array([   2.,   20.,  200.])
print data['row3']    # array([   3.,   30.,  300.])

Simple excel find and replace for formulas

If the formulas are identical you can use Find and Replace with Match entire cell contents checked and Look in: Formulas. Select the range, go into Find and Replace, make your entries and `Replace All.

enter image description here

Or do you mean that there are several formulas with this same form, but different cell references? If so, then one way to go is a regular expression match and replace. Regular expressions are not built into Excel (or VBA), but can be accessed via Microsoft's VBScript Regular Expressions library.

The following function provides the necessary match and replace capability. It can be used in a subroutine that would identify cells with formulas in the specified range and use the formulas as inputs to the function. For formulas strings that match the pattern you are looking for, the function will produce the replacement formula, which could then be written back to the worksheet.

Function RegexFormulaReplace(formula As String)
    Dim regex As New RegExp
    regex.Pattern = "=\(\(([A-Z]+\d+)-([A-Z]+\d+)\)/([A-Z]+\d+)\)"
'   Test if a match is found
    If regex.Test(formula) = True Then
        RegexFormulaReplace = regex.Replace(formula, "=(EXP((LN($1/$2)/14.32))-1")
    Else
        RegexFormulaReplace = CVErr(xlErrValue)
    End If
    Set regex = Nothing
End Function

In order for the function to work, you would need to add a reference to the Microsoft VBScript Regular Expressions 5.5 library. From the Developer tab of the main ribbon, select VBA and then References from the main toolbar. Scroll down to find the reference to the library and check the box next to it.

Laravel Eloquent "WHERE NOT IN"

Query Builder:

DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();

Eloquent:

SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();

XPath test if node value is number

The one I found very useful is the following:

<xsl:choose>
  <xsl:when test="not(number(myNode))">
      <!-- myNode is a not a number or empty(NaN) or zero -->      
  </xsl:when>
  <xsl:otherwise>
      <!-- myNode is a number (!= zero) -->        
  </xsl:otherwise>
</xsl:choose>

Virtualhost For Wildcard Subdomain and Static Subdomain

This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.

<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com

SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"

VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"

DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>

Check variable equality against a list of values

This is easily extendable and readable:

switch (foo) {
    case 1:
    case 3:
    case 12:
        // ...
        break

    case 4:
    case 5:
    case 6:
        // something else
        break
}

But not necessarily easier :)

Preventing HTML and Script injections in Javascript

myDiv.textContent = arbitraryHtmlString 

as @Dan pointed out, do not use innerHTML, even in nodes you don't append to the document because deffered callbacks and scripts are always executed. You can check this https://gomakethings.com/preventing-cross-site-scripting-attacks-when-using-innerhtml-in-vanilla-javascript/ for more info.

PSEXEC, access denied errors

I still use psexec, even on win 10. Replace the psexec.exe in the Windows 10's win32 folder with the older version to work -> I use version 2.11.0.0. The Windows 10 version I was using would only run .bat files as background/hidden process on the remote computer. Took a whole day to figure this out.

Adding the registry key from above to the remote computer helps as well:

   reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f

Javascript: Extend a Function

This is very simple and straight forward. Look at the code. Try to grasp the basic concept behind javascript extension.

First let us extend javascript function.

function Base(props) {
    const _props = props
    this.getProps = () => _props

    // We can make method private by not binding it to this object. 
    // Hence it is not exposed when we return this.
    const privateMethod = () => "do internal stuff" 

    return this
}

You can extend this function by creating child function in following way

function Child(props) {
    const parent = Base(props)
    this.getMessage = () => `Message is ${parent.getProps()}`;

    // You can remove the line below to extend as in private inheritance, 
    // not exposing parent function properties and method.
    this.prototype = parent
    return this
}

Now you can use Child function as follows,

let childObject = Child("Secret Message")
console.log(childObject.getMessage())     // logs "Message is Secret Message"
console.log(childObject.getProps())       // logs "Secret Message"

We can also create Javascript Function by extending Javascript classes, like this.

class BaseClass {
    constructor(props) {
        this.props = props
        // You can remove the line below to make getProps method private. 
        // As it will not be binded to this, but let it be
        this.getProps = this.getProps.bind(this)
    }

    getProps() {
        return this.props
    }
}

Let us extend this class with Child function like this,

function Child(props) {
    let parent = new BaseClass(props)
    const getMessage = () => `Message is ${parent.getProps()}`;
    return { ...parent, getMessage} // I have used spread operator. 
}

Again you can use Child function as follows to get similar result,

let childObject = Child("Secret Message")
console.log(childObject.getMessage())     // logs "Message is Secret Message"
console.log(childObject.getProps())       // logs "Secret Message"

Javascript is very easy language. We can do almost anything. Happy JavaScripting... Hope I was able to give you an idea to use in your case.

How to align text below an image in CSS?

Since the default for block elements is to order one on top of the other you should also be able to do this:

<div>
    <img src="path/to/img">
    <div>Text Under Image</div>
</div

img {
    display: block;
}

Ignore cells on Excel line graph

  1. In the value or values you want to separate, enter the =NA() formula. This will appear that the value is skipped but the preceding and following data points will be joined by the series line.
  2. Enter the data you want to skip in the same location as the original (row or column) but add it as a new series. Add the new series to your chart.
  3. Format the new data point to match the original series format (color, shape, etc.). It will appear as though the data point was just skipped in the original series but will still show on your chart if you want to label it or add a callout.

What are "res" and "req" parameters in Express functions?

I noticed one error in Dave Ward's answer (perhaps a recent change?): The query string paramaters are in request.query, not request.params. (See https://stackoverflow.com/a/6913287/166530 )

request.params by default is filled with the value of any "component matches" in routes, i.e.

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

and, if you have configured express to use its bodyparser (app.use(express.bodyParser());) also with POST'ed formdata. (See How to retrieve POST query parameters? )

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

Module 'tensorflow' has no attribute 'contrib'

If you want to use tf.contrib, you need to now copy and paste the source code from github into your script/notebook. It's annoying and doesn't always work. But that's the only workaround I've found. For example, if you wanted to use tf.contrib.opt.AdamWOptimizer, you have to copy and paste from here. https://github.com/tensorflow/tensorflow/blob/590d6eef7e91a6a7392c8ffffb7b58f2e0c8bc6b/tensorflow/contrib/opt/python/training/weight_decay_optimizers.py#L32

Java 8, Streams to find the duplicate elements

A multiset is a structure maintaining the number of occurrences for each element. Using Guava implementation:

Set<Integer> duplicated =
        ImmutableMultiset.copyOf(numbers).entrySet().stream()
                .filter(entry -> entry.getCount() > 1)
                .map(Multiset.Entry::getElement)
                .collect(Collectors.toSet());

Better/Faster to Loop through set or list?

set is what you want, so you should use set. Trying to be clever introduces subtle bugs like forgetting to add one tomax(mylist)! Code defensively. Worry about what's faster when you determine that it is too slow.

range(min(mylist), max(mylist) + 1)  # <-- don't forget to add 1

How to run a specific Android app using Terminal?

You can Start the android Service by this command.

adb shell am startservice -n packageName/.ServiceClass

Omitting the second expression when using the if-else shorthand

If you're not doing the else, why not do:

if (x==2) doSomething();

How to print struct variables in console?

To print the struct as JSON:

fmt.Printf("%#v\n", yourProject)

Also possible with (as it was mentioned above):

fmt.Printf("%+v\n", yourProject)

But the second option prints string values without "" so it is harder to read.

Get the value of a dropdown in jQuery

If you're using a <select>, .val() gets the 'value' of the selected <option>. If it doesn't have a value, it may fallback to the id. Put the value you want it to return in the value attribute of each <option>

Edit: See comments for clarification on what value actually is (not necessarily equal to the value attribute).

Query to search all packages for table and/or column

By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.

(\s|\(|\.|,|^)bqr(\s|,|\)|$)

How to destroy a DOM element with jQuery?

Not sure if it's just me, but using .remove() doesn't seem to work if you are selecting by an id.

Ex: $("#my-element").remove();

I had to use the element's class instead, or nothing happened.

Ex: $(".my-element").remove();

Environment variable to control java.io.tmpdir?

we can change the default tomcat file upload location, as

we have to set the environment variable like : CATALINA_TEMPDIR = YOUR FILE UPLOAD LOCATION. this location will change the path here: java -Djava.io.tmpdir=/path/to/tmpdir

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

You could use a regex, yes, but a simple string.Replace() will probably suffice.

 myString = myString.Replace("\r\n", string.Empty);

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

You may face this issue if you are running your app on Android's Marshmallow or later version (API level 23 or greater), because of the new Real-time Permissions model introduced in this.

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.

For getting permissions at runtime, you will have to request the user. You can do that in following way.

First request for permissions.

String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        requestPermissions(permissions, WRITE_REQUEST_CODE);

And then you can check the results in

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
       case WRITE_REQUEST_CODE:
         if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
           //Permission granted.
           //Continue with writing files...
         }
       else{
           //Permission denied.
         }
        break;
    }
}

Here is good learning source requesting-runtime-permissions-in-android-marshmallow/

Regular Expression to match valid dates

To control a date validity under the following format :

YYYY/MM/DD or YYYY-MM-DD

I would recommand you tu use the following regular expression :

(((19|20)([2468][048]|[13579][26]|0[48])|2000)[/-]02[/-]29|((19|20)[0-9]{2}[/-](0[4678]|1[02])[/-](0[1-9]|[12][0-9]|30)|(19|20)[0-9]{2}[/-](0[1359]|11)[/-](0[1-9]|[12][0-9]|3[01])|(19|20)[0-9]{2}[/-]02[/-](0[1-9]|1[0-9]|2[0-8])))

Matches

2016-02-29 | 2012-04-30 | 2019/09/31

Non-Matches

2016-02-30 | 2012-04-31 | 2019/09/35

You can customise it if you wants to allow only '/' or '-' separators. This RegEx strictly controls the validity of the date and verify 28,30 and 31 days months, even leap years with 29/02 month.

Try it, it works very well and prevent your code from lot of bugs !

FYI : I made a variant for the SQL datetime. You'll find it there (look for my name) : Regular Expression to validate a timestamp

Feedback are welcomed :)

failed to push some refs to [email protected]

It is probably due to an Outdated yarn.lock file

Just run the following commands

yarn install
git add yarn.lock
git commit -m "Updated Yarn lockfile"
git push heroku master

How to select label for="XYZ" in CSS?

If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:

itemSelected(id: number){
    console.log('label contains', document.querySelector("label[for='" + id + "']"));
}

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

What is a database transaction?

Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.

The main operation of a transaction are read and write.

All transaction must contain four properties that commonly known as ACID properties for the purpose of ensuring accuracy , completeness and data integrity.

Javascript date regex DD/MM/YYYY

I build this regular to check month 30/31 and let february to 29.

new RegExp(/^((0[1-9]|[12][0-9]|3[01])(\/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(\/)(02))|((0[1-9]|[12][0-9]|3[0])(\/)(0[469]|11))(\/)\d{4}$/)

I think, it's more simple and more flexible and enough full.

Perhaps first part can be contract but I Don't find properly.

Counting number of lines, words, and characters in a text file

I'm no Java expert, but I would presume that the .hasNext, .hasNextLine and .hasNextByte all use and increment the same file position indicator. You'll need to reset that, either by creating a new Scanner as Aashray mentioned, or using a RandomAccessFile and calling file.seek(0); after each loop.

CSS ''background-color" attribute not working on checkbox inside <div>

Improving another answer here

input[type=checkbox] {
  cursor: pointer;
  margin-right: 10px;
}

input[type=checkbox]:after {
  content: " ";
  background-color: lightgray;
  display: inline-block;
  position: relative;
  top: -4px;
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

input[type=checkbox]:checked:after {
  content: "\00a0\2714";
}

Uploading both data and files in one form using Ajax?

you can just append them on your formdata, add your files and datas in it.you can read this..

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

for better understanding. you can separately retrieve them $_FILES for your files and $_POST for your data.

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

Let's start with the problems these tools want to solve:

My system package manager don't have the Python versions I wanted or I want to install multiple Python versions side by side, Python 3.9.0 and Python 3.9.1, Python 3.5.3, etc

Then use pyenv.

I want to install and run multiple applications with different, conflicting dependencies.

Then use virtualenv or venv. These are almost completely interchangeable, the difference being that virtualenv supports older python versions and has a few more minor unique features, while venv is in the standard library.

I'm developing an /application/ and need to manage my dependencies, and manage the dependency resolution of the dependencies of my project.

Then use pipenv or poetry.

I'm developing a /library/ or a /package/ and want to specify the dependencies that my library users need to install

Then use setuptools.

I used virtualenv, but I don't like virtualenv folders being scattered around various project folders. I want a centralised management of the environments and some simple project management

Then use virtualenvwrapper. Variant: pyenv-virtualenvwrapper if you also use pyenv.


Not recommended

  • pyvenv. This is deprecated, use venv or virtualenv instead. Not to be confused with pipenv or pyenv.

How can I link to a specific glibc version?

Setup 1: compile your own glibc without dedicated GCC and use it

Since it seems impossible to do just with symbol versioning hacks, let's go one step further and compile glibc ourselves.

This setup might work and is quick as it does not recompile the whole GCC toolchain, just glibc.

But it is not reliable as it uses host C runtime objects such as crt1.o, crti.o, and crtn.o provided by glibc. This is mentioned at: https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location Those objects do early setup that glibc relies on, so I wouldn't be surprised if things crashed in wonderful and awesomely subtle ways.

For a more reliable setup, see Setup 2 below.

Build glibc and install locally:

export glibc_install="$(pwd)/glibc/build/install"

git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
mkdir build
cd build
../configure --prefix "$glibc_install"
make -j `nproc`
make install -j `nproc`

Setup 1: verify the build

test_glibc.c

#define _GNU_SOURCE
#include <assert.h>
#include <gnu/libc-version.h>
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>

atomic_int acnt;
int cnt;

int f(void* thr_data) {
    for(int n = 0; n < 1000; ++n) {
        ++cnt;
        ++acnt;
    }
    return 0;
}

int main(int argc, char **argv) {
    /* Basic library version check. */
    printf("gnu_get_libc_version() = %s\n", gnu_get_libc_version());

    /* Exercise thrd_create from -pthread,
     * which is not present in glibc 2.27 in Ubuntu 18.04.
     * https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291 */
    thrd_t thr[10];
    for(int n = 0; n < 10; ++n)
        thrd_create(&thr[n], f, NULL);
    for(int n = 0; n < 10; ++n)
        thrd_join(thr[n], NULL);
    printf("The atomic counter is %u\n", acnt);
    printf("The non-atomic counter is %u\n", cnt);
}

Compile and run with test_glibc.sh:

#!/usr/bin/env bash
set -eux
gcc \
  -L "${glibc_install}/lib" \
  -I "${glibc_install}/include" \
  -Wl,--rpath="${glibc_install}/lib" \
  -Wl,--dynamic-linker="${glibc_install}/lib/ld-linux-x86-64.so.2" \
  -std=c11 \
  -o test_glibc.out \
  -v \
  test_glibc.c \
  -pthread \
;
ldd ./test_glibc.out
./test_glibc.out

The program outputs the expected:

gnu_get_libc_version() = 2.28
The atomic counter is 10000
The non-atomic counter is 8674

Command adapted from https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location but --sysroot made it fail with:

cannot find /home/ciro/glibc/build/install/lib/libc.so.6 inside /home/ciro/glibc/build/install

so I removed it.

ldd output confirms that the ldd and libraries that we've just built are actually being used as expected:

+ ldd test_glibc.out
        linux-vdso.so.1 (0x00007ffe4bfd3000)
        libpthread.so.0 => /home/ciro/glibc/build/install/lib/libpthread.so.0 (0x00007fc12ed92000)
        libc.so.6 => /home/ciro/glibc/build/install/lib/libc.so.6 (0x00007fc12e9dc000)
        /home/ciro/glibc/build/install/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc12f1b3000)

The gcc compilation debug output shows that my host runtime objects were used, which is bad as mentioned previously, but I don't know how to work around it, e.g. it contains:

COLLECT_GCC_OPTIONS=/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o

Setup 1: modify glibc

Now let's modify glibc with:

diff --git a/nptl/thrd_create.c b/nptl/thrd_create.c
index 113ba0d93e..b00f088abb 100644
--- a/nptl/thrd_create.c
+++ b/nptl/thrd_create.c
@@ -16,11 +16,14 @@
    License along with the GNU C Library; if not, see
    <http://www.gnu.org/licenses/>.  */

+#include <stdio.h>
+
 #include "thrd_priv.h"

 int
 thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
 {
+  puts("hacked");
   _Static_assert (sizeof (thr) == sizeof (pthread_t),
                   "sizeof (thr) != sizeof (pthread_t)");

Then recompile and re-install glibc, and recompile and re-run our program:

cd glibc/build
make -j `nproc`
make -j `nproc` install
./test_glibc.sh

and we see hacked printed a few times as expected.

This further confirms that we actually used the glibc that we compiled and not the host one.

Tested on Ubuntu 18.04.

Setup 2: crosstool-NG pristine setup

This is an alternative to setup 1, and it is the most correct setup I've achieved far: everything is correct as far as I can observe, including the C runtime objects such as crt1.o, crti.o, and crtn.o.

In this setup, we will compile a full dedicated GCC toolchain that uses the glibc that we want.

The only downside to this method is that the build will take longer. But I wouldn't risk a production setup with anything less.

crosstool-NG is a set of scripts that downloads and compiles everything from source for us, including GCC, glibc and binutils.

Yes the GCC build system is so bad that we need a separate project for that.

This setup is only not perfect because crosstool-NG does not support building the executables without extra -Wl flags, which feels weird since we've built GCC itself. But everything seems to work, so this is only an inconvenience.

Get crosstool-NG and configure it:

git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
git checkout a6580b8e8b55345a5a342b5bd96e42c83e640ac5
export CT_PREFIX="$(pwd)/.build/install"
export PATH="/usr/lib/ccache:${PATH}"
./bootstrap
./configure --enable-local
make -j `nproc`
./ct-ng x86_64-unknown-linux-gnu
./ct-ng menuconfig

The only mandatory option that I can see, is making it match your host kernel version to use the correct kernel headers. Find your host kernel version with:

uname -a

which shows me:

4.15.0-34-generic

so in menuconfig I do:

  • Operating System
    • Version of linux

so I select:

4.14.71

which is the first equal or older version. It has to be older since the kernel is backwards compatible.

Now you can build with:

env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`

and now wait for about thirty minutes to two hours for compilation.

Setup 2: optional configurations

The .config that we generated with ./ct-ng x86_64-unknown-linux-gnu has:

CT_GLIBC_V_2_27=y

To change that, in menuconfig do:

  • C-library
  • Version of glibc

save the .config, and continue with the build.

Or, if you want to use your own glibc source, e.g. to use glibc from the latest git, proceed like this:

  • Paths and misc options
    • Try features marked as EXPERIMENTAL: set to true
  • C-library
    • Source of glibc
      • Custom location: say yes
      • Custom location
        • Custom source location: point to a directory containing your glibc source

where glibc was cloned as:

git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28

Setup 2: test it out

Once you have built he toolchain that you want, test it out with:

#!/usr/bin/env bash
set -eux
install_dir="${CT_PREFIX}/x86_64-unknown-linux-gnu"
PATH="${PATH}:${install_dir}/bin" \
  x86_64-unknown-linux-gnu-gcc \
  -Wl,--dynamic-linker="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib/ld-linux-x86-64.so.2" \
  -Wl,--rpath="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib" \
  -v \
  -o test_glibc.out \
  test_glibc.c \
  -pthread \
;
ldd test_glibc.out
./test_glibc.out

Everything seems to work as in Setup 1, except that now the correct runtime objects were used:

COLLECT_GCC_OPTIONS=/home/ciro/crosstool-ng/.build/install/x86_64-unknown-linux-gnu/bin/../x86_64-unknown-linux-gnu/sysroot/usr/lib/../lib64/crt1.o

Setup 2: failed efficient glibc recompilation attempt

It does not seem possible with crosstool-NG, as explained below.

If you just re-build;

env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`

then your changes to the custom glibc source location are taken into account, but it builds everything from scratch, making it unusable for iterative development.

If we do:

./ct-ng list-steps

it gives a nice overview of the build steps:

Available build steps, in order:
  - companion_tools_for_build
  - companion_libs_for_build
  - binutils_for_build
  - companion_tools_for_host
  - companion_libs_for_host
  - binutils_for_host
  - cc_core_pass_1
  - kernel_headers
  - libc_start_files
  - cc_core_pass_2
  - libc
  - cc_for_build
  - cc_for_host
  - libc_post_cc
  - companion_libs_for_target
  - binutils_for_target
  - debug
  - test_suite
  - finish
Use "<step>" as action to execute only that step.
Use "+<step>" as action to execute up to that step.
Use "<step>+" as action to execute from that step onward.

therefore, we see that there are glibc steps intertwined with several GCC steps, most notably libc_start_files comes before cc_core_pass_2, which is likely the most expensive step together with cc_core_pass_1.

In order to build just one step, you must first set the "Save intermediate steps" in .config option for the intial build:

  • Paths and misc options
    • Debug crosstool-NG
      • Save intermediate steps

and then you can try:

env -u LD_LIBRARY_PATH time ./ct-ng libc+ -j`nproc`

but unfortunately, the + required as mentioned at: https://github.com/crosstool-ng/crosstool-ng/issues/1033#issuecomment-424877536

Note however that restarting at an intermediate step resets the installation directory to the state it had during that step. I.e., you will have a rebuilt libc - but no final compiler built with this libc (and hence, no compiler libraries like libstdc++ either).

and basically still makes the rebuild too slow to be feasible for development, and I don't see how to overcome this without patching crosstool-NG.

Furthermore, starting from the libc step didn't seem to copy over the source again from Custom source location, further making this method unusable.

Bonus: stdlibc++

A bonus if you're also interested in the C++ standard library: How to edit and re-build the GCC libstdc++ C++ standard library source?

Count number of vector values in range with R

There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:

sum( 2 %<% x %<% 5 )
sum( 2 %<=% x %<=% 5 )

which gives the same results as:

sum( 2 < x & x < 5 )
sum( 2 <= x & x <= 5 )

Which is better is probably more a matter of personal preference.

Django set default form values

I hope this can help you:

form.instance.updatedby = form.cleaned_data['updatedby'] = request.user.id

Remove tracking branches no longer on remote

I use a short method to do the trick, I recommend you to do the same as it could save some hours & give you more visibility

Just add the following snippet into your .bashrc (.bashprofile on macos).

git-cleaner() { git fetch --all --prune && git branch --merged | grep -v -E "\bmaster|preprod|dmz\b" | xargs -n 1 git branch -d ;};
  1. Fetch all remotes
  2. Get only merged branches from git
  3. Remove from this list the "protected / important" branches
  4. Remove the rest (e.g, clean and merged branches)

You'll have to edit the grep regex in order to fit to your needs (here, it prevent master, preprod and dmz from deletion)

Check time difference in Javascript

Try This :

_x000D_
_x000D_
function SumHours() {_x000D_
  var smon = document.getElementById('sMon').value ;_x000D_
  var fmon = document.getElementById('fMon').value ;_x000D_
  var diff = 0 ;_x000D_
  if (smon && fmon) {_x000D_
    smon = ConvertToSeconds(smon);_x000D_
    fmon = ConvertToSeconds(fmon);_x000D_
    diff = Math.abs( fmon - smon ) ;_x000D_
    console.log( 'time difference is : ' + secondsTohhmmss(diff) );_x000D_
  }_x000D_
_x000D_
  function ConvertToSeconds(time) {_x000D_
    var splitTime = time.split(":");_x000D_
    return splitTime[0] * 3600 + splitTime[1] * 60;_x000D_
  }_x000D_
_x000D_
  function secondsTohhmmss(secs) {_x000D_
    var hours = parseInt(secs / 3600);_x000D_
    var seconds = parseInt(secs % 3600);_x000D_
    var minutes = parseInt(seconds / 60) ;_x000D_
    return hours + "hours : " + minutes + "minutes ";_x000D_
  }_x000D_
}
_x000D_
<td>_x000D_
  <input type="time" class="dataInput" id="sMon" onchange="SumHours();" />_x000D_
</td>_x000D_
_x000D_
<td>_x000D_
  <input type="time" class="dataInputt" id="fMon" onchange="SumHours();"/>_x000D_
</td>
_x000D_
_x000D_
_x000D_

Changing project port number in Visual Studio 2013

Steps to resolve this:

  1. Open the solution file.
  2. Find the Port tag against your project name.
  3. Assign any different port as current.
  4. Right click on your project and select Property Pages.
  5. Click on Start Options tab and checked Start URL: option.
  6. Assign the start URL in front of Start URL option like:
    localhost:8080/login.aspx

How to reference a local XML Schema file correctly?

If you work in MS Visual Studio just do following

  1. Put WSDL file and XSD file at the same folder.
  2. Correct WSDL file like this YourSchemeFile.xsd

  3. Use visual Studio using this great example How to generate service reference with only physical wsdl file

Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.

View the change history of a file using Git versioning

If you're using the git GUI (on Windows) under the Repository menu you can use "Visualize master's History". Highlight a commit in the top pane and a file in the lower right and you'll see the diff for that commit in the lower left.

Set NA to 0 in R

To add to James's example, it seems you always have to create an intermediate when performing calculations on NA-containing data frames.

For instance, adding two columns (A and B) together from a data frame dfr:

temp.df <- data.frame(dfr) # copy the original
temp.df[is.na(temp.df)] <- 0
dfr$C <- temp.df$A + temp.df$B # or any other calculation
remove('temp.df')

When I do this I throw away the intermediate afterwards with remove/rm.

Remove insignificant trailing zeros from a number?

If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.

var n = 1.245000
var noZeroes = n.toString() // "1.245" 

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

Learning Ruby on Rails

Beware, the rails world is a massively frustrating mess of outdated and inconsistent documentation and examples. It is maybe one of the fastest moving and most faddish development communities there is. By the time you learn something it will already have changed. Even the books are not consistent in which version of rails they are talking about. Documentation by blogging! enough said.

I currently do RoR on windows. My advice is to avoid windows if you can. Lots of things don't work and the rails community really really doesn't care about you. The move to Git has really messed me up since it doesn't work very well on windows. A lot of gems will fail because of this (Heroku looks like a cool tool - too bad for me it can't handle window's Git setup). Capistrano is out. It goes on and annoyingly on.

Plus, in the back of your mind, you always wonder when something doesn't work "Is it a rails/windows problem?" I am not sure this is solved by using linux because linux brings its own hassles like constantly having to upgrade all those different dependencies, etc...If that's the kind of thing you enjoy it might be an okay choice for you. Those days of enjoying system fiddling are behind me and I just want to get on with doing my work. I am planning on installing ubuntu on a home machine just so i can get familiar with things like capistrano so maybe my opinion will change.

I'd highly suggest if you are going to do rails dev for any amount of time you seriously consider getting a Mac. If you value your time and sanity it will pay for itself almost instantly. Depending on how you value your time 10 hours of debugging windows/linux setup problems and you have spend as much as a Mac costs anyway.

Rails is a joy compared to what it replaces but it is a bit of a pain in that its proponents skip right past a lot of the boring but important stuff like documentation, compatibility issues and community building. It is way more powerful than other frameworks like Django but I sometimes look over at the Django documentation and community and sigh like a guy with a wild sexy girlfriend looking at his friend's plain but sane and stable wife. But then rails adds a feature and I go "Ohhh shiny!"

IMO the Rails Screencasts are better than the Peepcode screencasts. RubyPlus also has screencasts, mind you, they are bit rough around the edges. BuildingWebApps has a free online course that starts doing screencasts halfway through.

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

Iterating through a list in reverse order in java

You could use the concrete class LinkedList instead of the general interface List. Then you have a descendingIterator for iterating with the reverse direction.

LinkedList<String > linkedList;
for( Iterator<String > it = linkedList.descendingIterator(); it.hasNext(); ) {
    String text = it.next();
}

Don't know why there is no descendingIterator with ArrayList...

cannot resolve symbol javafx.application in IntelliJ Idea IDE

In IntelliJ Idea,

Check the following things are configured properly,

Step 1:

File -> Setting -> Plugins -> search javafx and make sure its enabled.

Step 2: Project Structure (Ctrl+Shift+Alt+s)

Platform Settings -> SDKs -> 1.8 -> Make sure Classpath should have "jre\lib\ext\jfxrt.jar"

Step 3:

Project Settings -> Project -> Project SDK - should be selected 1.8

Project Settings -> Project -> Project language level - configured as 8

Ubuntu: If not found jfxrt.jar in your SDKs then install sudo apt-get install openjfx

Storing C++ template function definitions in a .CPP file

This code is well-formed. You only have to pay attention that the definition of the template is visible at the point of instantiation. To quote the standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

How do I keep two side-by-side divs the same height?

I was having the same problem so i created this small function using jquery as jquery is part of every web application nowadays.

function fEqualizeHeight(sSelector) {
    var sObjects = $(sSelector);

    var iCount = sObjects.length;

    var iHeights = [];

    if (iCount > 0) {
        $(sObjects).each(function () {
            var sHeight = $(this).css('height');
            var iHeight = parseInt(sHeight.replace(/px/i,''));
            iHeights.push(iHeight);
        });

        iHeights.sort(function (a, b) {
            return a - b
        });

        var iMaxHeight = iHeights.pop();

        $(sSelector).each(function () {
            $(this).css({
                'height': iMaxHeight + 'px'
            });
        });
    }
}

You can call this function on page ready event

$(document).ready(function(){
   fEqualizeHeight('.columns');
});

I hope this works for you.

Java - how do I write a file to a specified directory

Use:

File file = new File("Z:\\results\\results.txt");

You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.

For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.

File file = new File("/home/userName/Documents/results.txt");

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

Simple test, accessing http://localhost:8000/hello?foo=bar#this-is-not-sent-to-server

python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"
Serving HTTP on 0.0.0.0 port 8000 ...
localhost - - [02/Jun/2009 12:48:47] code 404, message File not found
localhost - - [02/Jun/2009 12:48:47] "GET /hello?foo=bar HTTP/1.1" 404 -

The server receives the request without the #appendage - anything after the hash tag is simply an anchor lookup on the client.

You can find the anchor name used within the URL via javascript using, as an example:

<script>alert(window.location.hash);</script>

The parse_url() function in PHP can work if you already have the needed URL string including the fragment (http://codepad.org/BDqjtXix):

<?
echo parse_url("http://foo?bar#fizzbuzz",PHP_URL_FRAGMENT);
?>

Output: fizzbuzz

But I don't think PHP receives the fragment information because it's client-only.

Google Chrome default opening position and size

You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.

How do I obtain the frequencies of each value in an FFT?

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

What is "git remote add ..." and "git push origin master"?

Git remote add origin:

It centralises your source code to the other projects.It is developed based on Linux, complete open source and make your code useful to the other git users.we call it as reference

Pushes your code into git repository using remote url of the git hub.

Convert array to string in NodeJS

You're using an Array like an "associative array", which does not exist in JavaScript. Use an Object ({}) instead.

If you are going to continue with an array, realize that toString() will join all the numbered properties together separated by a comma. (the same as .join(",")).

Properties like a and b will not come up using this method because they are not in the numeric indexes. (ie. the "body" of the array)

In JavaScript, Array inherits from Object, so you can add and delete properties on it like any other object. So for an array, the numbered properties (they're technically just strings under the hood) are what counts in methods like .toString(), .join(), etc. Your other properties are still there and very much accessible. :)

Read Mozilla's documentation for more information about Arrays.

var aa = [];

// these are now properties of the object, but not part of the "array body"
aa.a = "A";
aa.b = "B";

// these are part of the array's body/contents
aa[0] = "foo";
aa[1] = "bar";

aa.toString(); // most browsers will say "foo,bar" -- the same as .join(",")

How to disable an input box using angular.js

You need to use ng-disabled directive

<input data-ng-model="userInf.username" 
       class="span12 editEmail" 
       type="text" 
       placeholder="[email protected]" 
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="<expression to disable>" />

How to get data by SqlDataReader.GetValue by column name

You can also do this.

//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName"); 
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);

ICommand MVVM implementation

I have written this article about the ICommand interface.

The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param) is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param)).

Requires the method to switching event CanExecuteChanged. It is called from the user interface elements for switching the state CanExecute() command.

public class ModelCommand : ICommand
{
    #region Constructors

    public ModelCommand(Action<object> execute)
        : this(execute, null) { }

    public ModelCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return _canExecute != null ? _canExecute(parameter) : true;
    }

    public void Execute(object parameter)
    {
        if (_execute != null)
            _execute(parameter);
    }

    public void OnCanExecuteChanged()
    {
        CanExecuteChanged(this, EventArgs.Empty);
    }

    #endregion

    private readonly Action<object> _execute = null;
    private readonly Predicate<object> _canExecute = null;
}

Generate .pem file used to set up Apple Push Notifications

it is very simple after exporting the Cert.p12 and key.p12, Please find below command for the generating 'apns' .pem file.

https://www.sslshopper.com/ssl-converter.html ?

command to create apns-dev.pem from Cert.pem and Key.pem
?    

openssl rsa -in Key.pem -out apns-dev-key-noenc.pem
?    

cat Cert.pem apns-dev-key-noenc.pem > apns-dev.pem

Above command is useful for both Sandbox and Production.

How to export data with Oracle SQL Developer?

If, at some point, you only need to export a single result set, just right click "on the data" (any column of any row) there you will find an export option. The wizard exports the complete result set regardless of what you selected

How to use componentWillMount() in React Hooks?

I wrote a custom hook that will run a function once before first render.

useBeforeFirstRender.js

import { useState, useEffect } from 'react'

export default (fun) => {
  const [hasRendered, setHasRendered] = useState(false)

  useEffect(() => setHasRendered(true), [hasRendered])

  if (!hasRendered) {
    fun()
  }
}

Usage:

import React, { useEffect } from 'react'
import useBeforeFirstRender from '../hooks/useBeforeFirstRender'


export default () => { 
  useBeforeFirstRender(() => {
    console.log('Do stuff here')
  })

  return (
    <div>
      My component
    </div>
  )
}

How to initialize struct?

  1. Will "length" ever deviate from the real length of "s". If the answer is no, then you don't need to store length, because strings store their length already, and you can just call s.Length.

  2. To get the syntax you asked for, you can implement an "implicit" operator like so:

    static implicit operator MyStruct(string s) {
        return new MyStruct(...);
    }
    
  3. The implicit operator will work, regardless of whether you make your struct mutable or not.

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

There is problem with Bootstrap version and jQuery version in my case.. I fixeed it by changing the version of Bootstrap and jQuery. thank you!!

How do you pass a function as a parameter in C?

Pass address of a function as parameter to another function as shown below

#include <stdio.h>

void print();
void execute(void());

int main()
{
    execute(print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void f()) // receive address of print
{
    f();
}

Also we can pass function as parameter using function pointer

#include <stdio.h>

void print();
void execute(void (*f)());

int main()
{
    execute(&print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void (*f)()) // receive address of print
{
    f();
}

Setting the classpath in java using Eclipse IDE

Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project

Format ints into string of hex

The most recent and in my opinion preferred approach is the f-string:

''.join(f'{i:02x}' for i in [1, 15, 255])

Format options

The old format style was the %-syntax:

['%02x'%i for i in [1, 15, 255]]

The more modern approach is the .format method:

 ['{:02x}'.format(i) for i in [1, 15, 255]]

More recently, from python 3.6 upwards we were treated to the f-string syntax:

[f'{i:02x}' for i in [1, 15, 255]]

Format syntax

Note that the f'{i:02x}' works as follows.

  • The first part before : is the input or variable to format.
  • The x indicates that the string should be hex. f'{100:02x}' is '64' and f'{100:02d}' is '1001'.
  • The 02 indicates that the string should be left-filled with 0's to length 2. f'{100:02x}' is '64' and f'{100:30x}' is ' 64'.

Pandas Replace NaN with blank/empty string

using keep_default_na=False should help you:

df = pd.read_csv(filename, keep_default_na=False)

How can I get the current screen orientation?

getActivity().getResources().getConfiguration().orientation

this command returns int value 1 for Portrait and 2 for Landscape

How to fit in an image inside span tag?

Try using a div tag and block for span!

<div>
  <span style="padding-right:3px; padding-top: 3px; display:block;">
    <img class="manImg" src="images/ico_mandatory.gif"></img>
  </span>
</div>

Can I set enum start value in Java?

The ordinal() function returns the relative position of the identifier in the enum. You can use this to obtain automatic indexing with an offset, as with a C-style enum.

Example:

public class TestEnum {
    enum ids {
        OPEN,
        CLOSE,
        OTHER;

        public final int value = 100 + ordinal();
    };

    public static void main(String arg[]) {
        System.out.println("OPEN:  " + ids.OPEN.value);
        System.out.println("CLOSE: " + ids.CLOSE.value);
        System.out.println("OTHER: " + ids.OTHER.value);
    }
};

Gives the output:

OPEN:  100
CLOSE: 101
OTHER: 102

Edit: just realized this is very similar to ggrandes' answer, but I will leave it here because it is very clean and about as close as you can get to a C style enum.

How to save all files from source code of a web site?

Try Winhttrack

...offline browser utility.

It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.

WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...

git - pulling from specific branch

Laravel documentation example:

git pull https://github.com/laravel/docs.git 5.8

based on the command format:

git pull origin <branch>

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

How do I get the coordinates of a mouse click on a canvas element?

Be wary while doing the coordinate conversion; there are multiple non-cross-browser values returned in a click event. Using clientX and clientY alone are not sufficient if the browser window is scrolled (verified in Firefox 3.5 and Chrome 3.0).

This quirks mode article provides a more correct function that can use either pageX or pageY or a combination of clientX with document.body.scrollLeft and clientY with document.body.scrollTop to calculate the click coordinate relative to the document origin.

UPDATE: Additionally, offsetLeft and offsetTop are relative to the padded size of the element, not the interior size. A canvas with the padding: style applied will not report the top-left of its content region as offsetLeft. There are various solutions to this problem; the simplest one may be to clear all border, padding, etc. styles on the canvas itself and instead apply them to a box containing the canvas.

Correctly determine if date string is a valid date in that format

Use in simple way with php prebuilt function:

function checkmydate($date) {
  $tempDate = explode('-', $date);
  // checkdate(month, day, year)
  return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}

Test

   checkmydate('2015-12-01'); //true
   checkmydate('2015-14-04'); //false

Is it possible that one domain name has multiple corresponding IP addresses?

Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

Example to get last article or any other element:

document.querySelector("article:last-child")

How to install php-curl in Ubuntu 16.04

To Install cURL 7.49.0 on Ubuntu 16.04 and Derivatives

wget http://curl.haxx.se/download/curl-7.49.0.tar.gz
tar -xvf curl-7.49.0.tar.gz
cd curl-7.49.0/
./configure
make
sudo make install

How do I convert a float number to a whole number in JavaScript?

Bit shift by 0 which is equivalent to division by 1

// >> or >>>
2.0 >> 0; // 2
2.0 >>> 0; // 2

How to generate a random string of 20 characters

I'd use this approach:

String randomString(final int length) {
    Random r = new Random(); // perhaps make it a class variable so you don't make a new one every time
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString();
}

If you want a byte[] you can do this:

byte[] randomByteString(final int length) {
    Random r = new Random();
    byte[] result = new byte[length];
    for(int i = 0; i < length; i++) {
        result[i] = r.nextByte();
    }
    return result;
}

Or you could do this

byte[] randomByteString(final int length) {
    Random r = new Random();
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString().getBytes();
}

How to send POST request in JSON using HTTPClient in Android?

In this answer I am using an example posted by Justin Grammens.

About JSON

JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.

The Parts
A fan object with email as a key and [email protected] as a value

{
  fan:
    {
      email : '[email protected]'
    }
}

So the object equivalent would be fan.email; or fan['email'];. Both would have the same value of '[email protected]'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.

public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
    //instantiates httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //url with the post data
    HttpPost httpost = new HttpPost(path);

    //convert parameters into JSON object
    JSONObject holder = getJsonObjectFromMap(params);

    //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);
    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    //Handles what is returned from the page 
    ResponseHandler responseHandler = new BasicResponseHandler();
    return httpclient.execute(httpost, responseHandler);
}

Map

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.

private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

    //all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //Stores JSON
    JSONObject holder = new JSONObject();

    //using the earlier example your first entry would get email
    //and the inner while would get the value which would be '[email protected]' 
    //{ fan: { email : '[email protected]' } }

    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();

        //Create a new map
        Map m = (Map)pairs.getValue();   

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        Iterator iter2 = m.entrySet().iterator();
        while (iter2.hasNext()) 
        {
            Map.Entry pairs2 = (Map.Entry)iter2.next();
            data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }

        //puts email and '[email protected]'  together in map
        holder.put(key, data);
    }
    return holder;
}

Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.

(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)

Update

I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.

"message failed to fetch from registry" while trying to install any module

You also need to install software-properties-common for add-apt-repository to work. so it will be

sudo apt-get purge nodejs npm
sudo apt-get install -y python-software-properties python g++ make software-properties-common
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

Java: get greatest common divisor

I used this method that I created when I was 14 years old.

    public static int gcd (int a, int b) {
        int s = 1;
        int ia = Math.abs(a);//<-- turns to absolute value
        int ib = Math.abs(b);
        if (a == b) {
            s = a;
        }else {
            while (ib != ia) {
                if (ib > ia) {
                    s = ib - ia;
                    ib = s;
                }else { 
                    s = ia - ib;
                    ia = s;
                }
            }
        }
        return s;
    }

Issue with adding common code as git submodule: "already exists in the index"

This happens if the .git file is missing in the target path. It happend to me after I executed git clean -f -d.

I had to delete all target folders showing in the message and then executing git submodule update --remote

How can I get the DateTime for the start of the week?

   d = DateTime.Now;
            int dayofweek =(int) d.DayOfWeek;
            if (dayofweek != 0)
            {
                d = d.AddDays(1 - dayofweek);
            }
            else { d = d.AddDays(-6); }

Can anyone explain python's relative imports?

Checking it out in python3:

python -V
Python 3.6.5

Example1:

.
+-- parent.py
+-- start.py
+-- sub
    +-- relative.py

- start.py
import sub.relative

- parent.py
print('Hello from parent.py')

- sub/relative.py
from .. import parent

If we run it like this(just to make sure PYTHONPATH is empty):

PYTHONPATH='' python3 start.py

Output:

Traceback (most recent call last):
  File "start.py", line 1, in <module>
    import sub.relative
  File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/relative.py

- sub/relative.py
import parent

If we run it like this:

PYTHONPATH='' python3 start.py

Output:

Hello from parent.py

Example2:

.
+-- parent.py
+-- sub
    +-- relative.py
    +-- start.py

- parent.py
print('Hello from parent.py')

- sub/relative.py
print('Hello from relative.py')

- sub/start.py
import relative
from .. import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 2, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/start.py:

- sub/start.py
import relative
import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 3, in <module>
    import parent
ModuleNotFoundError: No module named 'parent'

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Also it's better to use import from root folder, i.e.:

- sub/start.py
import sub.relative
import parent

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Remove a child with a specific attribute, in SimpleXML for PHP

Since I encountered the same fatal error as Gerry and I'm not familiar with DOM, I decided to do it like this:

$item = $xml->xpath("//seg[@id='A12']");
$page = $xml->xpath("/data");
$id = "A12";

if (  count($item)  &&  count($page) ) {
    $item = $item[0];
    $page = $page[0];

     // find the numerical index within ->children().
    $ch = $page->children();
    $ch_as_array = (array) $ch;

    if (  count($ch_as_array)  &&  isset($ch_as_array['seg'])  ) {
        $ch_as_array = $ch_as_array['seg'];
        $index_in_array = array_search($item, $ch_as_array);
        if (  ($index_in_array !== false)
          &&  ($index_in_array !== null)
          &&  isset($ch[$index_in_array])
          &&  ($ch[$index_in_array]['id'] == $id)  ) {

             // delete it!
            unset($ch[$index_in_array]);

            echo "<pre>"; var_dump($xml); echo "</pre>";
        }
    }  // end of ( if xml object successfully converted to array )
}  // end of ( valid item  AND  section )

How to load image (and other assets) in Angular an project?

Angular-cli includes the assets folder in the build options by default. I got this issue when the name of my images had spaces or dashes. For example :

  • 'my-image-name.png' should be 'myImageName.png'
  • 'my image name.png' should be 'myImageName.png'

If you put the image in the assets/img folder, then this line of code should work in your templates :

<img alt="My image name" src="./assets/img/myImageName.png">

If the issue persist just check if your Angular-cli config file and be sure that your assets folder is added in the build options.

Insert current date in datetime format mySQL

The best way to make it easier and efficient is this:

CREATE TABLE table_name (
field1,
..
..
time_updated timestamp default current_timestamp
)

Now, when you insert a row into table, you can skip this field (time_updated) as it will fill with current time as default value

Any shortcut to initialize all array elements to zero?

In c/cpp there is no shortcut but to initialize all the arrays with the zero subscript.Ex:

  int arr[10] = {0};

But in java there is a magic tool called Arrays.fill() which will fill all the values in an array with the integer of your choice.Ex:

  import java.util.Arrays;

    public class Main
    {
      public static void main(String[] args)
       {
         int ar[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
         Arrays.fill(ar, 10);
         System.out.println("Array completely filled" +                          
            " with 10\n" + Arrays.toString(ar));
   }
 }

Sublime Text 2: How do I change the color that the row number is highlighted?

For Sublime Text 3, all I had to do was add "highlight_line": true to my user settings file: Preferences -> Settings - User. It was only once that preference was set that all the color scheme lineHighlight settings took effect.

Hopefully this will save someone else some of this same flailing about.

Access parent URL from iframe

This worked for me to access the iframe src url.

window.document.URL

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

Remove spaces from std::string in C++

I'm afraid it's the best solution that I can think of. But you can use reserve() to pre-allocate the minimum required memory in advance to speed up things a bit. You'll end up with a new string that will probably be shorter but that takes up the same amount of memory, but you'll avoid reallocations.

EDIT: Depending on your situation, this may incur less overhead than jumbling characters around.

You should try different approaches and see what is best for you: you might not have any performance issues at all.

Using Panel or PlaceHolder

I weird bug* in visual studio 2010, if you put controls inside a Placeholder it does not render them in design view mode.

This is especially true for Hidenfields and Empty labels.

I would love to use placeholders instead of panels but I hate the fact I cant put other controls inside placeholders at design time in the GUI.

The provider is not compatible with the version of Oracle client

It would seem to me that though you have ODP with the Oracle Istant Client, the ODP may be trying to use the actual Oracle Client instead. Do you have a standard Oracle client installed on the machine as well? I recall Oracle being quite picky about when it came to multiple clients on the same machine.

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

It is important to define an id in the model

.DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Model(model => model.Id(p => p.id))
    )

Vuejs and Vue.set(), update array

VueJS can't pickup your changes to the state if you manipulate arrays like this.

As explained in Common Beginner Gotchas, you should use array methods like push, splice or whatever and never modify the indexes like this a[2] = 2 nor the .length property of an array.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    f: 'DD-MM-YYYY',_x000D_
    items: [_x000D_
      "10-03-2017",_x000D_
      "12-03-2017"_x000D_
    ]_x000D_
  },_x000D_
  methods: {_x000D_
_x000D_
    cha: function(index, item, what, count) {_x000D_
      console.log(item + " index > " + index);_x000D_
      val = moment(this.items[index], this.f).add(count, what).format(this.f);_x000D_
_x000D_
      this.items.$set(index, val)_x000D_
      console.log("arr length:  " + this.items.length);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<div id="app">_x000D_
  <ul>_x000D_
    <li v-for="(index, item) in items">_x000D_
      <br><br>_x000D_
      <button v-on:click="cha(index, item, 'day', -1)">_x000D_
      - day</button> {{ item }}_x000D_
      <button v-on:click="cha(index, item, 'day', 1)">_x000D_
      + day</button>_x000D_
      <br><br>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert an NSTimeInterval (seconds) into minutes

pseudo-code:

minutes = floor(326.4/60)
seconds = round(326.4 - minutes * 60)

Disable Scrolling on Body

HTML css works fine if body tag does nothing you can write as well

<body scroll="no" style="overflow: hidden">

In this case overriding should be on the body tag, it is easier to control but sometimes gives headaches.

animating addClass/removeClass with jQuery

Although, the question is fairly old, I'm adding info not present in other answers.

The OP is using stop() to stop the current animation as soon as the event completes. However, using the right mix of parameters with the function should help. eg. stop(true,true) or stop(true,false) as this affects the queued animations well.

The following link illustrates a demo that shows the different parameters available with stop() and how they differ from finish().

http://api.jquery.com/finish/

Although the OP had no issues using JqueryUI, this is for other users who may come across similar scenarios but cannot use JqueryUI/need to support IE7 and 8 too.

How do I get the path of a process in Unix / Linux

thanks : Kiwy
with AIX:

getPathByPid()
{
    if [[ -e /proc/$1/object/a.out ]]; then
        inode=`ls -i /proc/$1/object/a.out 2>/dev/null | awk '{print $1}'`
        if [[ $? -eq 0 ]]; then
            strnode=${inode}"$"
            strNum=`ls -li /proc/$1/object/ 2>/dev/null | grep $strnode | awk '{print $NF}' | grep "[0-9]\{1,\}\.[0-9]\{1,\}\."`
            if [[ $? -eq 0 ]]; then
                # jfs2.10.6.5869
                n1=`echo $strNum|awk -F"." '{print $2}'`
                n2=`echo $strNum|awk -F"." '{print $3}'`
                # brw-rw----    1 root     system       10,  6 Aug 23 2013  hd9var
                strexp="^b.*"$n1,"[[:space:]]\{1,\}"$n2"[[:space:]]\{1,\}.*$"   # "^b.*10, \{1,\}5 \{1,\}.*$"
                strdf=`ls -l /dev/ | grep $strexp | awk '{print $NF}'`
                if [[ $? -eq 0 ]]; then
                    strMpath=`df | grep $strdf | awk '{print $NF}'`
                    if [[ $? -eq 0 ]]; then
                        find $strMpath -inum $inode 2>/dev/null
                        if [[ $? -eq 0 ]]; then
                            return 0
                        fi
                    fi
                fi
            fi
        fi
    fi
    return 1
}

Open Facebook page from Android app?

I have created a method to open facebook page into facebook app, if app is not existing then opening in chrome

    String socailLink="https://www.facebook.com/kfc";
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String facebookUrl = Utils.getFacebookUrl(getActivity(), socailLink);
    if (facebookUrl == null || facebookUrl.length() == 0) {
        Log.d("facebook Url", " is coming as " + facebookUrl);
        return;
    }
    intent.setData(Uri.parse(facebookUrl));
    startActivity(intent);

Utils.class add these method

public static String getFacebookUrl(FragmentActivity activity, String facebook_url) {
    if (activity == null || activity.isFinishing()) return null;

    PackageManager packageManager = activity.getPackageManager();
    try {
        int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
        if (versionCode >= 3002850) { //newer versions of fb app
            Log.d("facebook api", "new");
            return "fb://facewebmodal/f?href=" + facebook_url;
        } else { //older versions of fb app
            Log.d("facebook api", "old");
            return "fb://page/" + splitUrl(activity, facebook_url);
        }
    } catch (PackageManager.NameNotFoundException e) {
        Log.d("facebook api", "exception");
        return facebook_url; //normal web url
    }
}

and this

 /***
 * this method used to get the facebook profile name only , this method split domain into two part index 0 contains https://www.facebook.com and index 1 contains after / part
 * @param context contain context
 * @param url contains facebook url like https://www.facebook.com/kfc
 * @return if it successfully split then return "kfc"
 *
 * if exception in splitting then return "https://www.facebook.com/kfc"
 *
 */
 public static String splitUrl(Context context, String url) {
    if (context == null) return null;
    Log.d("Split string: ", url + " ");
    try {
        String splittedUrl[] = url.split(".com/");
        Log.d("Split string: ", splittedUrl[1] + " ");
        return splittedUrl.length == 2 ? splittedUrl[1] : url;
    } catch (Exception ex) {
        return url;
    }
}

Error:(1, 0) Plugin with id 'com.android.application' not found

Check the spelling, mine was 'com.android.aplication'

Git for beginners: The definitive practical guide

How to track remote branches

Assuming there is a remote repository that you cloned your local repository from and also assuming that there is a branch named 'some_branch' on that remote repository, here is how to track it locally:

# list remote branches
git branch -r

# start tracking one remote branch
git branch --track some_branch origin/some_branch

# change to the branch locally
git checkout some_branch

# make changes and commit them locally
....

# push your changes to the remote repository:
git push

Bootstrap push div content to new line

Do a row div.

Like this:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
        <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to compare DateTime without time via LINQ?

The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
      && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)

It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

Does document.body.innerHTML = "" clear the web page?

To expound on Douwem's answer, in your script tag, put your code in an onload:

<script type="text/javascript">
    window.onload=function(){
       document.body.innerHTML = "";
    }
</script>

Python Turtle, draw text with on screen with larger font

You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..

But another question is this: How do you set the color of the text You write?

Answer: You use the turtle.color() method or turtle.fillcolor(), like this:

turtle.fillcolor("blue")

or just:

turtle.color("orange")

These calls must come before the turtle.write() command..

NodeJS - Error installing with NPM

As commented below you may not need to install VS on windows, check this out

https://github.com/nodejs/node-gyp/issues/629#issuecomment-153196245

UPDATED 02/2016

Some npm plugins need node-gyp to be installed.

However, node-gyp has it's own dependencies (from the github page):

enter image description here

UPDATED 09/2016

If you're using Windows you can now install all node-gyp dependencies with single command (NOTE: Run As Admin in Windows PowerShell):

 $ npm install --global --production windows-build-tools

and then install the package

 $ npm install --global node-gyp

UPDATED 06/2018

https://github.com/nodejs/node-gyp/issues/809#issuecomment-155019383

Delete your $HOME/.node-gyp directory and try again.

See full documentation here: node-gyp

Regex Letters, Numbers, Dashes, and Underscores

Your expression should already match dashes, because the final - will not be interpreted as a range operator (since the range has no end). To add underscores as well, try:

([A-Za-z0-9_-]+)

How do I set browser width and height in Selenium WebDriver?

Here is firefox profile default prefs from python selenium 2.31.0 firefox_profile.py

and type "about:config" in firefox address bar to see all prefs

reference to the entries in about:config: http://kb.mozillazine.org/About:config_entries

DEFAULT_PREFERENCES = {
    "app.update.auto": "false",
    "app.update.enabled": "false",
    "browser.download.manager.showWhenStarting": "false",
    "browser.EULA.override": "true",
    "browser.EULA.3.accepted": "true",
    "browser.link.open_external": "2",
    "browser.link.open_newwindow": "2",
    "browser.offline": "false",
    "browser.safebrowsing.enabled": "false",
    "browser.search.update": "false",
    "extensions.blocklist.enabled": "false",
    "browser.sessionstore.resume_from_crash": "false",
    "browser.shell.checkDefaultBrowser": "false",
    "browser.tabs.warnOnClose": "false",
    "browser.tabs.warnOnOpen": "false",
    "browser.startup.page": "0",
    "browser.safebrowsing.malware.enabled": "false",
    "startup.homepage_welcome_url": "\"about:blank\"",
    "devtools.errorconsole.enabled": "true",
    "dom.disable_open_during_load": "false",
    "extensions.autoDisableScopes" : 10,
    "extensions.logging.enabled": "true",
    "extensions.update.enabled": "false",
    "extensions.update.notifyUser": "false",
    "network.manage-offline-status": "false",
    "network.http.max-connections-per-server": "10",
    "network.http.phishy-userpass-length": "255",
    "offline-apps.allow_by_default": "true",
    "prompts.tab_modal.enabled": "false",
    "security.fileuri.origin_policy": "3",
    "security.fileuri.strict_origin_policy": "false",
    "security.warn_entering_secure": "false",
    "security.warn_entering_secure.show_once": "false",
    "security.warn_entering_weak": "false",
    "security.warn_entering_weak.show_once": "false",
    "security.warn_leaving_secure": "false",
    "security.warn_leaving_secure.show_once": "false",
    "security.warn_submit_insecure": "false",
    "security.warn_viewing_mixed": "false",
    "security.warn_viewing_mixed.show_once": "false",
    "signon.rememberSignons": "false",
    "toolkit.networkmanager.disable": "true",
    "toolkit.telemetry.enabled": "false",
    "toolkit.telemetry.prompted": "2",
    "toolkit.telemetry.rejected": "true",
    "javascript.options.showInConsole": "true",
    "browser.dom.window.dump.enabled": "true",
    "webdriver_accept_untrusted_certs": "true",
    "webdriver_enable_native_events": "true",
    "webdriver_assume_untrusted_issuer": "true",
    "dom.max_script_run_time": "30",
    }

IF EXISTS in T-SQL

There's no need for "else" in this case:

IF EXISTS(SELECT *  FROM  table1  WHERE Name='John' ) return 1
return 0

How do I add an integer value with javascript (jquery) to a value that's returning a string?

In regards to the octal misinterpretation of .js - I just used this...

parseInt(parseFloat(nv))

and after testing with leading zeros, came back everytime with the correct representation.

hope this helps.

What data is stored in Ephemeral Storage of Amazon EC2 instance?

According to AWS documentation [https://aws.amazon.com/premiumsupport/knowledge-center/instance-store-vs-ebs/] instance store volumes is not persistent through instance stops, terminations, or hardware failures. Any AMI created from instance stored disk doesn't contain data present in instance store so all instances launched by this AMI will not have data stored in instance store. Instance store can be used as cache for applications running on instance, for all persistent data you should use EBS.

convert json ipython notebook(.ipynb) to .py file

You definitely can achieve that with nbconvert using the following command:

jupyter nbconvert --to python while.ipynb 

However, having used it personally I would advise against it for several reasons:

  1. It's one thing to be able to convert to simple Python code and another to have all the right abstractions, classes access and methods set up. If the whole point of you converting your notebook code to Python is getting to a state where your code and notebooks are maintainable for the long run, then nbconvert alone will not suffice. The only way to do that is by manually going through the codebase.
  2. Notebooks inherently promote writing code which is not maintainable (https://docs.google.com/presentation/d/1n2RlMdmv1p25Xy5thJUhkKGvjtV-dkAIsUXP-AL4ffI/edit#slide=id.g3d7fe085e7_0_21). Using nbconvert on top might just prove to be a bandaid. Specific examples of where it promotes not-so-maintainable code are imports might be sprayed throughout, hard coded paths are not in one simple place to view, class abstractions might not be present, etc.
  3. nbconvert still mixes execution code and library code.
  4. Comments are still not present (probably were not in the notebook).
  5. There is still a lack of unit tests etc.

So to summarize, there is not good way to out of the box convert python notebooks to maintainable, robust python modularized code, the only way is to manually do surgery.

Transparent color of Bootstrap-3 Navbar

  1. Go to http://px64.net/
  2. mess around with opacity, add your image or choose color.
  3. copy either html or css(css is easier) the site spits out.
  4. Select your element aka the navbar.

  5. .navbar{ background-image:url(link that the site provides); background-repeat:repeat;

  6. Enjoy.

How do you implement a good profanity filter?

I agree with the futility of the subject, but if you have to have a filter, check out Ning's Boxwood:

Boxwood is a PHP extension for fast replacement of multiple words in a piece of text. It supports case-sensitive and case-insensitive matching. It requires that the text it operates on be encoded as UTF-8.

Also see this blog post for more details:

With Boxwood, you can have your list of search terms be as long as you like -- the search and replace algorithm doesn't get slower with more words on the list of words to look for. It works by building a trie of all the search terms and then scans your subject text just once, walking down elements of the trie and comparing them to characters in your text. It supports US-ASCII and UTF-8, case-sensitive or insensitive matching, and has some English-centric word boundary checking logic.

Fade In Fade Out Android Animation in Java

As I believe in the power of XML (for layouts), this is the equivalent for the accepted answer, but purely as an animation resource:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:interpolator/accelerate_decelerate"
    android:fillAfter="true">
    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:duration="1000" />
    <alpha
        android:fromAlpha="1"
        android:toAlpha="0"
        android:duration="1000"
        android:startOffset="1000"/>
</set>

The fillAfter is for the fade to remain after completing the animation. The interpolator handles interpolation of the animations, as you can guess. You can also use other types of interpolators, like Linear or Overshoot.

Be sure to start your animation on your view:

yourView.startAnimation(AnimationUtils.loadAnimation(co??ntext, R.anim.fade));

Location Services not working in iOS 8

According to the Apple docs:

As of iOS 8, the presence of a NSLocationWhenInUseUsageDescription or a NSLocationAlwaysUsageDescription key value in your app's Info.plist file is required. It's then also necessary to request permission from the user prior to registering for location updates, either by calling [self.myLocationManager requestWhenInUseAuthorization] or [self.myLocationManager requestAlwaysAuthorization] depending on your need. The string you entered into the Info.plist will then be displayed in the ensuing dialog.

If the user grants permission, it's business as usual. If they deny permission, then the delegate is not informed of location updates.

Can I use Homebrew on Ubuntu?

The following steps worked for me:

  • Clone it from github

    git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew
    
  • Open your .bash_profile file using vi ~/.bash_profile

  • Add these lines

    export PATH="$HOME/.linuxbrew/bin:$PATH"
    export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
    export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"
    
  • Then type the following lines in your terminal

    export PATH=$HOME/.linuxbrew/bin:$PATH
    hash -r
    

Yes, it is done. Type brew in your terminal to check its existence.

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

I've had the same error and I solve it with: git merge -s recursive -X theirs origin/master

Bootstrap - dropdown menu not working?

This is a Rails specific answer, but I had this same problem with Bootstrap dropdown menus in my Rails app. What fixed it was adding this to app/assets/javascripts/application.js:

//= require bootstrap

Hope that helps someone.

How to download a file via FTP with Python ftplib

The ftplib module in the Python standard library can be compared to assembler. Use a high level library like: https://pypi.python.org/pypi/ftputil

Exact time measurement for performance testing

As others said, Stopwatch should be the right tool for this. There can be few improvements made to it though, see this thread specifically: Benchmarking small code samples in C#, can this implementation be improved?.

I have seen some useful tips by Thomas Maierhofer here

Basically his code looks like:

//prevent the JIT Compiler from optimizing Fkt calls away
long seed = Environment.TickCount;

//use the second Core/Processor for the test
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);

//prevent "Normal" Processes from interrupting Threads
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

//prevent "Normal" Threads from interrupting this thread
Thread.CurrentThread.Priority = ThreadPriority.Highest;

//warm up
method();

var stopwatch = new Stopwatch()
for (int i = 0; i < repetitions; i++)
{
    stopwatch.Reset();
    stopwatch.Start();
    for (int j = 0; j < iterations; j++)
        method();
    stopwatch.Stop();
    print stopwatch.Elapsed.TotalMilliseconds;
}

Another approach is to rely on Process.TotalProcessTime to measure how long the CPU has been kept busy running the very code/process, as shown here This can reflect more real scenario since no other process affects the measurement. It does something like:

 var start = Process.GetCurrentProcess().TotalProcessorTime;
 method();
 var stop = Process.GetCurrentProcess().TotalProcessorTime;
 print (end - begin).TotalMilliseconds;

A naked, detailed implementation of the samething can be found here.

I wrote a helper class to perform both in an easy to use manner:

public class Clock
{
    interface IStopwatch
    {
        bool IsRunning { get; }
        TimeSpan Elapsed { get; }

        void Start();
        void Stop();
        void Reset();
    }



    class TimeWatch : IStopwatch
    {
        Stopwatch stopwatch = new Stopwatch();

        public TimeSpan Elapsed
        {
            get { return stopwatch.Elapsed; }
        }

        public bool IsRunning
        {
            get { return stopwatch.IsRunning; }
        }



        public TimeWatch()
        {
            if (!Stopwatch.IsHighResolution)
                throw new NotSupportedException("Your hardware doesn't support high resolution counter");

            //prevent the JIT Compiler from optimizing Fkt calls away
            long seed = Environment.TickCount;

            //use the second Core/Processor for the test
            Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);

            //prevent "Normal" Processes from interrupting Threads
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

            //prevent "Normal" Threads from interrupting this thread
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
        }



        public void Start()
        {
            stopwatch.Start();
        }

        public void Stop()
        {
            stopwatch.Stop();
        }

        public void Reset()
        {
            stopwatch.Reset();
        }
    }



    class CpuWatch : IStopwatch
    {
        TimeSpan startTime;
        TimeSpan endTime;
        bool isRunning;



        public TimeSpan Elapsed
        {
            get
            {
                if (IsRunning)
                    throw new NotImplementedException("Getting elapsed span while watch is running is not implemented");

                return endTime - startTime;
            }
        }

        public bool IsRunning
        {
            get { return isRunning; }
        }



        public void Start()
        {
            startTime = Process.GetCurrentProcess().TotalProcessorTime;
            isRunning = true;
        }

        public void Stop()
        {
            endTime = Process.GetCurrentProcess().TotalProcessorTime;
            isRunning = false;
        }

        public void Reset()
        {
            startTime = TimeSpan.Zero;
            endTime = TimeSpan.Zero;
        }
    }



    public static void BenchmarkTime(Action action, int iterations = 10000)
    {
        Benchmark<TimeWatch>(action, iterations);
    }

    static void Benchmark<T>(Action action, int iterations) where T : IStopwatch, new()
    {
        //clean Garbage
        GC.Collect();

        //wait for the finalizer queue to empty
        GC.WaitForPendingFinalizers();

        //clean Garbage
        GC.Collect();

        //warm up
        action();

        var stopwatch = new T();
        var timings = new double[5];
        for (int i = 0; i < timings.Length; i++)
        {
            stopwatch.Reset();
            stopwatch.Start();
            for (int j = 0; j < iterations; j++)
                action();
            stopwatch.Stop();
            timings[i] = stopwatch.Elapsed.TotalMilliseconds;
            print timings[i];
        }
        print "normalized mean: " + timings.NormalizedMean().ToString();
    }

    public static void BenchmarkCpu(Action action, int iterations = 10000)
    {
        Benchmark<CpuWatch>(action, iterations);
    }
}

Just call

Clock.BenchmarkTime(() =>
{
    //code

}, 10000000);

or

Clock.BenchmarkCpu(() =>
{
    //code

}, 10000000);

The last part of the Clock is the tricky part. If you want to display the final timing, its up to you to choose what sort of timing you want. I wrote an extension method NormalizedMean which gives you the mean of the read timings discarding the noise. I mean I calculate the the deviation of each timing from the actual mean, and then I discard the values which was farer (only the slower ones) from the mean of deviation (called absolute deviation; note that its not the often heard standard deviation), and finally return the mean of remaining values. This means, for instance, if timed values are { 1, 2, 3, 2, 100 } (in ms or whatever), it discards 100, and returns the mean of { 1, 2, 3, 2 } which is 2. Or if timings are { 240, 220, 200, 220, 220, 270 }, it discards 270, and returns the mean of { 240, 220, 200, 220, 220 } which is 220.

public static double NormalizedMean(this ICollection<double> values)
{
    if (values.Count == 0)
        return double.NaN;

    var deviations = values.Deviations().ToArray();
    var meanDeviation = deviations.Sum(t => Math.Abs(t.Item2)) / values.Count;
    return deviations.Where(t => t.Item2 > 0 || Math.Abs(t.Item2) <= meanDeviation).Average(t => t.Item1);
}

public static IEnumerable<Tuple<double, double>> Deviations(this ICollection<double> values)
{
    if (values.Count == 0)
        yield break;

    var avg = values.Average();
    foreach (var d in values)
        yield return Tuple.Create(d, avg - d);
}

Commit empty folder structure (with git)

Simply add file named as .keep in images folder.you can now stage and commit and also able to add folder to version control.

Create a empty file in images folder $ touch .keep

$ git status

On branch master
Your branch is up-to-date with 'origin/master'.

Untracked files:
  (use "git add ..." to include in what will be committed)

    images/

nothing added to commit but untracked files present (use "git add" to track)

$ git add .

$ git commit -m "adding empty folder"

Django MEDIA_URL and MEDIA_ROOT

UPDATE for Django >= 1.7

Per Django 2.1 documentation: Serving files uploaded by a user during development

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

You no longer need if settings.DEBUG as Django will handle ensuring this is only used in Debug mode.


ORIGINAL answer for Django <= 1.6

Try putting this into your urls.py

from django.conf import settings

# ... your normal urlpatterns here

if settings.DEBUG:
    # static files (images, css, javascript, etc.)
    urlpatterns += patterns('',
        (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.MEDIA_ROOT}))

With this you can serve the static media from Django when DEBUG = True (when you run on local computer) but you can let your web server configuration serve static media when you go to production and DEBUG = False

HTML form with two submit buttons and two "target" attributes

In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.

<!DOCTYPE html>
<html>
  <body>
    <form>
      <input type="submit" formaction="firsttarget.php" value="Submit to first" />
      <input type="submit" formaction="secondtarget.php" value="Submit to second" />
    </form>
  </body>
</html>

anaconda update all possible packages?

I solved this problem with conda and pip.

Firstly, I run:

conda uninstall qt and conda uninstall matplotlib and conda uninstall PyQt5

After that, I opened the cmd and run this code that

pip uninstall qt , pip uninstall matplotlib , pip uninstall PyQt5

Lastly, You should install matplotlib in pip by this code that pip install matplotlib

What character represents a new line in a text area

It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:

The element's value is defined to be the element's raw value with the following transformation applied:

Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.

Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:

Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.

To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Since Java 8, you can use:

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

  1. If you have released to Apple TestFlight for testing

    You have to click the link each time and select No, only after that, your tester can see the build. This is quite annoying if you want to get your build delivered as soon as possible.

    enter image description here

  2. Do this for the next build, (If do this before the build then this error will not occur)

The solution is add the following setting to your iOS Info.plist:

    <key>ITSAppUsesNonExemptEncryption</key>
    <false/>

enter image description here

Can not add "Missing Compliance", see this Missing Compliance

Get img src with PHP

I know people say you shouldn't use regular expressions to parse HTML, but in this case I find it perfectly fine.

$string = '<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />';
preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $string, $result);
$foo = array_pop($result);

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

Apple has made following changes so download new certificate developer.apple.com

renewed certificate and place it as below screen shots .In the keychain as below screen shots click on system and then certificate. Delete the expired certificate . Then drag and drop the AppleWWDRCA.cer that you downloaded from above link

Apple Worldwide Developer Relations Intermediate Certificate Expiration

To help protect customers and developers, we require that all third party apps, passes for Apple Wallet, Safari Extensions, Safari Push Notifications, and App Store purchase receipts are signed by a trusted certificate authority. The Apple Worldwide Developer Relations Certificate Authority issues the certificates you use to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

Since different methods can be used for validating receipts and delivering remote notifications, we recommend that you test your services to ensure no implementation-specific issues exist. Your apps may experience receipt verification failure if the receipt checking code makes incorrect assumptions about the certificate. Make sure that your code adheres to the Receipt Validation Programming Guide and resolve all receipt validation issues before February 14, 2016.

enter image description here

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

rsync: how can I configure it to create target directory on server?

This answer uses bits of other answers, but hopefully it'll be a bit clearer as to the circumstances. You never specified what you were rsyncing - a single directory entry or multiple files.

So let's assume you are moving a source directory entry across, and not just moving the files contained in it.

Let's say you have a directory locally called data/myappdata/ and you have a load of subdirectories underneath this. You have data/ on your target machine but no data/myappdata/ - this is easy enough:

rsync -rvv /path/to/data/myappdata/ user@host:/remote/path/to/data/myappdata

You can even use a different name for the remote directory:

rsync -rvv --recursive /path/to/data/myappdata user@host:/remote/path/to/data/newdirname

If you're just moving some files and not moving the directory entry that contains them then you would do:

rsync -rvv /path/to/data/myappdata/*.txt user@host:/remote/path/to/data/myappdata/

and it will create the myappdata directory for you on the remote machine to place your files in. Again, the data/ directory must exist on the remote machine.

Incidentally, my use of -rvv flag is to get doubly verbose output so it is clear about what it does, as well as the necessary recursive behaviour.

Just to show you what I get when using rsync (3.0.9 on Ubuntu 12.04)

$ rsync -rvv *.txt [email protected]:/tmp/newdir/
opening connection using: ssh -l user remote.machine rsync --server -vvre.iLsf . /tmp/newdir/
[email protected]'s password:
sending incremental file list
created directory /tmp/newdir
delta-transmission enabled
bar.txt
foo.txt
total: matches=0  hash_hits=0  false_alarms=0 data=0

Hope this clears this up a little bit.

Visual Studio loading symbols

For me, it seems related to breakpoints, as indicated in the accepted answer. However, I found two workarounds that did not involve deleting all the breakpoints:

  • Restarting Visual Studio seemed to fix it temporarily.
  • Clicking the "X" button to close Visual Studio while debugging causes the "Do you want to stop debugging?" message box to pop up; while this message box is up, the symbols load at ordinary speeds. Once all the symbols are loaded, you can click "No" to cancel the close.

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

mysql: see all open connections to a given database?

If you're running a *nix system, also consider mytop.

To limit the results to one database, press "d" when it's running then type in the database name.

AngularJS: Service vs provider vs factory

JS Fiddle Demo

" Hello world " example with factory / service / provider:

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
//service style, probably the simplest one_x000D_
myApp.service('helloWorldFromService', function() {_x000D_
    this.sayHello = function() {_x000D_
        return "Hello, World!";_x000D_
    };_x000D_
});_x000D_
_x000D_
//factory style, more involved but more sophisticated_x000D_
myApp.factory('helloWorldFromFactory', function() {_x000D_
    return {_x000D_
        sayHello: function() {_x000D_
            return "Hello, World!";_x000D_
        }_x000D_
    };_x000D_
});_x000D_
    _x000D_
//provider style, full blown, configurable version     _x000D_
myApp.provider('helloWorld', function() {_x000D_
_x000D_
    this.name = 'Default';_x000D_
_x000D_
    this.$get = function() {_x000D_
        var name = this.name;_x000D_
        return {_x000D_
            sayHello: function() {_x000D_
                return "Hello, " + name + "!";_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
_x000D_
    this.setName = function(name) {_x000D_
        this.name = name;_x000D_
    };_x000D_
});_x000D_
_x000D_
//hey, we can configure a provider!            _x000D_
myApp.config(function(helloWorldProvider){_x000D_
    helloWorldProvider.setName('World');_x000D_
});_x000D_
        _x000D_
_x000D_
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {_x000D_
    _x000D_
    $scope.hellos = [_x000D_
        helloWorld.sayHello(),_x000D_
        helloWorldFromFactory.sayHello(),_x000D_
        helloWorldFromService.sayHello()];_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="myApp">_x000D_
<div ng-controller="MyCtrl">_x000D_
    {{hellos}}_x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Get file name from URL

Instead of reinventing the wheel, how about using Apache commons-io:

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilTest {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://www.example.com/some/path/to/a/file.xml?foo=bar#test");

        System.out.println(FilenameUtils.getBaseName(url.getPath())); // -> file
        System.out.println(FilenameUtils.getExtension(url.getPath())); // -> xml
        System.out.println(FilenameUtils.getName(url.getPath())); // -> file.xml
    }

}

Remove a character at a certain position in a string - javascript

If you omit the particular index character then use this method

function removeByIndex(str,index) {
      return str.slice(0,index) + str.slice(index+1);
}
    
var str = "Hello world", index=3;
console.log(removeByIndex(str,index));

// Output: "Helo world"

Command to get latest Git commit hash from a branch

git log -n 1 [branch_name]

branch_name (may be remote or local branch) is optional. Without branch_name, it will show the latest commit on the current branch.

For example:

git log -n 1
git log -n 1 origin/master
git log -n 1 some_local_branch

git log -n 1 --pretty=format:"%H"  #To get only hash value of commit

java.sql.SQLException: Exhausted Resultset

When there is no records returned from Database for a particular condition and When I tried to access the rs.getString(1); I got this error "exhausted resultset".

Before the issue, my code was:

rs.next();
sNr= rs.getString(1);

After the fix:

while (rs.next()) {
    sNr = rs.getString(1);
}

Convert String to Carbon

You were almost there.

Remove protected $dates = ['license_expire']

and then change your LicenseExpire accessor to:

public function getLicenseExpireAttribute($date)
{
    return Carbon::parse($date);
}

This way it will return a Carbon instance no matter what. So for your form you would just have $employee->license_expire->format('Y-m-d') (or whatever format is required) and diffForHumans() should work on your home page as well.

Hope this helps!

Invoking a jQuery function after .each() has completed

what about

$(parentSelect).nextAll().fadeOut(200, function() { 
    $(this).remove(); 
}).one(function(){
    myfunction();
}); 

Algorithm to return all combinations of k elements from n

Short java solution:

import java.util.Arrays;

public class Combination {
    public static void main(String[] args){
        String[] arr = {"A","B","C","D","E","F"};
        combinations2(arr, 3, 0, new String[3]);
    }

    static void combinations2(String[] arr, int len, int startPosition, String[] result){
        if (len == 0){
            System.out.println(Arrays.toString(result));
            return;
        }       
        for (int i = startPosition; i <= arr.length-len; i++){
            result[result.length - len] = arr[i];
            combinations2(arr, len-1, i+1, result);
        }
    }       
}

Result will be

[A, B, C]
[A, B, D]
[A, B, E]
[A, B, F]
[A, C, D]
[A, C, E]
[A, C, F]
[A, D, E]
[A, D, F]
[A, E, F]
[B, C, D]
[B, C, E]
[B, C, F]
[B, D, E]
[B, D, F]
[B, E, F]
[C, D, E]
[C, D, F]
[C, E, F]
[D, E, F]

return, return None, and no return at all?

On the actual behavior, there is no difference. They all return None and that's it. However, there is a time and place for all of these. The following instructions are basically how the different methods should be used (or at least how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.

Using return None

This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function.

In the following example, we return person's mother if the person given is a human. If it's not a human, we return None since the person doesn't have a mother (let's suppose it's not an animal or something).

def get_mother(person):
    if is_human(person):
        return person.mother
    else:
        return None

Using return

This is used for the same reason as break in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even though you don't need it that often.

We've got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function because we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an alert. This could be done in many different ways and using return is probably not even the best way, but it's just an example to show how to use return for exiting a function.

def find_prisoner_with_knife(prisoners):
    for prisoner in prisoners:
        if "knife" in prisoner.items:
            prisoner.move_to_inquisition()
            return # no need to check rest of the prisoners nor raise an alert
    raise_alert()

Note: You should never do var = find_prisoner_with_knife(), since the return value is not meant to be caught.

Using no return at all

This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return in void functions in languages such as C++ or Java.

In the following example, we set person's mother's name and then the function exits after completing successfully.

def set_mother(person, mother):
    if is_human(person):
        person.mother = mother

Note: You should never do var = set_mother(my_person, my_mother), since the return value is not meant to be caught.