Programs & Examples On #Online repository

Usage of __slots__?

Quoting Jacob Hallen:

The proper use of __slots__ is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. [This use of __slots__ eliminates the overhead of one dict for every object.] While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.

Unfortunately there is a side effect to slots. They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies. This is bad, because the control freaks should be abusing the metaclasses and the static typing weenies should be abusing decorators, since in Python, there should be only one obvious way of doing something.

Making CPython smart enough to handle saving space without __slots__ is a major undertaking, which is probably why it is not on the list of changes for P3k (yet).

SQL multiple columns in IN clause

You could do like this:

SELECT city FROM user WHERE (firstName, lastName) IN (('a', 'b'), ('c', 'd'));

The sqlfiddle.

How do I get the Git commit count?

If you're just using one branch, such as master, I think this would work great:

git rev-list --full-history --all | wc -l

This will only output a number. You can alias it to something like

git revno

to make things really convenient. To do so, edit your .git/config file and add this in:

[alias]
    revno = "!git rev-list --full-history --all | wc -l"

This will not work on Windows. I do not know the equivalent of "wc" for that OS, but writing a Python script to do the counting for you would be a multi-platform solution.

EDIT: Get count between two commits:


I was looking for an answer that would show how to get the number of commits between two arbitrary revisions and didn't see any.

git rev-list --count [older-commit]..[newer-commit]

UTF-8 encoding problem in Spring MVC

There are some similar questions: Spring MVC response encoding issue, Custom HttpMessageConverter with @ResponseBody to do Json things.

However, my simple solution:

@RequestMapping(method=RequestMethod.GET,value="/GetMyList")
public ModelAndView getMyList(){
  String test = "ccždš";
  ...
  ModelAndView mav = new ModelAndView("html_utf8");
  mav.addObject("responseBody", test);
}

and the view html_utf8.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>${responseBody}

No additional classes and configuration.
And You can also create another view (for example json_utf8) for other content type.

Grouping into interval of 5 minutes within a time range

I came across the same issue.

I found that it is easy to group by any minute interval is just dividing epoch by minutes in amount of seconds and then either rounding or using floor to get ride of the remainder. So if you want to get interval in 5 minutes you would use 300 seconds.

    SELECT COUNT(*) cnt, 
    to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300) 
    AT TIME ZONE 'UTC' as interval_alias
    FROM TABLE_NAME GROUP BY interval_alias
interval_alias       cnt
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:45:00  8
2010-11-16 10:55:00  11 

This will return the data correctly group by the selected minutes interval; however, it will not return the intervals that don't contains any data. In order to get those empty intervals we can use the function generate_series.

    SELECT generate_series(MIN(date_trunc('hour',timestamp_column)),
    max(date_trunc('minute',timestamp_column)),'5m') as interval_alias FROM 
    TABLE_NAME

Result:

interval_alias       
-------------------    
2010-11-16 10:30:00  
2010-11-16 10:35:00
2010-11-16 10:40:00   
2010-11-16 10:45:00
2010-11-16 10:50:00   
2010-11-16 10:55:00   

Now to get the result with interval with zero occurrences we just outer join both result sets.

    SELECT series.minute as interval,  coalesce(cnt.amnt,0) as count from 
       (
       SELECT count(*) amnt,
       to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
       AT TIME ZONE 'UTC' as interval_alias
       from TABLE_NAME  group by interval_alias
       ) cnt
    
    RIGHT JOIN 
       (    
       SELECT generate_series(min(date_trunc('hour',timestamp_column)),
       max(date_trunc('minute',timestamp_column)),'5m') as minute from TABLE_NAME 
       ) series
  on series.minute = cnt.interval_alias

The end result will include the series with all 5 minute intervals even those that have no values.

interval             count
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:40:00  0
2010-11-16 10:45:00  8
2010-11-16 10:50:00  0 
2010-11-16 10:55:00  11 

The interval can be easily changed by adjusting the last parameter of generate_series. In our case we use '5m' but it could be any interval we want.

How to delete an element from an array in C#

If you want to remove all instances of 4 without needing to know the index:

LINQ: (.NET Framework 3.5)

int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();

Non-LINQ: (.NET Framework 2.0)

static bool isNotFour(int n)
{
    return n != 4;
}

int[] numbers = { 1, 3, 4, 9, 2 };
numbers = Array.FindAll(numbers, isNotFour).ToArray();

If you want to remove just the first instance:

LINQ: (.NET Framework 3.5)

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();

Non-LINQ: (.NET Framework 2.0)

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();

Edit: Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.

php delete a single file in directory

// This code was tested by me (Helio Barbosa)

    // this directory (../backup) is for try only.
    // it is necessary create it and put files into him.

    $hDir = '../backup';
    if ($handle = opendir( $hDir )) {
        echo "Manipulador de diretório: $handle\n";
        echo "Arquivos:\n";

        /* Esta é a forma correta de varrer o diretório */
        /* Here is the correct form to do find files into the directory */
        while (false !== ($file = readdir($handle))) {
            // echo($file . "</br>");
            $filepath = $hDir . "/" . $file ;
            // echo( $filepath . "</br>" );
            if(is_file($filepath))
            {
                echo("Deleting:" . $file . "</br>");
                unlink($filepath);
            }           
        }

        closedir($handle);
    }

C++ cout hex values?

There are different kinds of flags & masks you can use as well. Please refer http://www.cplusplus.com/reference/iostream/ios_base/setf/ for more information.

#include <iostream>
using namespace std;

int main()
{
    int num = 255;
    cout.setf(ios::hex, ios::basefield);
    cout << "Hex: " << num << endl;

    cout.unsetf(ios::hex);
    cout << "Original format: " << num << endl;

    return 0;
}

Display string multiple times

The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.

print(*3*('-',), sep='_')

Press enter in textbox to and execute button command

You can handle the keydown event of your TextBox control.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode==Keys.Enter)
    buttonSearch_Click(sender,e);
}

It works even when the button Visible property is set to false

Sorted collection in Java

with Java 8 Comparator, if we want to sort list then Here are the 10 most populated cities in the world and we want to sort it by name, as reported by Time. Osaka, Japan. ... Mexico City, Mexico. ... Beijing, China. ... São Paulo, Brazil. ... Mumbai, India. ... Shanghai, China. ... Delhi, India. ... Tokyo, Japan.

 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.List;

public class SortCityList {

    /*
     * Here are the 10 most populated cities in the world and we want to sort it by
     * name, as reported by Time. Osaka, Japan. ... Mexico City, Mexico. ...
     * Beijing, China. ... São Paulo, Brazil. ... Mumbai, India. ... Shanghai,
     * China. ... Delhi, India. ... Tokyo, Japan.
     */
    public static void main(String[] args) {
        List<String> cities = Arrays.asList("Osaka", "Mexico City", "São Paulo", "Mumbai", "Shanghai", "Delhi",
                "Tokyo");
        System.out.println("Before Sorting List is:-");
        System.out.println(cities);
        System.out.println("--------------------------------");

        System.out.println("After Use of List sort(String.CASE_INSENSITIVE_ORDER) & Sorting List is:-");
        cities.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println(cities);
        System.out.println("--------------------------------");
        System.out.println("After Use of List sort(Comparator.naturalOrder()) & Sorting List is:-");
        cities.sort(Comparator.naturalOrder());
        System.out.println(cities);

    }

}

JS search in object values

Modern Javascript

const objects = [
    {
        "foo" : "bar",
        "bar" : "sit"
    },
    {
        "foo" : "lorem",
        "bar" : "ipsum"
    },
    {
        "foo" : "dolor blor",
        "bar" : "amet blo"
    }
];

const keyword = 'o';

const results = objects.filter(object => Object.values(object).some(i => i.includes(keyword)));
console.log(results);

// results [{ foo: 'lorem', bar: 'ipsum' },{ foo: 'dolor blor', bar: 'amet blo' }]

How to sort a list of lists by a specific index of the inner list?

This is a job for itemgetter

>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]

It is also possible to use a lambda function here, however the lambda function is slower in this simple case

How to specify Memory & CPU limit in docker compose version 3

Docker Compose does not support the deploy key. It's only respected when you use your version 3 YAML file in a Docker Stack.

This message is printed when you add the deploy key to you docker-compose.yml file and then run docker-compose up -d

WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use docker stack deploy to deploy to a swarm.

The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:

Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.

How can I multiply and divide using only bit shifting and adding?

x << k == x multiplied by 2 to the power of k
x >> k == x divided by 2 to the power of k

You can use these shifts to do any multiplication operation. For example:

x * 14 == x * 16 - x * 2 == (x << 4) - (x << 1)
x * 12 == x * 8 + x * 4 == (x << 3) + (x << 2)

To divide a number by a non-power of two, I'm not aware of any easy way, unless you want to implement some low-level logic, use other binary operations and use some form of iteration.

How can I check if the array of objects have duplicate property values?

With Underscore.js A few ways with Underscore can be done. Here is one of them. Checking if the array is already unique.

function isNameUnique(values){
    return _.uniq(values, function(v){ return v.name }).length == values.length
}

With vanilla JavaScript By checking if there is no recurring names in the array.

function isNameUnique(values){
    var names = values.map(function(v){ return v.name });
    return !names.some(function(v){ 
        return names.filter(function(w){ return w==v }).length>1 
    });
}

How to force NSLocalizedString to use a specific language

for my case i have two localized file , ja and en

and i would like to force it to en if the preferred language in the system neither en or ja

i'm going to edit the main.m file

i 'll check whether the first preferred is en or ja , if not then i 'll change the second preferred language to en.

int main(int argc, char *argv[])
{

    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"AppleLanguages"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    NSString *lang = [[NSLocale preferredLanguages] objectAtIndex:0];

    if (![lang isEqualToString:@"en"]  &&  ![lang isEqualToString:@"ja"]){

        NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[NSLocale preferredLanguages]];
        [array replaceObjectAtIndex:1 withObject:@"en"];

        [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"AppleLanguages"];
        [[NSUserDefaults standardUserDefaults] synchronize];


    }

    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));


    }


}

How to check null objects in jQuery

if (typeof($("#btext" + i)) == 'object'){
    $("#btext" + i).text("Branch " + i);
}

Round a double to 2 decimal places

function Double round2(Double val) {
    return new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue();
}

Note the toString()!!!!

This is because BigDecimal converts the exact binary form of the double!!!

These are the various suggested methods and their fail cases.

// Always Good!
new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue() 

Double val = 260.775d; //EXPECTED 260.78
260.77 - WRONG - new BigDecimal(val).setScale(2,RoundingMode.HALF_UP).doubleValue()

Double val = 260.775d; //EXPECTED 260.78
260.77 - TRY AGAIN - Math.round(val * 100.d) / 100.0d  

Double val = 256.025d; //EXPECTED 256.03d
256.02 - OOPS - new DecimalFormat("0.00").format(val) 
// By default use half even, works if you change mode to half_up 

Double val = 256.025d; //EXPECTED 256.03d
256.02 - FAIL - (int)(val * 100 + 0.5) / 100.0;

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Eliminating NAs from a ggplot

You can use the function subset inside ggplot2. Try this

library(ggplot2)

data("iris")
iris$Sepal.Length[5:10] <- NA # create some NAs for this example

ggplot(data=subset(iris, !is.na(Sepal.Length)), aes(x=Sepal.Length)) + 
geom_bar(stat="bin")

JPA eager fetch does not join

"mxc" is right. fetchType just specifies when the relation should be resolved.

To optimize eager loading by using an outer join you have to add

@Fetch(FetchMode.JOIN)

to your field. This is a hibernate specific annotation.

Insert picture into Excel cell

While my recommendation is to take advantage of the automation available from Doality.com specifically Picture Manager for Excel

The following vba code should meet your criteria. Good Luck!

Add a Button Control to your Excel Workbook and then double click on the button in order to get to the VBA Code -->

Sub Button1_Click()
    Dim filePathCell As Range
    Dim imageLocationCell As Range
    Dim filePath As String

    Set filePathCell = Application.InputBox(Prompt:= _
        "Please select the cell that contains the reference path to your image file", _
            Title:="Specify File Path", Type:=8)

     Set imageLocationCell = Application.InputBox(Prompt:= _
        "Please select the cell where you would like your image to be inserted.", _
            Title:="Image Cell", Type:=8)

    If filePathCell Is Nothing Then
       MsgBox ("Please make a selection for file path")
       Exit Sub
    Else
      If filePathCell.Cells.Count > 1 Then
        MsgBox ("Please select only a single cell that contains the file location")
        Exit Sub
      Else
        filePath = Cells(filePathCell.Row, filePathCell.Column).Value
      End If
    End If

    If imageLocationCell Is Nothing Then
       MsgBox ("Please make a selection for image location")
       Exit Sub
    Else
      If imageLocationCell.Cells.Count > 1 Then
        MsgBox ("Please select only a single cell where you want the image to be populated")
        Exit Sub
      Else
        InsertPic filePath, imageLocationCell
        Exit Sub
      End If
    End If
End Sub

Then create your Insert Method as follows:

Private Sub InsertPic(filePath As String, ByVal insertCell As Range)
    Dim xlShapes As Shapes
    Dim xlPic As Shape
    Dim xlWorksheet As Worksheet

    If IsEmpty(filePath) Or Len(Dir(filePath)) = 0 Then
        MsgBox ("File Path invalid")
        Exit Sub
    End If

    Set xlWorksheet = ActiveSheet

    Set xlPic = xlWorksheet.Shapes.AddPicture(filePath, msoFalse, msoCTrue, insertCell.top, insertCell.left, insertCell.width, insertCell.height)
    xlPic.LockAspectRatio = msoCTrue
End Sub

difference between System.out.println() and System.err.println()

System.out's main purpose is giving standard output.

System.err's main purpose is giving standard error.


Look at these

http://www.devx.com/tips/Tip/14698

http://wiki.eclipse.org/FAQ_Where_does_System.out_and_System.err_output_go%3F

Listing all extras of an Intent

Bundle extras = getIntent().getExtras();
Set<String> ks = extras.keySet();
Iterator<String> iterator = ks.iterator();
while (iterator.hasNext()) {
    Log.d("KEY", iterator.next());
}

How to change the default encoding to UTF-8 for Apache?

Just a hint if you have long filenames in utf-8: by default they will be shortened to 20 bytes, so it may happen that the last character might be "cut in half" and therefore unrecognized properly. Then you may want to set the following:

IndexOptions Charset=UTF-8 NameWidth=*

NameWidth setting will prevent shortening your file names, making them properly displayed and readable.

As other users already mentioned, this should be added either in httpd.conf or apache2.conf (if you do have admin rights) or in .htaccess (if you don't).

AngularJS/javascript converting a date String to date object

try this

html

<div ng-controller="MyCtrl">
  Hello, {{newDate | date:'MM/dd/yyyy'}}!
</div>

JS

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var collectionDate = '2002-04-26T09:00:00'; 

    $scope.newDate =new Date(collectionDate);
}

Demo

Qt: How do I handle the event of the user pressing the 'X' (close) button?

also you can reimplement protected member QWidget::closeEvent()

void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
    // do what you need here
    // then call parent's procedure
    QWidget::closeEvent(event);
}

How do I see which version of Swift I'm using?

Project build settings have a block 'Swift Compiler - Languages', which stores information about Swift Language Version in key-value format. It will show you all available (supported) Swift Language Version for your Xcode and active version also by a tick mark.

Project ? (Select Your Project Target) ? Build Settings ? (Type 'swift_version' in the Search bar) Swift Compiler Language ? Swift Language Version ? Click on Language list to open it (and there will be a tick mark on any one of list-item, that will be current swift version).

Look at this snapshot, for easy understanding:

xcode with described areas highlighted


With help of following code, programmatically you can find Swift version supported by your project.

#if swift(>=5.3)
print("Hello, Swift 5.3")

#elseif swift(>=5.2)
print("Hello, Swift 5.2")

#elseif swift(>=5.1)
print("Hello, Swift 5.1")

#elseif swift(>=5.0)
print("Hello, Swift 5.0")

#elseif swift(>=4.2)
print("Hello, Swift 4.2")

#elseif swift(>=4.1)
print("Hello, Swift 4.1")

#elseif swift(>=4.0)
print("Hello, Swift 4.0")

#elseif swift(>=3.2)
print("Hello, Swift 3.2")

#elseif swift(>=3.0)
print("Hello, Swift 3.0")

#elseif swift(>=2.2)
print("Hello, Swift 2.2")

#elseif swift(>=2.1)
print("Hello, Swift 2.1")

#elseif swift(>=2.0)
print("Hello, Swift 2.0")

#elseif swift(>=1.2)
print("Hello, Swift 1.2")

#elseif swift(>=1.1)
print("Hello, Swift 1.1")

#elseif swift(>=1.0)
print("Hello, Swift 1.0")

#endif

Here is result using Playground (with Xcode 11.x)

enter image description here

C compile : collect2: error: ld returned 1 exit status

I got this problem, and tried many ways to solve it. Finally, it turned out that make clean and make again solved it. The reason is: I got the source code together with object files compiled previously with an old gcc version. When my newer gcc version wants to link that old object files, it can't resolve some function in there. It happens to me several times that the source code distributors do not clean up before packing, so a make clean saved the day.

ld cannot find -l<library>

I had a similar problem with another library and the reason why it didn't found it, was that I didn't run the make install (after running ./configure and make) for that library. The make install may require root privileges (in this case use: sudo make install). After running the make install you should have the so files in the correct folder, i.e. here /usr/local/lib and not in the folder mentioned by you.

Extract regression coefficient values

To answer your question, you can explore the contents of the model's output by saving the model as a variable and clicking on it in the environment window. You can then click around to see what it contains and what is stored where.

Another way is to type yourmodelname$ and select the components of the model one by one to see what each contains. When you get to yourmodelname$coefficients, you will see all of beta-, p, and t- values you desire.

Where is git.exe located?

Appears to have moved again in the latest version of GH for windows to:

%USERPROFILE%\AppData\Local\GitHubDesktop\app-[gfw-version]\resources\app\git\cmd\git.exe

Given it now has the version in the folder structure i think it will move every time it auto-updates. This makes it impossible to put into path. I think the best option is to install git separately.

Why does the 260 character path length limit exist in Windows?

You can mount a folder as a drive. From the command line, if you have a path C:\path\to\long\folder you can map it to drive letter X: using:

subst x: \path\to\long\folder

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

Checking Bash exit status of several commands efficiently

For what it's worth, a shorter way to write code to check each command for success is:

command1 || echo "command1 borked it"
command2 || echo "command2 borked it"

It's still tedious but at least it's readable.

Use bash to find first folder name that contains a string

for example:

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"

or (For the better shell solution see Adrian Frühwirth's answer)

for dir1 in *
do
    [[ -d "$dir1" && "$dir1" =~ foo ]] && break
    dir1=        #fix based on comment
done
echo "$dir1"

or

dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"

Edited head -n1 based on @ hek2mgl comment

Next based on @chepner's comments

dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')

or

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)

jQuery-UI datepicker default date

If you want to update the highlighted day to a different day based on some server time, you can override the Date Picker code to allow for a new custom option named localToday or whatever you'd like to name it.

A small tweak to the selected answer in jQuery UI DatePicker change highlighted "today" date

// Get users 'today' date
var localToday = new Date();
localToday.setDate(tomorrow.getDate()+1); // tomorrow

// Pass the today date to datepicker
$( "#datepicker" ).datepicker({
    showButtonPanel: true,
    localToday: localToday    // This option determines the highlighted today date
});

I've overridden 2 datepicker methods to conditionally use a new setting for the "today" date instead of a new Date(). The new setting is called localToday.

Override $.datepicker._gotoToday and $.datepicker._generateHTML like this:

$.datepicker._gotoToday = function(id) {
    /* ... */
    var date = inst.settings.localToday || new Date()
    /* ... */
}

$.datepicker._generateHTML = function(inst) {
    /* ... */
    tempDate = inst.settings.localToday || new Date()
    /* ... */
}

Here's a demo which shows the full code and usage: http://jsfiddle.net/NAzz7/5/

How do I include inline JavaScript in Haml?

:javascript
    $(document).ready( function() {
      $('body').addClass( 'test' );
    } );

Docs: http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter

How to search for an element in a golang slice

You can save the struct into a map by matching the struct Key and Value components to their fictive key and value parts on the map:

mapConfig := map[string]string{}
for _, v := range myconfig {
   mapConfig[v.Key] = v.Value
}

Then using the golang comma ok idiom you can test for the key presence:

if v, ok := mapConfig["key1"]; ok {
    fmt.Printf("%s exists", v)
}   

Set drawable size programmatically

You can try button.requestLayout(). When the background size is changed, it needs to remeasure and layout, but it won't do it

How can I jump to class/method definition in Atom text editor?

Check out goto package:

This is a replacement for Atom’s built-in symbols-view package that uses Atom’s own syntax files to identify symbols rather than ctags. The ctags project is very useful but it is never going to keep up with all of the new Atom syntaxes that will be created as Atom grows.

Commands:

  • cmd-r - Goto File Symbol
  • cmd-shift-r - Goto Project Symbol
  • cmd-alt-down - Goto Declaration
  • Rebuild Index
  • Invalidate Index

Link here: https://atom.io/packages/goto (or search "goto" in package installer)

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

I had this same issue when working on an Ubuntu server.

I was getting the following error:

deploy@my-comp:~$ docker login -u my-username -p my-password
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://registry-1.docker.io/v2/: dial tcp 35.175.83.85:443: connect: connection refused

Here are the things I tried that did not work:

  • Restarting the docker service using sudo docker systemctl restart docker
  • Powering off and restarting the Ubuntu server.
  • Changing the name server to 8.8.8.8 in the /etc/resolv.conf file

Here's what worked for me:

I tried checking if the server has access to the internet using the following netcat command:

nc -vz google.com 443

And it returned this output:

nc: connect to google.com port 443 (tcp) failed: Connection refused
nc: connect to google.com port 443 (tcp) failed: Network is unreachable

Instead of something like this:

Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Connected to 172.217.166.110:443.
Ncat: 0 bytes sent, 0 bytes received in 0.07 seconds.

I tried checking again if the server has access to the internet using the following wget command:

wget -q --spider http://google.com ; echo $?

And it returned:

4

Instead of:

0

Note: Anything other than 0 in the output means your system is not connected to the internet

I then tried the last time if the server has access to the internet using the following Nmap command:

nmap -p 443 google.com

And it returned:

Starting Nmap 7.01 ( https://nmap.org ) at 2021-02-16 11:50 WAT
Nmap scan report for google.com (216.58.223.238)
Host is up (0.00052s latency).
Other addresses for google.com (not scanned): 2c0f:fb50:4003:802::200e
rDNS record for 216.58.223.238: los02s04-in-f14.1e100.net
PORT    STATE  SERVICE
443/tcp closed https

Nmap done: 1 IP address (1 host up) scanned in 1.21 seconds

Instead something like this:

Starting Nmap 7.01 ( https://nmap.org ) at 2021-02-16 11:50 WAT
Nmap scan report for google.com (216.58.223.238)
Host is up (0.00052s latency).
Other addresses for google.com (not scanned): 2c0f:fb50:4003:802::200e
rDNS record for 216.58.223.238: los02s04-in-f14.1e100.net
PORT    STATE  SERVICE
443/tcp open https

Nmap done: 1 IP address (1 host up) scanned in 1.21 seconds

Note: The state of port 443/tcp is closed instead of open

All this was enough to make me realize that connections to the internet were not allowed on the server.

All I had to do was speak with the team in charge of infrastructure to fix the network connectivity issue to the internet on the server. And once that was fixed my docker command started working fine.

Resources: 9 commands to check if connected to internet with shell script examples

That's all.

I hope this helps

Possible cases for Javascript error: "Expected identifier, string or number"

IE7 has problems with arrays of objects

columns: [
{
  field: "id",
  header: "ID"
},
{
  field: "name",
  header: "Name" , /* this comma was the problem*/ 
},
...

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

This worked for me.

app.get('/', function (req, res) {

    res.header("Access-Control-Allow-Origin", "*");
    res.send('hello world')
})

You can change * to fit your needs. Hope this can help.

How can I convert a DateTime to the number of seconds since 1970?

That's basically it. These are the methods I use to convert to and from Unix epoch time:

public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    return origin.AddSeconds(timestamp);
}

public static double ConvertToUnixTimestamp(DateTime date)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan diff = date.ToUniversalTime() - origin;
    return Math.Floor(diff.TotalSeconds);
}

Update: As of .Net Core 2.1 and .Net Standard 2.1 a DateTime equal to the Unix Epoch can be obtained from the static DateTime.UnixEpoch.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

Just to complete the existing answers, I'd suggest using select instead of nonblocking sockets. The point is that nonblocking sockets complicate stuff (except perhaps sending), so I'd say there is no reason to use them at all. If you regularly have the problem that your app is blocked waiting for IO, I would also consider doing the IO in a separate thread in the background.

How to increase maximum execution time in php

Use the PHP function

void set_time_limit ( int $seconds )

The maximum execution time, in seconds. If set to zero, no time limit is imposed.

This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.

Searching multiple files for multiple words

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to Search > Find in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (test1|test2)
  • Filters = *.txt
  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.
  • Search mode = Regular Expression

How do I find the value of $CATALINA_HOME?

Just as a addition. You can find the Catalina Paths in

->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS

In the VM Arguments the Paths are listed and changeable

Is it possible to open developer tools console in Chrome on Android phone?

You can do it using remote debugging, here is official documentation. Basic process:

  1. Connect your android device
  2. Select your device: More tools > Inspect devices* from dev tools on pc/mac.
  3. Authorize on your mobile.
  4. Happy debugging!!

* This is now "Remote devices".

How can I search an array in VB.NET?

VB

Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()

C#

string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();

-----Detailed------

Module Module1

    Sub Main()
        Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
        Dim searchStr = "ra"
        'Not case sensitive - checks if item starts with searchStr
        Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
        'Case sensitive - checks if item starts with searchStr
        Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
        'Not case sensitive - checks if item contains searchStr
        Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
        Stop
    End Sub

End Module

Set Content-Type to application/json in jsp file

You can do via Page directive.

For example:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

F# version of each way

let rec getExcelColumnName x  = if x<26 then int 'A'+x|>char|>string else (x/26-1|>c)+ c(x%26)

pardon the minimizing, was working on a better version of https://stackoverflow.com/a/4500043/57883


and the opposite direction:

// return values start at 0
let getIndexFromExcelColumnName (x:string) =
    let a = int 'A'
    let fPow len i =
        Math.Pow(26., len - 1 - i |> float)
        |> int

    let getValue len i c = 
        int c - a + 1 * fPow len i
    let f i = getValue x.Length i x.[i]
    [0 .. x.Length - 1]
    |> Seq.map f
    |> Seq.sum
    |> fun x -> x - 1

MySQL: can't access root account

I got the same problem when accessing mysql with root. The problem I found is that some database files does not have permission by the mysql user, which is the user that started the mysql server daemon.

We can check this with ls -l /var/lib/mysql command, if the mysql user does not have permission of reading or writing on some files or directories, that might cause problem. We can change the owner or mode of those files or directories with chown/chmod commands.

After these changes, restart the mysqld daemon and login with root with command:

mysql -u root

Then change passwords or create other users for logging into mysql.

HTH

Eclipse: The declared package does not match the expected package

  1. Right click on the external folder which is having package
src.prefix1.prefix.packagename1 
src.prefix1.prefix.packagename2
  1. Click Build path --> Remove from build path.

  2. Now go the folder prefix1 in the folder section of your project.

  3. Right click on it --> Build path --> Use as source folder.

  4. Done. The package folder wont show any error now. If it still shows, just restart the project.

Graphical DIFF programs for linux

I use Guiffy and it works well.
alt text
(source: guiffy.org)

How to call any method asynchronously in c#

Starting with .Net 4.5 you can use Task.Run to simply start an action:

void Foo(string args){}
...
Task.Run(() => Foo("bar"));

Task.Run vs Task.Factory.StartNew

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

What is external linkage and internal linkage?

Linkage determines whether identifiers that have identical names refer to the same object, function, or other entity, even if those identifiers appear in different translation units. The linkage of an identifier depends on how it was declared. There are three types of linkages:

  1. Internal linkage : identifiers can only be seen within a translation unit.
  2. External linkage : identifiers can be seen (and referred to) in other translation units.
  3. No linkage : identifiers can only be seen in the scope in which they are defined. Linkage does not affect scoping

C++ only : You can also have linkage between C++ and non-C++ code fragments, which is called language linkage.

Source :IBM Program Linkage

How to change the background color of a UIButton while it's highlighted?

Try tintColor:

_button.tintColor = [UIColor redColor];

RegEx pattern any two letters followed by six numbers

You could try something like this:

[a-zA-Z]{2}[0-9]{6}

Here is a break down of the expression:

[a-zA-Z]    # Match a single character present in the list below
               # A character in the range between “a” and “z”
               # A character in the range between “A” and “Z”
   {2}         # Exactly 2 times
[0-9]       # Match a single character in the range between “0” and “9”
   {6}         # Exactly 6 times

This will match anywhere in a subject. If you need boundaries around the subject then you could do either of the following:

^[a-zA-Z]{2}[0-9]{6}$

Which ensures that the whole subject matches. I.e there is nothing before or after the subject.

or

\b[a-zA-Z]{2}[0-9]{6}\b

which ensures there is a word boundary on each side of the subject.

As pointed out by @Phrogz, you could make the expression more terse by replacing the [0-9] for a \d as in some of the other answers.

[a-zA-Z]{2}\d{6}

Getting DOM element value using pure JavaScript

In the second version, you're passing the String returned from this.id. Not the element itself.

So id.value won't give you what you want.

You would need to pass the element with this.

doSomething(this)

then:

function(el){
    var value = el.value;
    ...
}

Note: In some browsers, the second one would work if you did:

window[id].value 

because element IDs are a global property, but this is not safe.

It makes the most sense to just pass the element with this instead of fetching it again with its ID.

How to replace four spaces with a tab in Sublime Text 2?

Select all, then:

Windows / Linux:

Ctrl+Shift+p

then type "indent"


Mac:

Shift+Command+p

then type "indent"

Adding POST parameters before submit

You could do an ajax call.

That way, you would be able to populate the POST array yourself through the ajax 'data: ' parameter

var params = {
  url: window.location.pathname,
  time: new Date().getTime(), 
};


$.ajax({
  method: "POST",
  url: "your/script.php",
  data: params
});

Remove property for all objects in array

This question is a bit old now, but I would like to offer an alternative solution that doesn't mutate source data and requires minimal manual effort:

function mapOut(sourceObject, removeKeys = []) {
  const sourceKeys = Object.keys(sourceObject);
  const returnKeys = sourceKeys.filter(k => !removeKeys.includes(k));
  let returnObject = {};
  returnKeys.forEach(k => {
    returnObject[k] = sourceObject[k];
  });
  return returnObject;
}

const array = [
  {"bad": "something", "good":"something"},
  {"bad":"something", "good":"something"},
];

const newArray = array.map(obj => mapOut(obj, [ "bad", ]));

It's still a little less than perfect, but maintains some level of immutability and has the flexibility to name multiple properties that you want to remove. (Suggestions welcome)

Trying to start a service on boot on Android

I faced with this problem if i leave the empty constructor in the receiver class. After the removing the empty contsructor onRreceive methos started working fine.

How to perform a for-each loop over all the files under a specified path?

Use command substitution instead of quotes to execute find instead of passing the command as a string:

for line in $(find . -iname '*.txt'); do 
     echo $line
     ls -l $line; 
done

Differences between cookies and sessions?

Cookies and session both store information about the user (to make the HTTP request stateful) but the difference is that cookies store information on the client-side (browser) and sessions store information on the server-side. A cookie is limited in the sense that it stores information about limited users and only stores limited content for each user. A session is not limit in such a way.

Printing all global variables/local variables?

In case you want to see the local variables of a calling function use select-frame before info locals

E.g.:

(gdb) bt
#0  0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1  0xfec36f39 in thr_kill () from /lib/libc.so.1
#2  0xfebe3603 in raise () from /lib/libc.so.1
#3  0xfebc2961 in abort () from /lib/libc.so.1
#4  0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5  0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb) 

How to save a plot into a PDF file without a large margin around

Save to EPS and then convert to PDF:

saveas(gcf, 'nombre.eps', 'eps2c')
system('epstopdf nombre.eps') %Needs TeX Live (maybe it works with MiKTeX).

You will need some software that converts EPS to PDF.

How do I run a docker instance from a DockerFile?

You cannot start a container from a Dockerfile.

The process goes like this:

Dockerfile =[docker build]=> Docker image =[docker run]=> Docker container

To start (or run) a container you need an image. To create an image you need to build the Dockerfile[1].

[1]: you can also docker import an image from a tarball or again docker load.

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

How to stop event bubbling on checkbox click

As others have mentioned, try stopPropagation().

And there is a second handler to try: event.cancelBubble = true; It's a IE specific handler, but it is supported in at least FF. Don't really know much about it, as I haven't used it myself, but it might be worth a shot, if all else fails.

Sublime Text 2 Code Formatting

Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.

For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).

Greets

retrieve links from web page using python and BeautifulSoup

BeatifulSoup's own parser can be slow. It might be more feasible to use lxml which is capable of parsing directly from a URL (with some limitations mentioned below).

import lxml.html

doc = lxml.html.parse(url)

links = doc.xpath('//a[@href]')

for link in links:
    print link.attrib['href']

The code above will return the links as is, and in most cases they would be relative links or absolute from the site root. Since my use case was to only extract a certain type of links, below is a version that converts the links to full URLs and which optionally accepts a glob pattern like *.mp3. It won't handle single and double dots in the relative paths though, but so far I didn't have the need for it. If you need to parse URL fragments containing ../ or ./ then urlparse.urljoin might come in handy.

NOTE: Direct lxml url parsing doesn't handle loading from https and doesn't do redirects, so for this reason the version below is using urllib2 + lxml.

#!/usr/bin/env python
import sys
import urllib2
import urlparse
import lxml.html
import fnmatch

try:
    import urltools as urltools
except ImportError:
    sys.stderr.write('To normalize URLs run: `pip install urltools --user`')
    urltools = None


def get_host(url):
    p = urlparse.urlparse(url)
    return "{}://{}".format(p.scheme, p.netloc)


if __name__ == '__main__':
    url = sys.argv[1]
    host = get_host(url)
    glob_patt = len(sys.argv) > 2 and sys.argv[2] or '*'

    doc = lxml.html.parse(urllib2.urlopen(url))
    links = doc.xpath('//a[@href]')

    for link in links:
        href = link.attrib['href']

        if fnmatch.fnmatch(href, glob_patt):

            if not href.startswith(('http://', 'https://' 'ftp://')):

                if href.startswith('/'):
                    href = host + href
                else:
                    parent_url = url.rsplit('/', 1)[0]
                    href = urlparse.urljoin(parent_url, href)

                    if urltools:
                        href = urltools.normalize(href)

            print href

The usage is as follows:

getlinks.py http://stackoverflow.com/a/37758066/191246
getlinks.py http://stackoverflow.com/a/37758066/191246 "*users*"
getlinks.py http://fakedomain.mu/somepage.html "*.mp3"

Woocommerce get products

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'hoodies'
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();
?>

This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.

What is App.config in C#.NET? How to use it?

Just to add something I was missing from all the answers - even if it seems to be silly and obvious as soon as you know:

The file has to be named "App.config" or "app.config" and can be located in your project at the same level as e.g. Program.cs.

I do not know if other locations are possible, other names (like application.conf, as suggested in the ODP.net documentation) did not work for me.

PS. I started with Visual Studio Code and created a new project with "dotnet new". No configuration file is created in this case, I am sure there are other cases. PPS. You may need to add a nuget package to be able to read the config file, in case of .NET CORE it would be "dotnet add package System.Configuration.ConfigurationManager --version 4.5.0"

How do you add CSS with Javascript?

This easy example of add <style> in head of html

var sheet = document.createElement('style');
sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ "table ul {    margin-top: 0 !important;    margin-bottom: 0 !important;}\n"
+ "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ ".messages.error{display:none !important;}\n"
+ ".messages.status{display:none !important;} ";

document.body.appendChild(sheet); // append in body
document.head.appendChild(sheet); // append in head

Source Dynamic style - manipulating CSS with JavaScript

How to include (source) R script in other scripts

Here is a function I wrote. It wraps the base::source function to store a list of sourced files in a global environment list named sourced. It will only re-source a file if you provide a .force=TRUE argument to the call to source. Its argument signature is otherwise identical to the real source() so you don't need to rewrite your scripts to use this.

warning("overriding source with my own function FYI")
source <- function(path, .force=FALSE, ...) {
  library(tools)
  path <- tryCatch(normalizePath(path), error=function(e) path)
  m<-md5sum(path)

  go<-TRUE
  if (!is.vector(.GlobalEnv$sourced)) {
    .GlobalEnv$sourced <- list()
  }
  if(! is.null(.GlobalEnv$sourced[[path]])) {
    if(m == .GlobalEnv$sourced[[path]]) {
      message(sprintf("Not re-sourcing %s. Override with:\n  source('%s', .force=TRUE)", path, path))
      go<-FALSE
    }
    else {
      message(sprintf('re-sourcing %s as it has changed from: %s to: %s', path, .GlobalEnv$sourced[[path]], m))
      go<-TRUE
    }
  } 
  if(.force) {
    go<-TRUE
    message("  ...forcing.")
  }
  if(go) {
    message(sprintf("sourcing %s", path))
    .GlobalEnv$sourced[path] <- m
    base::source(path, ...)
  }
}

It's pretty chatty (lots of calls to message()) so you can take those lines out if you care. Any advice from veteran R users is appreciated; I'm pretty new to R.

how to get multiple checkbox value using jquery

$('input:checked').map(function(i, e) {return e.value}).toArray();

List of phone number country codes

Android ready county list and flag images

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- country list -->
    <string-array name="data000">
        <item name="code">+93</item>
        <item name="country">Afghanistan</item>
        <item name="iso">AF</item>
        <item name="flag">@drawable/afghanistan</item>
    </string-array>
    <string-array name="data001">
        <item name="code">+355</item>
        <item name="country">Albania</item>
        <item name="iso">AL</item>
        <item name="flag">@drawable/albania</item>
    </string-array>
    ...

    <array name="countries">
        <item>@array/data000</item>
        <item>@array/data001</item>
        ...
    </array>
</resources>

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

Actually, the absolutely easiest way is to do the following...

byte[] content = your_byte[];

FileContentResult result = new FileContentResult(content, "application/octet-stream") 
{
  FileDownloadName = "your_file_name"
};

return result;

How to validate an e-mail address in swift?

I improved @Azik answer. I allow more special characters which are allowed by guidelines, as well as return a few extra edge cases as invalid.

The group think going on here to only allow ._%+- in the local part is not correct per guidelines. See @Anton Gogolev answer on this question or see below:

The local-part of the email address may use any of these ASCII characters:

  • uppercase and lowercase Latin letters A to Z and a to z;

  • digits 0 to 9;

  • special characters !#$%&'*+-/=?^_`{|}~;

  • dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. [email protected] is not allowed but "John..Doe"@example.com is allowed);

  • space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash); comments are allowed

  • with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)[email protected] are both equivalent to [email protected];

The code I use will not allow restricted out of place special characters, but will allow many more options than the majority of answers here. I would prefer more relaxed validation to error on the side of caution.

if enteredText.contains("..") || enteredText.contains("@@") 
   || enteredText.hasPrefix(".") || enteredText.hasSuffix(".con"){
       return false
}

let emailFormat = "[A-Z0-9a-z.!#$%&'*+-/=?^_`{|}~]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)     
return emailPredicate.evaluate(with: enteredText)

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003

Young generation garbage collection algorithms

The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.

The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.

The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).

From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't.

Web-scraping JavaScript page with Python

EDIT 30/Dec/2017: This answer appears in top results of Google searches, so I decided to update it. The old answer is still at the end.

dryscape isn't maintained anymore and the library dryscape developers recommend is Python 2 only. I have found using Selenium's python library with Phantom JS as a web driver fast enough and easy to get the work done.

Once you have installed Phantom JS, make sure the phantomjs binary is available in the current path:

phantomjs --version
# result:
2.1.1

Example

To give an example, I created a sample page with following HTML code. (link):

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Javascript scraping test</title>
</head>
<body>
  <p id='intro-text'>No javascript support</p>
  <script>
     document.getElementById('intro-text').innerHTML = 'Yay! Supports javascript';
  </script> 
</body>
</html>

without javascript it says: No javascript support and with javascript: Yay! Supports javascript

Scraping without JS support:

import requests
from bs4 import BeautifulSoup
response = requests.get(my_url)
soup = BeautifulSoup(response.text)
soup.find(id="intro-text")
# Result:
<p id="intro-text">No javascript support</p>

Scraping with JS support:

from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get(my_url)
p_element = driver.find_element_by_id(id_='intro-text')
print(p_element.text)
# result:
'Yay! Supports javascript'

You can also use Python library dryscrape to scrape javascript driven websites.

Scraping with JS support:

import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit(my_url)
response = session.body()
soup = BeautifulSoup(response)
soup.find(id="intro-text")
# Result:
<p id="intro-text">Yay! Supports javascript</p>

Passing data to a jQuery UI Dialog

Looking at your code what you need to do is add the functionality to close the window and update the page. In your "Yes" function you should write:

        buttons: {
            "Ja": function() {
                $.post(a.href);
                $(a). // code to remove the table row
                $("#dialog").dialog("close");
            },
            "Nej": function() { $(this).dialog("close"); }
        },

The code to remove the table row isn't fun to write so I'll let you deal with the nitty gritty details, but basically, you need to tell the dialog what to do after you post it. It may be a smart dialog but it needs some kind of direction.

How to save a bitmap on internal storage

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}

How to set timer in android?

This is some simple code for a timer:

Timer timer = new Timer();
TimerTask t = new TimerTask() {       
    @Override
    public void run() {

        System.out.println("1");
    }
};
timer.scheduleAtFixedRate(t,1000,1000);

Creating a LINQ select from multiple tables

If the anonymous type causes trouble for you, you can create a simple data class:

public class PermissionsAndPages
{
     public ObjectPermissions Permissions {get;set}
     public Pages Pages {get;set}
}

and then in your query:

select new PermissionsAndPages { Permissions = op, Page = pg };

Then you can pass this around:

return queryResult.SingleOrDefault(); // as PermissionsAndPages

Laravel - Pass more than one variable to view

Please try this,

$ms = Person::where('name', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return View::make('viewname')->with(compact('persons','ms'));

com.sun.jdi.InvocationException occurred invoking method

I also faced the same problem. In my case I was hitting a java.util.UnknownFormatConversionException. I figured this out only after putting a printStackTrace call. I resolved it by changing my code as shown below.

from:

StringBuilder sb = new StringBuilder();
sb.append("***** Test Details *****\n");
String.format("[Test: %1]", sb.toString());

to:

String.format("[Test: %s]", sb.toString());

How to make HTTP Post request with JSON body in Swift

Try this,

// prepare json data
let json: [String: Any] = ["title": "ABC",
                           "dict": ["1":"First", "2":"Second"]]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

// create post request
let url = URL(string: "http://httpbin.org/post")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

// insert json data to the request
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
    }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }
}

task.resume()

or try a convenient way Alamofire

add class with JavaScript

In your snippet, button is an instance of NodeList, to which you can't attach an event listener directly, nor can you change the elements' className properties directly.
Your best bet is to delegate the event:

document.body.addEventListener('mouseover',function(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
    {
        target.className += ' active';//set class
    }
},false);

Of course, my guess is that the active class needs to be removed once the mouseout event fires, you might consider using a second delegator for that, but you could just aswell attach an event handler to the one element that has the active class:

document.body.addEventListener('mouseover',function(e)
{
    e = e || window.event;
    var oldSrc, target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
    {
        target.className += ' active';//set class
        oldSrc = target.getAttribute('src');
        target.setAttribute('src', 'images/arrows/top_o.png');
        target.onmouseout = function()
        {
            target.onmouseout = null;//remove this event handler, we don't need it anymore
            target.className = target.className.replace(/\bactive\b/,'').trim();
            target.setAttribute('src', oldSrc);
        };
    }
},false);

There is some room for improvements, with this code, but I'm not going to have all the fun here ;-).

Check the fiddle here

Cannot access a disposed object - How to fix?

Try checking the IsDisposed property before accessing the control. You can also check it on the FormClosing event, assuming you're using the FormClosed event.

We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.

Calling GC.Collect before checking IsDisposed may help, but be careful with this. Read this article by Rico Mariani "When to call GC.Collect()".

Laravel, sync() - how to sync an array and also pass additional pivot fields?

This works for me

foreach ($photos_array as $photo) {

    //collect all inserted record IDs
    $photo_id_array[$photo->id] = ['type' => 'Offence'];  

}

//Insert into offence_photo table
$offence->photos()->sync($photo_id_array, false);//dont delete old entries = false

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

I had the same error message, my mistake was that I had a semicolon at the end of COMMIT TRANSACTION line

Simulating Key Press C#

Another alternative to simulating a F5 key press would be to simply host the WebBrowser control in the Window Forms application. You use the WebBrowser.Navigate method to load your web page and then use a standard Timer and on each tick of the timer you just re-Navigate to the url which will reload the page.

Java Array Sort descending?

I had the below working solution

    public static int[] sortArrayDesc(int[] intArray){
    Arrays.sort(intArray);                      //sort intArray in Asc order
    int[] sortedArray = new int[intArray.length];   //this array will hold the sorted values

    int indexSortedArray = 0;
    for(int i=intArray.length-1 ; i >= 0 ; i--){    //insert to sortedArray in reverse order
        sortedArray[indexSortedArray ++] = intArray [i];
    }
    return sortedArray;
}

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

VS 2010 Express is no longer linked to any VS Express pages (that I found). I did find this link to the ISO which I used and it fixed the errors mentioned here.

http://download.microsoft.com/download/1/E/5/1E5F1C0A-0D5B-426A-A603-1798B951DDAE/VS2010Express1.iso

Note: Also make sure you have x86 everything (Python + Postgresql) or you'll get other errors. I did not try x64 everything.

How to write UPDATE SQL with Table alias in SQL Server 2008?

The syntax for using an alias in an update statement on SQL Server is as follows:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

Float a div in top right corner without overlapping sibling header

If you can change the order of the elements, floating will work.

_x000D_
_x000D_
section {_x000D_
  position: relative;_x000D_
  width: 50%;_x000D_
  border: 1px solid;_x000D_
}_x000D_
h1 {_x000D_
  display: inline;_x000D_
}_x000D_
div {_x000D_
  float: right;_x000D_
}
_x000D_
<section>_x000D_
  <div>_x000D_
    <button>button</button>_x000D_
  </div>_x000D_
_x000D_
  <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>_x000D_
</section>
_x000D_
_x000D_
_x000D_

?By placing the div before the h1 and floating it to the right, you get the desired effect.

JavaScript for...in vs for

Note that the native Array.forEach method is now widely supported.

Escape double quotes in parameter

I cannot quickly reproduce the symptoms: if I try myscript '"test"' with a batch file myscript.bat containing just @echo.%1 or even @echo.%~1, I get all quotes: '"test"'

Perhaps you can try the escape character ^ like this: myscript '^"test^"'?

How to edit HTML input value colour?

Please try this:

<input class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2" type="text" name="name" value="" placeholder="Your Name" style="background-color:blue;"/>

You basically put all the CSS inside the style part of the input tag and it works.

Add text to Existing PDF using Python

cpdf will do the job from the command-line. It isn't python, though (afaik):

cpdf -add-text "Line of text" input.pdf -o output .pdf

Negative weights using Dijkstra's Algorithm

TL;DR: The answer depends on your implementation. For the pseudo code you posted, it works with negative weights.


Variants of Dijkstra's Algorithm

The key is there are 3 kinds of implementation of Dijkstra's algorithm, but all the answers under this question ignore the differences among these variants.

  1. Using a nested for-loop to relax vertices. This is the easiest way to implement Dijkstra's algorithm. The time complexity is O(V^2).
  2. Priority-queue/heap based implementation + NO re-entrance allowed, where re-entrance means a relaxed vertex can be pushed into the priority-queue again to be relaxed again later.
  3. Priority-queue/heap based implementation + re-entrance allowed.

Version 1 & 2 will fail on graphs with negative weights (if you get the correct answer in such cases, it is just a coincidence), but version 3 still works.

The pseudo code posted under the original problem is the version 3 above, so it works with negative weights.

Here is a good reference from Algorithm (4th edition), which says (and contains the java implementation of version 2 & 3 I mentioned above):

Q. Does Dijkstra's algorithm work with negative weights?

A. Yes and no. There are two shortest paths algorithms known as Dijkstra's algorithm, depending on whether a vertex can be enqueued on the priority queue more than once. When the weights are nonnegative, the two versions coincide (as no vertex will be enqueued more than once). The version implemented in DijkstraSP.java (which allows a vertex to be enqueued more than once) is correct in the presence of negative edge weights (but no negative cycles) but its running time is exponential in the worst case. (We note that DijkstraSP.java throws an exception if the edge-weighted digraph has an edge with a negative weight, so that a programmer is not surprised by this exponential behavior.) If we modify DijkstraSP.java so that a vertex cannot be enqueued more than once (e.g., using a marked[] array to mark those vertices that have been relaxed), then the algorithm is guaranteed to run in E log V time but it may yield incorrect results when there are edges with negative weights.


For more implementation details and the connection of version 3 with Bellman-Ford algorithm, please see this answer from zhihu. It is also my answer (but in Chinese). Currently I don't have time to translate it into English. I really appreciate it if someone could do this and edit this answer on stackoverflow.

Update Eclipse with Android development tools v. 23

Based on win7. Eclipse Version: 4.2.2 Build id: M20130204-1200

For those who broke Eclipse after trying to uninstall ADT plugin.

You need to remove all android folder/jars from plugin folder and features folder.

Then check your config.ini in /configuration. Probably you have these lines:

eclipse.product=

...

eclipse.application=

change them like this:

eclipse.product=org.eclipse.platform.ide
eclipse.application=org.eclipse.ui.ide.workbench

Maybe needed to run your eclipse from command line:

eclipsec.exe -clean.

Then I could install the newest ADT plugin, without needing to download whole eclipse packages and loosing all configuration/plugins.

Find TODO tags in Eclipse

In adition to the other answers mentioning the Tasks view:

It is also possible to filter the Tasks that are listed to only show the TODOs that contain the text // TODO Auto-generated method stub.

To achieve this you can click on the Filters... button in the top right of the Tasks View and define custom filters like this:

enter image description here

This way it's a bit easier and faster to find only some of the TODOs in the project in the Tasks View, and you don't have to search for the text in all files using the eclipse search tool (which can take quite some time).

Remove a file from a Git repository without deleting it from the local filesystem

If you want to just untrack a file and not delete from local and remote repo then use this command:

git update-index --assume-unchanged  file_name_with_path

Get viewport/window height in ReactJS

with a little typescript

_x000D_
_x000D_
import { useState, useEffect } from 'react';

interface WindowDimentions {
    width: number;
    height: number;
}

function getWindowDimensions(): WindowDimentions {
    const { innerWidth: width, innerHeight: height } = window;

    return {
      width,
      height
    };
  }
  
  export default function useWindowDimensions(): WindowDimentions {
    const [windowDimensions, setWindowDimensions] = useState<WindowDimentions>(
      getWindowDimensions()
    );
  
    useEffect(() => {
      function handleResize(): void {
        setWindowDimensions(getWindowDimensions());
      }
  
      window.addEventListener('resize', handleResize);

      return (): void => window.removeEventListener('resize', handleResize);
    }, []);
  
    return windowDimensions;
  }
_x000D_
_x000D_
_x000D_

Most efficient way to find mode in numpy array

from collections import Counter

n = int(input())
data = sorted([int(i) for i in input().split()])

sorted(sorted(Counter(data).items()), key = lambda x: x[1], reverse = True)[0][0]

print(Mean)

The Counter(data) counts the frequency and returns a defaultdict. sorted(Counter(data).items()) sorts using the keys, not the frequency. Finally, need to sorted the frequency using another sorted with key = lambda x: x[1]. The reverse tells Python to sort the frequency from the largest to the smallest.

Removing the title text of an iOS UIBarButtonItem

If like me you're using a custom view instead of the UINavigationBar and you're stuck with the back button then you have to do a bit of work that feels a bit cludgey.

[self.navigationController.navigationBar setHidden:NO];
self.navigationController.navigationBar.topItem.title = @"";
[self.navigationController.navigationBar setHidden:YES];

It seems like if it doesn't get presented then no matter what it'll try show a title, this means it's shown then hidden before it's drawn and solves the problem.

Spring MVC: How to return image in @ResponseBody?

 @RequestMapping(value = "/get-image",method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage() throws IOException {
    RandomAccessFile f = new RandomAccessFile("/home/vivex/apache-tomcat-7.0.59/tmpFiles/1.jpg", "r");
    byte[] b = new byte[(int)f.length()];
    f.readFully(b);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);


    return new ResponseEntity<byte[]>(b, headers, HttpStatus.CREATED);



}

Worked For Me.

Calculate difference between two dates (number of days)?

For a and b as two DateTime types:

DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();

Java: Replace all ' in a string with \'

Let's take a tour of String#repalceAll(String regex, String replacement)

You will see that:

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceAll(repl)

So lets take a look at Matcher.html#replaceAll(java.lang.String) documentation

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

You can see that in replacement we have special character $ which can be used as reference to captured group like

System.out.println("aHellob,aWorldb".replaceAll("a(\\w+?)b", "$1"));
// result Hello,World

But sometimes we don't want $ to be such special because we want to use it as simple dollar character, so we need a way to escape it.
And here comes \, because since it is used to escape metacharacters in regex, Strings and probably in other places it is good convention to use it here to escape $.

So now \ is also metacharacter in replacing part, so if you want to make it simple \ literal in replacement you need to escape it somehow. And guess what? You escape it the same way as you escape it in regex or String. You just need to place another \ before one you escaping.

So if you want to create \ in replacement part you need to add another \ before it. But remember that to write \ literal in String you need to write it as "\\" so to create two \\ in replacement you need to write it as "\\\\".


So try

s = s.replaceAll("'", "\\\\'");

Or even better

to reduce explicit escaping in replacement part (and also in regex part - forgot to mentioned that earlier) just use replace instead replaceAll which adds regex escaping for us

s = s.replace("'", "\\'");

Using Python's ftplib to get a directory listing, portably

I happen to be stuck with an FTP server (Rackspace Cloud Sites virtual server) that doesn't seem to support MLSD. Yet I need several fields of file information, such as size and timestamp, not just the filename, so I have to use the DIR command. On this server, the output of DIR looks very much like the OP's. In case it helps anyone, here's a little Python class that parses a line of such output to obtain the filename, size and timestamp.

import datetime

class FtpDir:
    def parse_dir_line(self, line):
        words = line.split()
        self.filename = words[8]
        self.size = int(words[4])
        t = words[7].split(':')
        ts = words[5] + '-' + words[6] + '-' + datetime.datetime.now().strftime('%Y') + ' ' + t[0] + ':' + t[1]
        self.timestamp = datetime.datetime.strptime(ts, '%b-%d-%Y %H:%M')

Not very portable, I know, but easy to extend or modify to deal with various different FTP servers.

LEFT JOIN only first row

I want to give a more generalized answer. One that will handle any case when you want to select only the first item in a LEFT JOIN.

You can use a subquery that GROUP_CONCATS what you want (sorted, too!), then just split the GROUP_CONCAT'd result and take only its first item, like so...

LEFT JOIN Person ON Person.id = (
    SELECT SUBSTRING_INDEX(
        GROUP_CONCAT(FirstName ORDER BY FirstName DESC SEPARATOR "_" ), '_', 1)
    ) FROM Person
);

Since we have DESC as our ORDER BY option, this will return a Person id for someone like "Zack". If we wanted someone with the name like "Andy", we would change ORDER BY FirstName DESC to ORDER BY FirstName ASC.

This is nimble, as this places the power of ordering totally within your hands. But, after much testing, it will not scale well in a situation with lots of users and lots of data.

It is, however, useful in running data-intensive reports for admin.

Cannot redeclare function php

You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:

if (!function_exists('parseDate')) {
    // ... proceed to declare your function
}

Nested JSON: How to add (push) new items to an object?

library is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.

Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.

What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};

"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.

How to disable all <input > inside a form with jQuery?

You can do it like this:

//HTML BUTTON
<button type="button" onclick="disableAll()">Disable</button>

//Jquery function
function disableAll() {
    //DISABLE ALL FIELDS THAT ARE NOT DISABLED
    $('form').find(':input:not(:disabled)').prop('disabled', true);

    //ENABLE ALL FIELDS THAT DISABLED
    //$('form').find(':input(:disabled)').prop('disabled', false);
}

C# Timer or Thread.Sleep

I would have to say a sleep is a better implementation with a state machine behind it. This would still keep you in control of the application at all times, but allowing any response needed at any specific time. This also will handle timer callbacks that are shorter than the "Processing execution time in the loop"

For example..

<!-- language: c# -->
public enum State
{
    Idle = 0,
    Processing = 1,
    Stop = 100,
}
public void Run()
{
    State state = State.Idle;   // could be a member variable, so a service could stop this too

    double intervalInSeconds = 60;
    System.DateTime nextExecution = System.DateTime.Now.AddSeconds(intervalInSeconds);
    while (state != State.Stop)
    {
        switch (state)
        {
            case State.Idle:
                {
                    if (nextExecution > System.DateTime.Now)
                    {
                        state = State.Processing;
                    }
                }
                break;
            case State.Processing:
                {
                    // do your once-per-minute code here

                    // if you want it to stop, just set it state to stop.
                    // if this was a service, you could stop execution by setting state to stop, also
                    // only time it would not stop is if it was waiting for the process to finish, which you can handle in other ways

                    state = State.Idle;
                    nextExecution = System.DateTime.Now.AddSeconds(intervalInSeconds);
                }
                break;
            default:
                break;
        }

        System.Threading.Thread.Sleep(1);
    }
}

Normalizing a list of numbers in Python

Use scikit-learn:

from sklearn.preprocessing import MinMaxScaler
data = np.array([1,2,3]).reshape(-1, 1)
scaler = MinMaxScaler()
scaler.fit(data)
print(scaler.transform(data))

Creating a UICollectionView programmatically

Swift 5

XCode 11.5

import UIKit

// 1. When creating this view, instanciate this class with the param "collectionViewLayout: UICollectionViewFlowLayout".

class BespokeCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    var cellId = "AwesomeCell"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 2. Register a reusable cell:
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
    }
    
    // 3. Return number of items:
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }
    
    // 4. Define the reusable cell:
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
        // You can cast type above as such: ...for: indexPath) as! BespokeCell
        return cell
    }
    
    // 5. Define the size of the cell. This depends on protocol 'UICollectionViewDelegateFlowLayout' to work:
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = view.frame.width // In this example the width is the same as the whole view.
        let height = CGFloat(200)
        return CGSize(width: width, height: height)
    }
}

To use your bespoke class, don't forget the collectionViewLayout param:

let layout = UICollectionViewFlowLayout()
let myViewController = WorkoutViewController(collectionViewLayout: layout)

If you're not using the storyboard, you need to attach this view to the window. That's a different problem. Systems up to iOS 12 will handle the window logic on the AppDelegate file. On iOS 13+, this logic is handled on the SceneDelegate file.

window?.rootViewController = someController

Good luck!

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

async at console app in C#?

In most project types, your async "up" and "down" will end at an async void event handler or returning a Task to your framework.

However, Console apps do not support this.

You can either just do a Wait on the returned task:

static void Main()
{
  MainAsync().Wait();
  // or, if you want to avoid exceptions being wrapped into AggregateException:
  //  MainAsync().GetAwaiter().GetResult();
}

static async Task MainAsync()
{
  ...
}

or you can use your own context like the one I wrote:

static void Main()
{
  AsyncContext.Run(() => MainAsync());
}

static async Task MainAsync()
{
  ...
}

More information for async Console apps is on my blog.

Difference between declaring variables before or in loop?

Even if I know my compiler is smart enough, I won't like to rely on it, and will use the a) variant.

The b) variant makes sense to me only if you desperately need to make the intermediateResult unavailable after the loop body. But I can't imagine such desperate situation, anyway....

EDIT: Jon Skeet made a very good point, showing that variable declaration inside a loop can make an actual semantic difference.

Cloning a private Github repo

First make sure that you have a SSH key or generate one at: https://help.github.com/articles/generating-ssh-keys/

Once you have your key, you have to add it to your github account at: https://github.com/settings/ssh

For Windows users it's useful to run git bash as an administrator.

Now the cloning should work for private repositories (repo), without having to put your username and password.

How to make unicode string with python3

Literal strings are unicode by default in Python3.

Assuming that text is a bytes object, just use text.decode('utf-8')

unicode of Python2 is equivalent to str in Python3, so you can also write:

str(text, 'utf-8')

if you prefer.

jQuery function to open link in new window

http://www.jquerybyexample.net/2012/05/open-link-in-new-tab-or-new-popup.html

$(document).ready(function() {
$('A.BLAH').click(function() {
var NWin = window.open($(this).prop('href'), '', 'height=600,width=1000');
if (window.focus)
{
NWin.focus();
}
return false;
});
});

Error handling with PHPMailer

Please note!!! You must use the following format when instantiating PHPMailer!

$mail = new PHPMailer(true);

If you don't exceptions are ignored and the only thing you'll get is an echo from the routine! I know this is well after this was created but hopefully it will help someone.

Typescript export vs. default export

Named export

In TS you can export with the export keyword. It then can be imported via import {name} from "./mydir";. This is called a named export. A file can export multiple named exports. Also the names of the imports have to match the exports. For example:

// foo.js file
export class foo{}
export class bar{}

// main.js file in same dir
import {foo, bar} from "./foo";

The following alternative syntax is also valid:

// foo.js file
function foo() {};
function bar() {};
export {foo, bar};

// main.js file in same dir
import {foo, bar} from './foo'

Default export

We can also use a default export. There can only be one default export per file. When importing a default export we omit the square brackets in the import statement. We can also choose our own name for our import.

// foo.js file
export default class foo{}

// main.js file in same directory
import abc from "./foo";

It's just JavaScript

Modules and their associated keyword like import, export, and export default are JavaScript constructs, not typescript. However typescript added the exporting and importing of interfaces and type aliases to it.

How do I set GIT_SSL_NO_VERIFY for specific repos only?

This question keeps coming up and I did not find a satisfying result yet, so here is what worked for me (based on a previous answer https://stackoverflow.com/a/52706362/1806760, which is not working):

My server is https://gitlab.dev with a self-signed certificate.

First run git config --system --edit (from an elevated command prompt, change --system to --global if you want to do it for just your user), then insert the following snippet after any previous [http] sections:

[http "https://gitlab.dev"]
        sslVerify = false

Then check if you did everything correctly:

> git config --type=bool --get-urlmatch http.sslVerify https://gitlab.dev
false

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

As you're using Windows, installation should automatically edit the %PATH% variable. Therefore, I suspect you simply need to reboot your system after installing.

Getting the class name from a static method in Java

Do what @toolkit says. Do not do anything like this:

return new Object() { }.getClass().getEnclosingClass();

(Edit: Or if you are using a Java version that came out well after this answer was originally written, @Rein.)

How to write logs in text file when using java.util.logging.Logger

Firstly, where did you define your logger and from what class\method trying to call it? There is a working example, fresh baked:

public class LoggingTester {
    private final Logger logger = Logger.getLogger(LoggingTester.class
            .getName());
    private FileHandler fh = null;

    public LoggingTester() {
        //just to make our log file nicer :)
        SimpleDateFormat format = new SimpleDateFormat("M-d_HHmmss");
        try {
            fh = new FileHandler("C:/temp/test/MyLogFile_"
                + format.format(Calendar.getInstance().getTime()) + ".log");
        } catch (Exception e) {
            e.printStackTrace();
        }

        fh.setFormatter(new SimpleFormatter());
        logger.addHandler(fh);
    }

    public void doLogging() {
        logger.info("info msg");
        logger.severe("error message");
        logger.fine("fine message"); //won't show because to high level of logging
    }
}   

In your code you forgot to define the formatter, if you need simple one you can do it as I mentioned above, but there is another option, you can format it by yourself, there is an example (just insert it instead of this line fh.setFormatter(new SimpleFormatter()) following code):

fh.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                SimpleDateFormat logTime = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
                Calendar cal = new GregorianCalendar();
                cal.setTimeInMillis(record.getMillis());
                return record.getLevel()
                        + logTime.format(cal.getTime())
                        + " || "
                        + record.getSourceClassName().substring(
                                record.getSourceClassName().lastIndexOf(".")+1,
                                record.getSourceClassName().length())
                        + "."
                        + record.getSourceMethodName()
                        + "() : "
                        + record.getMessage() + "\n";
            }
        });

Or any other modification whatever you like. Hope it helps.

Maven plugins can not be found in IntelliJ

I just delete all my maven plugins stored in .m2\repository\org\apache\maven\plugins, and IntelliJ downloaded all the plugins again a it solve my problem and it worked fine for me!!!

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

To make it more clear(and to put it together) I had to do Two things mentioned above.

1- Create a file /etc/ld.so.conf.d/opencv.conf and write to it the paths of folder where your opencv libraries are stored.(Answer by Cookyt)

2- Include the path of your opencv's .so files in LD_LIBRARY_PATH ()

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/opencv/lib

How To limit the number of characters in JTextField?

Just Try This :

textfield.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
        if(textfield.getText().length()>=5&&!(evt.getKeyChar()==KeyEvent.VK_DELETE||evt.getKeyChar()==KeyEvent.VK_BACK_SPACE)) {
            getToolkit().beep();
            evt.consume();
         }
     }
});

Difference between Git and GitHub

Github is required if you want to collaborate across developers. If you are a single contributor git is enough, make sure you backup your code on regular basis

Removing page title and date when printing web page (with CSS?)

Try this;

@media print{ @page { margin-top: 30px; margin-bottom: 30px;}}

Failure [INSTALL_FAILED_INVALID_APK]

There seems to be multiple reasons for this failure. For me, the issue was that in AndroidManifest file I had referenced a non-existing library(only in this particular device) using the 'uses-library' tag. After removing the library which this device did not have the apk got installed properly.

How to inject window into a service?

Angular 4 introduce InjectToken, and they also create a token for document called DOCUMENT. I think this is the official solution and it works in AoT.

I use the same logic to create a small library called ngx-window-token to prevent doing this over and over.

I have used it in other project and build in AoT without issues.

Here is how I used it in other package

Here is the plunker

In your module

imports: [ BrowserModule, WindowTokenModule ] In your component

constructor(@Inject(WINDOW) _window) { }

How to compare two maps by their values

If you assume that there can be duplicate values the only way to do this is to put the values in lists, sort them and compare the lists viz:

List<String> values1 = new ArrayList<String>(map1.values());
List<String> values2 = new ArrayList<String>(map2.values());
Collections.sort(values1);
Collections.sort(values2);
boolean mapsHaveEqualValues = values1.equals(values2);

If values cannot contain duplicate values then you can either do the above without the sort using sets.

WRONGTYPE Operation against a key holding the wrong kind of value php

This error means that the value indexed by the key "l_messages" is not of type hash, but rather something else. You've probably set it to that other value earlier in your code. Try various other value-getter commands, starting with GET, to see which one works and you'll know what type is actually here.

Random integer in VB.NET

Function xrand() As Long
        Dim r1 As Long = Now.Day & Now.Month & Now.Year & Now.Hour & Now.Minute & Now.Second & Now.Millisecond
        Dim RAND As Long = Math.Max(r1, r1 * 2)
        Return RAND
End Function

[BBOYSE] This its the best way, from scratch :P

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

How to add app icon within phonegap projects?

FAQ: ICON / SPLASH SCREEN (Cordova 5.x / 2015)

I present my answer as a general FAQ that may help you to solve many problems I've encountered while dealing with icons/splash screens. You may find out like me that the documentation is not always very clear nor up to date. This will probably go to StackOverflow documentation when available.

First: answering the question

How can I add custom app icons for iOS and Android with phonegap?

In your version of Cordova the icon tag is useless. It is not even documented in Cordova 3.0.0. You should use the documentation version that fits the cli you are using and not the latest one!

The icon tag does not work for Android at all before the version 3.5.0 according to what I can see in the different versions of the documentation. In 3.4.0 they still advice to manually copy the files

In newer versions: your config.xml looks better for newer Cordova versions. However there are still many things you may want to know. If you decide to upgrade here are some useful things to modify:

  • You don't need the gap: namespace
  • You need <preference name="SplashScreen" value="screen" /> for Android

Here are more details of the questions you might ask yourself when trying to deal with icons and splash screen:

Can I use an old version of Cordova / Phonegap

No, the icon/splashscreen feature was not in former versions of Cordova so you must use a recent version. In former versions, only Phonegap Build did handle the icons/splash screen so building locally and handling icons was only possible with a hook. I don't know the minimum version to use this feature but with 5.1.1 it works fine in both Cordova/Phonegap cli. With Cordova 3.5 it didn't work for me.

Edit: for Android you must use at least 3.5.0

How can I debug the build process about icons?

The cli use a CP command. If you provide an invalid icon path, it will show a cp error:

sebastien@sebastien-xps:cordova (dev *+$%)$ cordova run android --device
cp: no such file or directory: /home/sebastien/Desktop/Stample-react/cordova/res/www/stample_splash.png

Edit: you have use cordova build <platform> --verbose to get logs of cp command usage to see where your icons gets copied

The icons should go in a folder according to the config. For me it goes in many subfolders in : platforms/android/build/intermediates/res/armv7/debug/drawable-hdpi-v4/icon.png

Then you can find the APK, and open it as a zip archive to check the icons are present. They must be in a res/drawable* folder because it's a special folder for Android.

Where should I put the icons/splash screens in my project?

In many examples you will find the icons/splash screens are declared inside a res folder. This res is a special Android folder in the output APK, but it does not mean you have to use a res folder in your project.

You can put your icon anywhere, but the path you use must be relative to the root of the project, and not www so take care! This is documented, but not clearly because all the examples are using res and you don't know where this folder is :(

I mean if you put the icon in www/icon.png you absolutly must include www in your path.

Edit Mars 2016: after upgrading my versions, now it seems that icons are relative to www folder but documentation has not been changed (issue)

Does <icon src="icon.png"/> work?

No it does not!.

On Android, it seems it used to work before (when the density attribute was not supported yet?) but not anymore. See this Cordova issue

On iOS, it seems using this global declaration may override more specific declarations so take care and build with --verbose to ensure everything works as expected.

Can I use the same icon/splash screen file for all the densities.

Yes you can. You can even use the same file for both the icon, and splash screen (just to test!). I have used a "big" icon file of 65kb without any problem.

What's the difference when using the platform tag vs the platform attribute

<icon src="icon.png" platform="android" density="ldpi" />

is the same as

<platform name="android">
    <icon src="www/stample_icon.png" density="ldpi" />
</platform>

Should I use the gap: namespace if using Phonegap?

In my experience new versions of Phonegap or Cordova are both able to understand icon declarations without using any gap: xml namespace.

However I'm still waiting for a valid answer here: cordova/phonegap plugin add VS config.xml

As far as I understand, some features with the gap: namespace may be available earlier in PhonegapBuild, then in Phonegap and then being ported to Cordova (?)

Is <preference name="SplashScreen" value="screen" /> required?

At least for Android yes it is. I opened an issue with additional explainations.

Does icon declaration order matters?

Yes it does! It may not have any impact on Android but it has on iOS according to my tests. This is unexpected and undocumented behavior so I opened another issue.

Do I need cordova-plugin-splashscreen?

Yes this is absolutly required if you want the splash screen to work. The documentation is not clear (issue) and let us think that the plugin is required only to offer a splash screen javascript API.

How can I resize the images for all width/height/densities fastly

There are tools to help you do that. The best one for me is http://makeappicon.com/ but it requires to provide an email address.

Other possible solutions are:

Can you give me an example config?

Yes. Here's my real config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="co.x" version="0.2.6" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>x</name>
    <description>
        x
    </description>
    <author email="[email protected]" href="https://x.co">
        x
    </author>
    <content src="index.html" />
    <preference name="permissions"                  value="none" />
    <preference name="webviewbounce"                value="false" />
    <preference name="StatusBarOverlaysWebView"     value="false" />
    <preference name="StatusBarBackgroundColor"     value="#0177C6" />
    <preference name="detect-data-types"            value="true" />
    <preference name="stay-in-webview"              value="false" />
    <preference name="android-minSdkVersion"        value="14" />
    <preference name="android-targetSdkVersion"     value="22" />
    <preference name="phonegap-version"             value="cli-5.1.1" />

    <preference name="SplashScreenDelay"            value="10000" />
    <preference name="SplashScreen"                 value="screen" />


    <plugin name="cordova-plugin-device"                spec="1.0.1" />
    <plugin name="cordova-plugin-console"               spec="1.0.1" />
    <plugin name="cordova-plugin-whitelist"             spec="1.1.0" />
    <plugin name="cordova-plugin-crosswalk-webview"     spec="1.2.0" />
    <plugin name="cordova-plugin-statusbar"             spec="1.0.1" />
    <plugin name="cordova-plugin-screen-orientation"    spec="1.3.6" />
    <plugin name="cordova-plugin-splashscreen"          spec="2.1.0" />

    <access origin="http://*" />
    <access origin="https://*" />

    <access launch-external="yes" origin="tel:*" />
    <access launch-external="yes" origin="geo:*" />
    <access launch-external="yes" origin="mailto:*" />
    <access launch-external="yes" origin="sms:*" />
    <access launch-external="yes" origin="market:*" />

    <platform name="android">
        <icon src="www/stample_icon.png" density="ldpi" />
        <icon src="www/stample_icon.png" density="mdpi" />
        <icon src="www/stample_icon.png" density="hdpi" />
        <icon src="www/stample_icon.png" density="xhdpi" />
        <icon src="www/stample_icon.png" density="xxhdpi" />
        <icon src="www/stample_icon.png" density="xxxhdpi" />
        <splash src="www/stample_splash.png" density="land-hdpi"/>
        <splash src="www/stample_splash.png" density="land-ldpi"/>
        <splash src="www/stample_splash.png" density="land-mdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-hdpi"/>
        <splash src="www/stample_splash.png" density="port-ldpi"/>
        <splash src="www/stample_splash.png" density="port-mdpi"/>
        <splash src="www/stample_splash.png" density="port-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxxhdpi"/>
    </platform>

    <platform name="ios">
        <icon src="www/stample_icon.png" width="180" height="180" />
        <icon src="www/stample_icon.png" width="60" height="60" />
        <icon src="www/stample_icon.png" width="120" height="120" />
        <icon src="www/stample_icon.png" width="76" height="76" />
        <icon src="www/stample_icon.png" width="152" height="152" />
        <icon src="www/stample_icon.png" width="40" height="40" />
        <icon src="www/stample_icon.png" width="80" height="80" />
        <icon src="www/stample_icon.png" width="57" height="57" />
        <icon src="www/stample_icon.png" width="114" height="114" />
        <icon src="www/stample_icon.png" width="72" height="72" />
        <icon src="www/stample_icon.png" width="144" height="144" />
        <icon src="www/stample_icon.png" width="29" height="29" />
        <icon src="www/stample_icon.png" width="58" height="58" />
        <icon src="www/stample_icon.png" width="50" height="50" />
        <icon src="www/stample_icon.png" width="100" height="100" />
        <splash src="www/stample_splash.png" width="320" height="480"/>
        <splash src="www/stample_splash.png" width="640" height="960"/>
        <splash src="www/stample_splash.png" width="768" height="1024"/>
        <splash src="www/stample_splash.png" width="1536" height="2048"/>
        <splash src="www/stample_splash.png" width="1024" height="768"/>
        <splash src="www/stample_splash.png" width="2048" height="1536"/>
        <splash src="www/stample_splash.png" width="640" height="1136"/>
        <splash src="www/stample_splash.png" width="750" height="1334"/>
        <splash src="www/stample_splash.png" width="1242" height="2208"/>
        <splash src="www/stample_splash.png" width="2208" height="1242"/>
    </platform>

    <allow-intent href="*" />
    <engine name="browser" spec="^3.6.0" />
    <engine name="android" spec="^4.0.2" />
</widget>

A good source of examples are starter kits. Like phonegap-start or Ionic starter

Fixed Table Cell Width

table { 
    table-layout:fixed; width:200px;
}
table tr {
    height: 20px;
}

10x10

python pip on Windows - command 'cl.exe' failed

  1. Install Microsoft visual c++ 14.0 build tool.(Windows 7)
  2. create a virtual environment using conda.
  3. Activate the environment and use conda to install the necessary package.

For example: conda install -c conda-forge spacy

How do I copy the contents of one ArrayList into another?

Here is a workaround to copy all the objects from one arrayList to another:

 ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();

myObject.addAll(myTempObject.subList(0, myTempObject.size()));

subList is intended to return a List with a range of data. so you can copy the whole arrayList or part of it.

How to clear the canvas for redrawing

Given that canvas is a canvas element,

const context = canvas.getContext('2d');

context.clearRect(0, 0, canvas.width, canvas.height);

Function in JavaScript that can be called only once

Point to an empty function once it has been called:

_x000D_
_x000D_
function myFunc(){
     myFunc = function(){}; // kill it as soon as it was called
     console.log('call once and never again!'); // your stuff here
};
_x000D_
<button onClick=myFunc()>Call myFunc()</button>
_x000D_
_x000D_
_x000D_


Or, like so:

_x000D_
_x000D_
var myFunc = function func(){
     if( myFunc.fired ) return;
     myFunc.fired = true;
     console.log('called once and never again!'); // your stuff here
};

// even if referenced & "renamed"
((refToMyfunc)=>{
  setInterval(refToMyfunc, 1000);
})(myFunc)
_x000D_
_x000D_
_x000D_

Java: Date from unix timestamp

For kotlin

fun unixToDate(timeStamp: Long) : String? {
    val time = java.util.Date(timeStamp as Long * 1000)
    val sdf = SimpleDateFormat("yyyy-MM-dd")
    return sdf.format(time)

}

How to set proper codeigniter base url?

Well that's very interesting, Here is quick and working code:

index.php

/**
 * Define APP_URL Dynamically
 * Write this at the bottom of index.php
 *
 * Automatic base url
 */
define('APP_URL', ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . "://{$_SERVER['SERVER_NAME']}".str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME'])); 

config.php

/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
|   http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = APP_URL;

CodeIgniter ROCKS!!! :)

Resolve conflicts using remote changes when pulling from Git remote

You can either use the answer from the duplicate link pointed by nvm.

Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):

git pull -s recursive -X theirs

How to find out whether a file is at its `eof`?

Get the EOF position of the file:

def get_eof_position(file_handle):
    original_position = file_handle.tell()
    eof_position = file_handle.seek(0, 2)
    file_handle.seek(original_position)
    return eof_position

and compare it with the current position: get_eof_position == file_handle.tell().

How do I get a file's last modified time in Perl?

Calling the built-in function stat($fh) returns an array with the following information about the file handle passed in (from the perlfunc man page for stat):

  0 dev      device number of filesystem
  1 ino      inode number
  2 mode     file mode  (type and permissions)
  3 nlink    number of (hard) links to the file
  4 uid      numeric user ID of file's owner
  5 gid      numeric group ID of file's owner
  6 rdev     the device identifier (special files only)
  7 size     total size of file, in bytes
  8 atime    last access time since the epoch
  9 mtime    last modify time since the epoch
 10 ctime    inode change time (NOT creation time!) since the epoch
 11 blksize  preferred block size for file system I/O
 12 blocks   actual number of blocks allocated

Element number 9 in this array will give you the last modified time since the epoch (00:00 January 1, 1970 GMT). From that you can determine the local time:

my $epoch_timestamp = (stat($fh))[9];
my $timestamp       = localtime($epoch_timestamp);

Alternatively, you can use the built-in module File::stat (included as of Perl 5.004) for a more object-oriented interface.

And to avoid the magic number 9 needed in the previous example, additionally use Time::localtime, another built-in module (also included as of Perl 5.004). Together these lead to some (arguably) more legible code:

use File::stat;
use Time::localtime;
my $timestamp = ctime(stat($fh)->mtime);

Folder is locked and I can't unlock it

I was moving a folder up one level and into another folder. My mistake was doing the move from within the parent folder.

Bad example:

pwd -> C:\Repo\ParentDir\
svn move ./DirtoCopy ../AnotherDir

SVN needs to update the parent directory with the deleted folders info.
You have to do it from the common root of the source and destination folders or use full paths.

Good example:

svn move C:\Repo\ParentDir\DirtoCopy C:\Repo\NewLocation

How do I create JavaScript array (JSON format) dynamically?

Our array of objects

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

with for...in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

or with Array.prototype.map(), which is much cleaner:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

You can also use the Secure Template Overloads, they will help you replace the unsecure calls with secure ones anywhere it is possible to easily deduce buffer size (static arrays).

Just add the following:

#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 

Then fix the remaining warnings by hand, by using the _s functions.

How do I do word Stemming or Lemmatization?

I tried your list of terms on this snowball demo site and the results look okay....

  • cats -> cat
  • running -> run
  • ran -> ran
  • cactus -> cactus
  • cactuses -> cactus
  • community -> communiti
  • communities -> communiti

A stemmer is supposed to turn inflected forms of words down to some common root. It's not really a stemmer's job to make that root a 'proper' dictionary word. For that you need to look at morphological/orthographic analysers.

I think this question is about more or less the same thing, and Kaarel's answer to that question is where I took the second link from.

Apache Spark: The number of cores vs. the number of executors

From the excellent resources available at RStudio's Sparklyr package page:

SPARK DEFINITIONS:

It may be useful to provide some simple definitions for the Spark nomenclature:

Node: A server

Worker Node: A server that is part of the cluster and are available to run Spark jobs

Master Node: The server that coordinates the Worker nodes.

Executor: A sort of virtual machine inside a node. One Node can have multiple Executors.

Driver Node: The Node that initiates the Spark session. Typically, this will be the server where sparklyr is located.

Driver (Executor): The Driver Node will also show up in the Executor list.

CREATE DATABASE permission denied in database 'master' (EF code-first)

I had the same problem. This what worked for me:

  1. Go to SQL Server Management Studio and run it as Administrator.
  2. Choose Security -> Then Logins
  3. Choose the usernames or whatever users that will access your database under the Logins and Double Click it.
  4. Give them a Server Roles that will give them credentials to create database. On my case, public was already checked so I checked dbcreator and sysadmin.
  5. Run update-database again on Package Manager Console. Database should now successfully created.

Here is an image so that you can get the bigger picture, I blurred my credentials of course:enter image description here

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

Some currency pairs have no historical data for certain days.

Compare =GOOGLEFINANCE("CURRENCY:EURNOK", "close", DATE(2016,1,1), DATE(2016,1,12):

Date                Close
1/1/2016 23:58:00   9.6248922
1/2/2016 23:58:00   9.632922114
1/3/2016 23:58:00   9.579957264
1/4/2016 23:58:00   9.609146435
1/5/2016 23:58:00   9.573877808
1/6/2016 23:58:00   9.639368875
1/7/2016 23:58:00   9.707103569
1/8/2016 23:58:00   9.673324479
1/9/2016 23:58:00   9.702379872
1/10/2016 23:58:00  9.702721875
1/11/2016 23:58:00  9.705679083

and =GOOGLEFINANCE("CURRENCY:EURRUB", "close", DATE(2016,1,1), DATE(2016,1,12):

Date                Close
1/1/2016 23:58:00   79.44402768
1/4/2016 23:58:00   79.14048175
1/5/2016 23:58:00   80.0452446
1/6/2016 23:58:00   80.3761125
1/7/2016 23:58:00   81.70830185
1/8/2016 23:58:00   81.70680013
1/11/2016 23:58:00  82.50853122

So, =INDEX(GOOGLEFINANCE("CURRENCY:EURRUB", "close", DATE(2016,1,1)), 2, 2) gives

79.44402768

But =INDEX(GOOGLEFINANCE("CURRENCY:EURRUB", "close", DATE(2016,1,2)), 2, 2) gives

#N/A

Therefore, when working with currency pairs that have no exchange rates for weekends/holidays, the following formula may be used for getting the exchange rate for the first following working day:

=INDEX(GOOGLEFINANCE("CURRENCY:EURRUB", "close", DATE(2016,1,2), 4), 2, 2)

Laravel 5 Class 'form' not found

I have tried everything, but only this helped:

php artisan route:clear
php artisan cache:clear

Create SQL script that create database and tables

Yes, you can add as many SQL statements into a single script as you wish. Just one thing to note: the order matters. You can't INSERT into a table until you CREATE it; you can't set a foreign key until the primary key is inserted.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

In your app/config/parameters.yml

# This file is auto-generated during the composer install
parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: 3306
    database_name: symfony
    database_user: root
    database_password: "your_password"
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: en
    secret: ThisTokenIsNotSoSecretChangeIt

The value of database_password should be within double or single quotes as in: "your_password" or 'your_password'.

I have seen most of users experiencing this error because they are using password with leading zero or numeric values.

Error :The remote server returned an error: (401) Unauthorized

I add credentials for HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

Laravel - display a PDF file in storage without forcing download?

Ben Swinburne's answer is absolutely correct - he deserves the points! For me though the answer left be dangling a bit in Laravel 5.1 which made me research — and in 5.2 (which inspired this answer) there's a a new way to do it quickly.

Note: This answer contains hints to support UTF-8 filenames, but it is recommended to take cross platform support into consideration !

In Laravel 5.2 you can now do this:

$pathToFile = '/documents/filename.pdf'; // or txt etc.

// when the file name (display name) is decided by the name in storage,
// remember to make sure your server can store your file name characters in the first place (!)
// then encode to respect RFC 6266 on output through content-disposition
$fileNameFromStorage = rawurlencode(basename($pathToFile));

// otherwise, if the file in storage has a hashed file name (recommended)
// and the display name comes from your DB and will tend to be UTF-8
// encode to respect RFC 6266 on output through content-disposition
$fileNameFromDatabase = rawurlencode('??????????.pdf');

// Storage facade path is relative to the root directory
// Defined as "storage/app" in your configuration by default
// Remember to import Illuminate\Support\Facades\Storage
return response()->file(storage_path($pathToFile), [
    'Content-Disposition' => str_replace('%name', $fileNameFromDatabase, "inline; filename=\"%name\"; filename*=utf-8''%name"),
    'Content-Type'        => Storage::getMimeType($pathToFile), // e.g. 'application/pdf', 'text/plain' etc.
]);

And in Laravel 5.1 you can add above method response()->file() as a fallback through a Service Provider with a Response Macro in the boot method (make sure to register it using its namespace in config/app.php if you make it a class). Boot method content:

// Be aware that I excluded the Storage::exists() and / or try{}catch(){}
$factory->macro('file', function ($pathToFile, array $userHeaders = []) use ($factory) {

    // Storage facade path is relative to the root directory
    // Defined as "storage/app" in your configuration by default
    // Remember to import Illuminate\Support\Facades\Storage
    $storagePath         = str_ireplace('app/', '', $pathToFile); // 'app/' may change if different in your configuration
    $fileContents        = Storage::get($storagePath);
    $fileMimeType        = Storage::getMimeType($storagePath); // e.g. 'application/pdf', 'text/plain' etc.
    $fileNameFromStorage = basename($pathToFile); // strips the path and returns filename with extension

    $headers = array_merge([
        'Content-Disposition' => str_replace('%name', $fileNameFromStorage, "inline; filename=\"%name\"; filename*=utf-8''%name"),
        'Content-Length'      => strlen($fileContents), // mb_strlen() in some cases?
        'Content-Type'        => $fileMimeType,
    ], $userHeaders);

    return $factory->make($fileContents, 200, $headers);
});

Some of you don't like Laravel Facades or Helper Methods but that choice is yours. This should give you pointers if Ben Swinburne's answer doesn't work for you.

Opinionated note: You shouldn't store files in a DB. Nonetheless, this answer will only work if you remove the Storage facade parts, taking in the contents instead of the path as the first parameter as with the @BenSwinburne answer.

Android Linear Layout - How to Keep Element At Bottom Of View?

You should put the parameter gravity to bottom not in the textview but in the Linear Layout. Like this:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="bottom|end">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Something"/>
</LinearLayout>

Modifying CSS class property values on the fly with JavaScript / jQuery

This may be late to the discussion, but I needed something like what is being talked about here, but didn't find anything that really did what I wanted, and did it easily. What I needed was to hide and show numerous elements without explicitly visiting each element individually to update them in some way that changed the display style to and from hidden. So I came up with the following:

<style>
  /* The bulk of the css rules should go here or in an external css file */
  /* None of these rules will be changed, but may be overridden */
  .aclass { display: inline-block; width: 50px; height: 30px; }
</style>
<style id="style">
  /* Only the rules to be changed should go in this style */
  .bclass { display: inline-block; }
</style>
<script>
  //
  // This is a helper function that returns the named style as an object.
  // This could also be done in other ways.
  // 
  function setStyle() { return document.getElementById( 'style' ); }
</script>
<div id="d1" class="aclass" style="background-color: green;">
  Hi
</div>
<!-- The element to be shown and hidden --> 
<div id="d2" class="aclass bclass" style="background-color: yellow;">
  there
</div>
<div id="d3" class="aclass" style="background-color: lightblue;">
  sailor
</div>
<hr />
<!-- These buttons demonstrate hiding and showing the d3 dive element -->
<button onclick="setStyle().innerHTML = '.bclass { display: none; }';">
  Hide
</button>&nbsp;&nbsp;
<button onclick="setStyle().innerHTML = '.bclass { display: inline-block; }';">
  Show
</button>

By toggling the bclass rule in the embedded and named stylesheet, which comes after the any other relevant style sheets, in this case one with the aclass rule, I could update the just the display css rule in one place and have it override the aclass rule, which also had it's own display rule.

The beauty of this technique is that it is so simple, effectively one line that does the actual work, it doesn't require any libraries, such as JQuery or plug-ins, and the real work of updating all of the places where the change applies is performed by the browser's css core functionality, not in JavaScript. Also, it works in IE 9 and above, Chrome, Safari, Opera, and all of the other browsers that MicroSoft Edge could emulate, for desktop and tablet/phones devices.

Formatting doubles for output in C#

I found this quick fix.

    double i = 10 * 0.69;
    System.Diagnostics.Debug.WriteLine(i);


    String s = String.Format("{0:F20}", i).Substring(0,20);
    System.Diagnostics.Debug.WriteLine(s + " " +s.Length );

Barcode scanner for mobile phone for Website in form

Scandit is a startup whose goal is to replace bulky, expensive laser barcode scanners with cheap mobile phones.

There are SDKs for Android, iOS, Windows, C API/Linux, React Native, Cordova/PhoneGap, Xamarin.

There is also Scandit Barcode Scanner SDK for the Web which the WebAssembly version of the SDK. It runs in modern browsers, also on phones.

There's a client library that also provides a barcode picker component. It can be used like this:

<div id="barcode-picker" style="max-width: 1280px; max-height: 80%;"></div>

<script src="https://unpkg.com/scandit-sdk"></script>
<script>
    console.log('Loading...');
    ScanditSDK.configure("xxx", {
engineLocation: "https://unpkg.com/scandit-sdk/build/"
    }).then(() => {
      console.log('Loaded');
      ScanditSDK.BarcodePicker.create(document.getElementById('barcode-picker'), {
        playSoundOnScan: true,
        vibrateOnScan: true
      }).then(function(barcodePicker) {
        console.log("Ready");
        barcodePicker.applyScanSettings(new ScanditSDK.ScanSettings({
          enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39", "code93", "itf", "qr"],
          codeDuplicateFilter: 1000
        }));
        barcodePicker.onScan(function(barcodes) {
          console.log(barcodes);
        });
      });
    });
</script>

Disclaimer: I work for Scandit

How do I use 3DES encryption/decryption in Java?

Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the contents). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:

import java.security.MessageDigest;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class TripleDESTest {

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

        String text = "kyle boon";

        byte[] codedtext = new TripleDESTest().encrypt(text);
        String decodedtext = new TripleDESTest().decrypt(codedtext);

        System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
        System.out.println(decodedtext); // This correctly shows "kyle boon"
    }

    public byte[] encrypt(String message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        final byte[] plainTextBytes = message.getBytes("utf-8");
        final byte[] cipherText = cipher.doFinal(plainTextBytes);
        // final String encodedCipherText = new sun.misc.BASE64Encoder()
        // .encode(cipherText);

        return cipherText;
    }

    public String decrypt(byte[] message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        decipher.init(Cipher.DECRYPT_MODE, key, iv);

        // final byte[] encData = new
        // sun.misc.BASE64Decoder().decodeBuffer(message);
        final byte[] plainText = decipher.doFinal(message);

        return new String(plainText, "UTF-8");
    }
}

How to trigger an event after using event.preventDefault()

Nope. Once the event has been canceled, it is canceled.

You can re-fire the event later on though, using a flag to determine whether your custom code has already run or not - such as this (please ignore the blatant namespace pollution):

var lots_of_stuff_already_done = false;

$('.button').on('click', function(e) {
    if (lots_of_stuff_already_done) {
        lots_of_stuff_already_done = false; // reset flag
        return; // let the event bubble away
    }

    e.preventDefault();

    // do lots of stuff

    lots_of_stuff_already_done = true; // set flag
    $(this).trigger('click');
});

A more generalized variant (with the added benefit of avoiding the global namespace pollution) could be:

function onWithPrecondition(callback) {
    var isDone = false;

    return function(e) {
        if (isDone === true)
        {
            isDone = false;
            return;
        }

        e.preventDefault();

        callback.apply(this, arguments);

        isDone = true;
        $(this).trigger(e.type);
    }
}

Usage:

var someThingsThatNeedToBeDoneFirst = function() { /* ... */ } // do whatever you need
$('.button').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst));

Bonus super-minimalistic jQuery plugin with Promise support:

(function( $ ) {
    $.fn.onButFirst = function(eventName,         /* the name of the event to bind to, e.g. 'click' */
                               workToBeDoneFirst, /* callback that must complete before the event is re-fired */
                               workDoneCallback   /* optional callback to execute before the event is left to bubble away */) {
        var isDone = false;

        this.on(eventName, function(e) {
            if (isDone === true) {
                isDone = false;
                workDoneCallback && workDoneCallback.apply(this, arguments);
                return;
            }

            e.preventDefault();

            // capture target to re-fire event at
            var $target = $(this);

            // set up callback for when workToBeDoneFirst has completed
            var successfullyCompleted = function() {
                isDone = true;
                $target.trigger(e.type);
            };

            // execute workToBeDoneFirst callback
            var workResult = workToBeDoneFirst.apply(this, arguments);

            // check if workToBeDoneFirst returned a promise
            if (workResult && $.isFunction(workResult.then))
            {
                workResult.then(successfullyCompleted);
            }
            else
            {
                successfullyCompleted();
            }
        });

        return this;
    };
}(jQuery));

Usage:

$('.button').onButFirst('click',
    function(){
        console.log('doing lots of work!');
    },
    function(){
        console.log('done lots of work!');
    });

Declare Variable for a Query String

Using EXEC

You can use following example for building SQL statement.

DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London'''
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand)

Using sp_executesql

With using this approach you can ensure that the data values being passed into the query are the correct datatypes and avoind use of more quotes.

DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = 'London'
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

Reference

Passing data from controller to view in Laravel

try with this code :

Controller:
-----------------------------
 $fromdate=date('Y-m-d',strtotime(Input::get('fromdate'))); 
        $todate=date('Y-m-d',strtotime(Input::get('todate'))); 

 $datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To 
        return view('inventoryreport/inventoryreportview', compact('datas'));

View Page : 
@foreach($datas as $student)
   {{$student}}

@endforeach
[Link here]

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

How do I shrink my SQL Server Database?

DBCC SHRINKDATABASE works for me, but this is its full syntax:

DBCC SHRINKDATABASE ( database_name, [target_percent], [truncate] )

where target_percent is the desired percentage of free space left in the database file after the database has been shrunk.

And truncate parameter can be:

NOTRUNCATE

Causes the freed file space to be retained in the database files. If not specified, the freed file space is released to the operating system.

TRUNCATEONLY

Causes any unused space in the data files to be released to the operating system and shrinks the file to the last allocated extent, reducing the file size without moving any data. No attempt is made to relocate rows to unallocated pages. target_percent is ignored when TRUNCATEONLY is used.

...and yes no_one is right, shrinking datbase is not very good practice becasue for example :

shrink on data files are excellent ways to introduce significant logical fragmentation, becasue it moves pages from the end of the allocated range of a database file to somewhere at the front of the file...

shrink database can have a lot of consequence on database, server.... think a lot about it before you do it!

on the web there are a lot of blogs and articles about it.

Jquery: How to check if the element has certain css class/style

if($('#someElement').hasClass('test')) {
  ... do something ...
}
else {
  ... do something else ...
}

Round up to Second Decimal Place in Python

The python round function could be rounding the way not you expected.

You can be more specific about the rounding method by using Decimal.quantize

eg.

from decimal import Decimal, ROUND_HALF_UP
res = Decimal('0.25').quantize(Decimal('0.0'), rounding=ROUND_HALF_UP)
print(res) 
# prints 0.3

More reference:

https://gist.github.com/jackiekazil/6201722

Java 8 Stream API to find Unique Object matching a property value

Instead of using a collector try using findFirst or findAny.

Optional<Person> matchingObject = objects.stream().
    filter(p -> p.email().equals("testemail")).
    findFirst();

This returns an Optional since the list might not contain that object.

If you're sure that the list always contains that person you can call:

Person person = matchingObject.get();

Be careful though! get throws NoSuchElementException if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent or better, use ifPresent, map, orElse or any of the other alternatives found in the Optional class).

If you're okay with a null reference if there is no such person, then:

Person person = matchingObject.orElse(null);

If possible, I would try to avoid going with the null reference route though. Other alternatives methods in the Optional class (ifPresent, map etc) can solve many use cases. Where I have found myself using orElse(null) is only when I have existing code that was designed to accept null references in some cases.


Optionals have other useful methods as well. Take a look at Optional javadoc.

How to retrieve a module's path?

you can just import your module then hit its name and you'll get its full path

>>> import os
>>> os
<module 'os' from 'C:\\Users\\Hassan Ashraf\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\os.py'>
>>>

Add regression line equation and R^2 on graph

I've modified Ramnath's post to a) make more generic so it accepts a linear model as a parameter rather than the data frame and b) displays negatives more appropriately.

lm_eqn = function(m) {

  l <- list(a = format(coef(m)[1], digits = 2),
      b = format(abs(coef(m)[2]), digits = 2),
      r2 = format(summary(m)$r.squared, digits = 3));

  if (coef(m)[2] >= 0)  {
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
  } else {
    eq <- substitute(italic(y) == a - b %.% italic(x)*","~~italic(r)^2~"="~r2,l)    
  }

  as.character(as.expression(eq));                 
}

Usage would change to:

p1 = p + geom_text(aes(x = 25, y = 300, label = lm_eqn(lm(y ~ x, df))), parse = TRUE)

How to get table cells evenly spaced?

Take the width of the table and divide it by the number of cell ().

PerformanceTable {width:500px;}    
PerformanceTable.td {width:100px;}

If the table dynamically widens or shrinks you could dynamically increase the cell size with a little javascript.

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

Have you installed a different version JRE after , while using previous version of JRE in Eclipse .

if Not than :

  1. Right click on your project -> Build Path -> Configure Build Path
  2. Go to 'Libraries' tab
  3. Add Library -> JRE System Library -> Next -> Workspace default JRE (or you can Choose Alternate JRE form your System) -> Finish

if Yes than .

  1. Right click on your project -> Build Path -> Configure Build Path
  2. Go to 'Libraries' tab
  3. Remove Previous Version
  4. Add Library -> JRE System Library -> Next -> Workspace default JRE (or you can Choose Alternate JRE from your System) -> Finish

How to secure phpMyAdmin

In newer versions of phpMyAdmin access permissions for user-names + ip-addresses can be set up inside the phpMyAdmin's config.inc.php file. This is a much better and more robust method of restricting access (over hard-coding URLs and IP addresses into Apache's httpd.conf).

Here is a full example of how to switch to white-listing all users (no one outside this list will be allowed access), and also how to restrict user root to the local system and network only.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'deny,allow';
$cfg['Servers'][$i]['AllowDeny']['rules'] = array(
    'deny % from all', // deny everyone by default, then -

    'allow % from 127.0.0.1', // allow all local users
    'allow % from ::1',

    //'allow % from SERVER_ADDRESS', // allow all from server IP

    // allow user:root access from these locations (local network)
    'allow root from localhost',
    'allow root from 127.0.0.1',
    'allow root from 10.0.0.0/8',
    'allow root from 172.16.0.0/12',
    'allow root from 192.168.0.0/16',

    'allow root from ::1',

    // add more usernames and their IP (or IP ranges) here -    
    );

Source: How to Install and Secure phpMyAdmin on localhost for Windows

This gives you much more fine-grained access restrictions than Apache's URL permissions or an .htaccess file can provide, at the MySQL user name level.

Make sure that the user you are login in with, has its MySQL Host: field set to 127.0.0.1 or ::1, as phpMyAdmin and MySQL are on the same system.

How do I print the elements of a C++ vector in GDB?

With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:

print *(myVector._M_impl._M_start)@myVector.size()

To print only the first N elements, do:

print *(myVector._M_impl._M_start)@N

Explanation

This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:

myVector._M_impl._M_start 

And the GDB command to print N elements of an array starting at pointer P is:

print P@N

Or, in a short form (for a standard .gdbinit):

p P@N

How to Convert datetime value to yyyymmddhhmmss in SQL server?

Since SQL Server Version 2012 you can use:

SELECT format(getdate(),'yyyyMMddHHmmssffff')

get value from DataTable

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

Get column index from column name in python pandas

To modify DSM's answer a bit, get_loc has some weird properties depending on the type of index in the current version of Pandas (1.1.5) so depending on your Index type you might get back an index, a mask, or a slice. This is somewhat frustrating for me because I don't want to modify the entire columns just to extract one variable's index. Much simpler is to avoid the function altogether:

list(df.columns).index('pear')

Very straightforward and probably fairly quick.

Getting byte array through input type = file

This is simple way to convert files to Base64 and avoid "maximum call stack size exceeded at FileReader.reader.onload" with the file has big size.

_x000D_
_x000D_
document.querySelector('#fileInput').addEventListener('change',   function () {_x000D_
_x000D_
    var reader = new FileReader();_x000D_
    var selectedFile = this.files[0];_x000D_
_x000D_
    reader.onload = function () {_x000D_
        var comma = this.result.indexOf(',');_x000D_
        var base64 = this.result.substr(comma + 1);_x000D_
        console.log(base64);_x000D_
    }_x000D_
    reader.readAsDataURL(selectedFile);_x000D_
}, false);
_x000D_
<input id="fileInput" type="file" />
_x000D_
_x000D_
_x000D_

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

iPhone Debugging: How to resolve 'failed to get the task for process'?

The ad-hoc profile doesn't support debugging. You need to debug with a Development profile, and use the Ad-Hoc profile only for distributing non-debuggable copies.