Programs & Examples On #Onbeforeunload

The onbeforeunload event is triggered before a user navigates away. This event listener can be used to show a confirmation dialog to the user on page leave.

How can I override the OnBeforeUnload dialog and replace it with my own?

You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.

function onunload = (){
    window.open('logout.php');
}

This code called when user leave the page or close the active window and user logged out by 'logout.php'. The new window close immediately when logout php consist of code:

window.close();

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

This is an easy way to present the message if any data is input into the form, and not to show the message if the form is submitted:

$(function () {
    $("input, textarea, select").on("input change", function() {
        window.onbeforeunload = window.onbeforeunload || function (e) {
            return "You have unsaved changes.  Do you want to leave this page and lose your changes?";
        };
    });
    $("form").on("submit", function() {
        window.onbeforeunload = null;
    });
})

jQuery UI Dialog OnBeforeUnload

This works for me:

_x000D_
_x000D_
window.addEventListener("beforeunload", function(event) {_x000D_
  event.returnValue = "You may have unsaved Data";_x000D_
});
_x000D_
_x000D_
_x000D_

Prevent a webpage from navigating away using JavaScript

In Ayman's example by returning false you prevent the browser window/tab from closing.

window.onunload = function () {
  alert('You are trying to leave.');
  return false;
}

Add column with number of days between dates in DataFrame pandas

How about this:

times['days_since'] = max(list(df.index.values))  
times['days_since'] = times['days_since'] - times['months']  
times

Proper way to get page content

A simple, fast way to get the content by id :

echo get_post_field('post_content', $id);

And if you want to get the content formatted :

echo apply_filters('the_content', get_post_field('post_content', $id));

Works with pages, posts & custom posts.

CAST to DECIMAL in MySQL

An alternative, I think for your purpose, is to use the round() function:

select round((10 * 1.5),2) // prints 15.00

You can try it here:

What is the simplest C# function to parse a JSON string into an object?

I think this is what you want:

JavaScriptSerializer JSS = new JavaScriptSerializer();
T obj = JSS.Deserialize<T>(String);

How to add Python to Windows registry

When installing Python 3.4 the "Add python.exe to Path" came up unselected. Re-installed with this selected and problem resolved.

Android: set view style programmatically

Technically you can apply styles programmatically, with custom views anyway:

private MyRelativeLayout extends RelativeLayout {
  public MyRelativeLayout(Context context) {
     super(context, null, R.style.LightStyle);
  }
}

The one argument constructor is the one used when you instantiate views programmatically.

So chain this constructor to the super that takes a style parameter.

RelativeLayout someLayout = new MyRelativeLayout(new ContextThemeWrapper(this,R.style.RadioButton));

Or as @Dori pointed out simply:

RelativeLayout someLayout = new RelativeLayout(new ContextThemeWrapper(activity,R.style.LightStyle));

Now in Kotlin:

class MyRelativeLayout @JvmOverloads constructor(
    context: Context, 
    attributeSet: AttributeSet? = null, 
    defStyleAttr: Int = R.style.LightStyle,
) : RelativeLayout(context, attributeSet, defStyleAttr)

or

 val rl = RelativeLayout(ContextThemeWrapper(activity, R.style.LightStyle))

Why javascript getTime() is not a function?

For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.

I was facing this error because I tried to compare two dates using the following Method

var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator

However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.

Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime() method was simply not added to the prototype.

Solution

In this case, recreating a date-Object based on your dates will fix the issue.

var res = new Date(dat1).getTime() > new Date(dat2).getTime()

Edit:

I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.

The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.

class Details {
    description: string;
    date: Date;
    score: number;
    approved: boolean;

    constructor(data: any) {
      Object.assign(this, data);
    }
}

and to perform the mapping:

public getDetails(id: number): Promise<Details> {
    return this.http
               .get<Details>(`${this.baseUrl}/api/details/${id}`)
               .map(response => new Details(response.json()))
               .toPromise();
}

for arrays use:

public getDetails(): Promise<Details[]> {
    return this.http
               .get<Details>(`${this.baseUrl}/api/details`)
               .map(response => {
                   const array = JSON.parse(response.json()) as any[];
                   const details = array.map(data => new Details(data));
                   return details;
               })
               .toPromise();
}

For credits and further information about this topic follow the link.

How to split a string and assign it to variables

Two steps, for example,

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := strings.Split("127.0.0.1:5432", ":")
    ip, port := s[0], s[1]
    fmt.Println(ip, port)
}

Output:

127.0.0.1 5432

One step, for example,

package main

import (
    "fmt"
    "net"
)

func main() {
    host, port, err := net.SplitHostPort("127.0.0.1:5432")
    fmt.Println(host, port, err)
}

Output:

127.0.0.1 5432 <nil>

How to resize images proportionally / keeping the aspect ratio?

This totally worked for me for a draggable item - aspectRatio:true

.appendTo(divwrapper).resizable({
    aspectRatio: true,
    handles: 'se',
    stop: resizestop 
})

Finding all the subsets of a set

Here's some pseudocode. You can cut same recursive calls by storing the values for each call as you go and before recursive call checking if the call value is already present.

The following algorithm will have all the subsets excluding the empty set.

list * subsets(string s, list * v){
    if(s.length() == 1){
        list.add(s);    
        return v;
    }
    else
    {
        list * temp = subsets(s[1 to length-1], v);     
        int length = temp->size();

        for(int i=0;i<length;i++){
            temp.add(s[0]+temp[i]);
        }

        list.add(s[0]);
        return temp;
    }
}

How do I connect to mongodb with node.js (and authenticate)?

Slight typo with Chris' answer.

Db.authenticate(user, password, function({ // callback }));

should be

Db.authenticate(user, password, function(){ // callback } );

Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.

How to get scrollbar position with Javascript?

if you care for the whole page. you can use this:

_x000D_
_x000D_
document.body.getBoundingClientRect().top
_x000D_
_x000D_
_x000D_

How to properly assert that an exception gets raised in pytest?

Better practice will be using a class that inherit unittest.TestCase and running self.assertRaises.

For example:

import unittest


def whatever():
    return 9/0


class TestWhatEver(unittest.TestCase):

    def test_whatever():
        with self.assertRaises(ZeroDivisionError):
            whatever()

Then you would execute it by running:

pytest -vs test_path

How to implement the ReLU function in Numpy

ReLU(x) also is equal to (x+abs(x))/2

creating an array of structs in c++

It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:

#include <iostream>

using namespace std;

int main()
{
    int pause;

    struct Customer
    {
           int uid;
           string name;
    };

    Customer customerRecords[2];
    customerRecords[0] = {25, "Bob Jones"};
    customerRecords[1] = {26, "Jim Smith"};
    cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
    cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
    cin >> pause;
return 0;
}

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

The first version is preferable:

  • It works for all kinds of keys, so you can, for example, say {1: 'one', 2: 'two'}. The second variant only works for (some) string keys. Using different kinds of syntax depending on the type of the keys would be an unnecessary inconsistency.
  • It is faster:

    $ python -m timeit "dict(a='value', another='value')"
    1000000 loops, best of 3: 0.79 usec per loop
    $ python -m timeit "{'a': 'value','another': 'value'}"
    1000000 loops, best of 3: 0.305 usec per loop
    
  • If the special syntax for dictionary literals wasn't intended to be used, it probably wouldn't exist.

How can I get the application's path in a .NET console application?

For Console Applications, you can try this:

System.IO.Directory.GetCurrentDirectory();

Output (on my local machine):

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug

Or you can try (there's an additional backslash in the end):

AppDomain.CurrentDomain.BaseDirectory

Output:

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug\

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?

Also, have you perhaps changed the file's properties' Build Action to something other than Compile?

How to multi-line "Replace in files..." in Notepad++

This is a subjective opinion, but I think a text editor shouldn't do everything and the kitchen sink. I prefer lightweight flexible and powerful (in their specialized fields) editors. Although being mostly a Windows user, I like the Unix philosophy of having lot of specialized tools that you can pipe together (like the UnxUtils) rather than a monster doing everything, but not necessarily as you would like it!

Find in files is on the border of these extra features, but useful when you can double-click on a found line to open the file at the right line. Note that initially, in SciTE it was just a Tools call to grep or equivalent!
FTP is very close to off topic, although it can be seen as an extended open/save dialog.
Replace in files is too much IMO: it is dangerous (you can mess lot of files at once) if you have no preview, etc. I would rather use a specialized tool I chose, perhaps among those in Multi line search and replace tool.

To answer the question, looking at N++, I see a Run menu where you can launch any tool, with assignment of a name and shortcut key. I see also Plugins > NppExec, which seems able to launch stuff like sed (not tried it).

In C - check if a char exists in a char array

The equivalent C code looks like this:

#include <stdio.h>
#include <string.h>

// This code outputs: h is in "This is my test string"
int main(int argc, char* argv[])
{
   const char *invalid_characters = "hz";
   char *mystring = "This is my test string";
   char *c = mystring;
   while (*c)
   {
       if (strchr(invalid_characters, *c))
       {
          printf("%c is in \"%s\"\n", *c, mystring);
       }

       c++;
   }

   return 0;
}

Note that invalid_characters is a C string, ie. a null-terminated char array.

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

Simply install Win64 OpenSSL v1.0.2a or Win32 OpenSSL v1.0.2a, you can download these from http://slproweb.com/products/Win32OpenSSL.html. Works out of the box, no configuration needed.

Hide header in stack navigator React navigation

Add new navigationOptions object in the stackNavigator.

Try this :

const MainNavigator = createStackNavigator({
  LoginPage: {screen : LoginPageContainer, navigationOptions: { header: null } },
  MiddlePage: {screen : MiddlePageContainer, navigationOptions: { header: null } },
  SMS: {screen: ShowSmsContainer, navigationOptions: { header: null } },
  Map: {screen: ShowMapContainer, navigationOptions: { header: null } }
});

Hope it helps.

Why can I ping a server but not connect via SSH?

On the server, try:

netstat -an 

and look to see if tcp port 22 is opened (use findstr in Windows or grep in Unix).

How do I set a JLabel's background color?

For the Background, make sure you have imported java.awt.Color into your package.

In your main method, i.e. public static void main(String[] args), call the already imported method:

JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);

NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.

How to convert an XML file to nice pandas dataframe?

You can also convert by creating a dictionary of elements and then directly converting to a data frame:

import xml.etree.ElementTree as ET
import pandas as pd

# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags>   <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" />   <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" />   <row Id="3" TagName="elicitation" Count="10" />   <row Id="5" TagName="open-source" Count="16" /> </tags>

root = ET.parse('test.xml').getroot()

tags = {"tags":[]}
for elem in root:
    tag = {}
    tag["Id"] = elem.attrib['Id']
    tag["TagName"] = elem.attrib['TagName']
    tag["Count"] = elem.attrib['Count']
    tags["tags"]. append(tag)

df_users = pd.DataFrame(tags["tags"])
df_users.head()

Is there a way to get rid of accents and convert a whole string to regular letters?

@David Conrad solution is the fastest I tried using the Normalizer, but it does have a bug. It basically strips characters which are not accents, for example Chinese characters and other letters like æ, are all stripped. The characters that we want to strip are non spacing marks, characters which don't take up extra width in the final string. These zero width characters basically end up combined in some other character. If you can see them isolated as a character, for example like this `, my guess is that it's combined with the space character.

public static String flattenToAscii(String string) {
    char[] out = new char[string.length()];
    String norm = Normalizer.normalize(string, Normalizer.Form.NFD);

    int j = 0;
    for (int i = 0, n = norm.length(); i < n; ++i) {
        char c = norm.charAt(i);
        int type = Character.getType(c);

        //Log.d(TAG,""+c);
        //by Ricardo, modified the character check for accents, ref: http://stackoverflow.com/a/5697575/689223
        if (type != Character.NON_SPACING_MARK){
            out[j] = c;
            j++;
        }
    }
    //Log.d(TAG,"normalized string:"+norm+"/"+new String(out));
    return new String(out);
}

What is a vertical tab?

Microsoft Word uses VT as a line separator in order to distinguish it from the normal new line function, which is used as a paragraph separator.

Oracle - how to remove white spaces?

Run below query replacing TABLE_NAME & COLUMN_NAME with your actual table & column names:

UPDATE TABLE_NAME SET COLUMN_NAME=TRIM(' ' from COLUMN_NAME);

SQL Update Multiple Fields FROM via a SELECT Statement

I just had to solve a similar problem where I added a Sequence number (so that items as grouped by a parent ID, have a Sequence that I can order by (and presumably the user can change the sequence number to change the ordering).

In my case, it's insurance for a Patient, and the user gets to set the order they are assigned, so just going by the primary key isn't useful for long-term, but is useful for setting a default.

The problem with all the other solutions is that certain aggregate functions aren't allowed outside of a SELECT

This SELECT gets you the new Sequence number:

select PatientID,
       PatientInsuranceID, 
       Sequence, 
       Row_Number() over(partition by PatientID order by PatientInsuranceID) as RowNum
from PatientInsurance
order by PatientID, PatientInsuranceID

This update command, would be simple, but isn't allowed:

update PatientInsurance
set Sequence = Row_Number() over(partition by PatientID order by PatientInsuranceID)

The solution that worked (I just did it), and is similar to eKek0's solution:

UPDATE PatientInsurance
SET  PatientInsurance.Sequence = q.RowNum
FROM (select PatientInsuranceID, 
             Row_Number() over(partition by PatientID order by PatientInsuranceID) as RowNum
      from PatientInsurance
     ) as q 
WHERE PatientInsurance.PatientInsuranceID=q.PatientInsuranceID 

this lets me select the ID I need to match things up to, and the value I need to set for that ID. Other solutions would have been fine IF I wasn't using Row_Number() which won't work outside of a SELECT.

Given that this is a 1 time operation, it's coding is still simple, and run-speed is fast enough for 4000+ rows

Writing to an Excel spreadsheet

  • xlrd/xlwt (standard): Python does not have this functionality in it's standard library, but I think of xlrd/xlwt as the "standard" way to read and write excel files. It is fairly easy to make a workbook, add sheets, write data/formulas, and format cells. If you need all of these things, you may have the most success with this library. I think you could choose openpyxl instead and it would be quite similar, but I have not used it.

    To format cells with xlwt, define a XFStyle and include the style when you write to a sheet. Here is an example with many number formats. See example code below.

  • Tablib (powerful, intuitive): Tablib is a more powerful yet intuitive library for working with tabular data. It can write excel workbooks with multiple sheets as well as other formats, such as csv, json, and yaml. If you don't need formatted cells (like background color), you will do yourself a favor to use this library, which will get you farther in the long run.

  • csv (easy): Files on your computer are either text or binary. Text files are just characters, including special ones like newlines and tabs, and can be easily opened anywhere (e.g. notepad, your web browser, or Office products). A csv file is a text file that is formatted in a certain way: each line is a list of values, separated by commas. Python programs can easily read and write text, so a csv file is the easiest and fastest way to export data from your python program into excel (or another python program).

    Excel files are binary and require special libraries that know the file format, which is why you need an additional library for python, or a special program like Microsoft Excel, Gnumeric, or LibreOffice, to read/write them.


import xlwt

style = xlwt.XFStyle()
style.num_format_str = '0.00E+00'

...

for i,n in enumerate(list1):
    sheet1.write(i, 0, n, fmt)

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

How to delete an instantiated object Python?

object.__del__(self) is called when the instance is about to be destroyed.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed(As quoted by ethan)

Also, From Python official doc reference:

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero

Fastest way to check a string is alphanumeric in Java

I've written the tests that compare using regular expressions (as per other answers) against not using regular expressions. Tests done on a quad core OSX10.8 machine running Java 1.6

Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2() function is marginally faster than isAlphanumeric(). One supports the case where extended Unicode numbers are allowed, and the other is for when only standard ASCII numbers are allowed.

public class QuickTest extends TestCase {

    private final int reps = 1000000;

    public void testRegexp() {
        for(int i = 0; i < reps; i++)
            ("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
    }

public void testIsAlphanumeric() {
    for(int i = 0; i < reps; i++)
        isAlphanumeric("ab4r3rgf"+i);
}

public void testIsAlphanumeric2() {
    for(int i = 0; i < reps; i++)
        isAlphanumeric2("ab4r3rgf"+i);
}

    public boolean isAlphanumeric(String str) {
        for (int i=0; i<str.length(); i++) {
            char c = str.charAt(i);
            if (!Character.isLetterOrDigit(c))
                return false;
        }

        return true;
    }

    public boolean isAlphanumeric2(String str) {
        for (int i=0; i<str.length(); i++) {
            char c = str.charAt(i);
            if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
                return false;
        }
        return true;
    }

}

What is tempuri.org?

Webservices require unique namespaces so they don't confuse each others schemas and whatever with each other. A URL (domain, subdomain, subsubdomain, etc) is a clever identifier as it's "guaranteed" to be unique, and in most circumstances you've already got one.

Reading DataSet

TL;DR: - grab the datatable from the dataset and read from the rows property.

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            DataColumn col = new DataColumn("Id", typeof(int));
            dt.Columns.Add(col);
            dt.Rows.Add(new object[] { 1 });
            ds.Tables.Add(dt);

            var row = ds.Tables[0].Rows[0];
            //access the ID column.  
            var id = (int) row.ItemArray[0];

A DataSet is a copy of data accessed from a database, but doesn't even require a database to use at all. It is preferred, though.

Note that if you are creating a new application, consider using an ORM, such as the Entity Framework or NHibernate, since DataSets are no longer preferred; however, they are still supported and as far as I can tell, are not going away any time soon.

If you are reading from standard dataset, then @KMC's answer is what you're looking for. The proper way to do this, though, is to create a Strongly-Typed DataSet and use that so you can take advantage of Intellisense. Assuming you are not using the Entity Framework, proceed.

If you don't already have a dedicated space for your data access layer, such as a project or an App_Data folder, I suggest you create one now. Otherwise, proceed as follows under your data project folder: Add > Add New Item > DataSet. The file created will have an .xsd extension.

You'll then need to create a DataTable. Create a DataTable (click on the file, then right click on the design window - the file has an .xsd extension - and click Add > DataTable). Create some columns (Right click on the datatable you just created > Add > Column). Finally, you'll need a table adapter to access the data. You'll need to setup a connection to your database to access data referenced in the dataset.

After you are done, after successfully referencing the DataSet in your project (using statement), you can access the DataSet with intellisense. This makes it so much easier than untyped datasets.

When possible, use Strongly-Typed DataSets instead of untyped ones. Although it is more work to create, it ends up saving you lots of time later with intellisense. You could do something like:

MyStronglyTypedDataSet trainDataSet = new MyStronglyTypedDataSet();
DataAdapterForThisDataSet dataAdapter = new DataAdapterForThisDataSet();
//code to fill the dataset 
//omitted - you'll have to either use the wizard to create data fill/retrieval
//methods or you'll use your own custom classes to fill the dataset.
if(trainDataSet.NextTrainDepartureTime > CurrentTime){
   trainDataSet.QueueNextTrain = true; //assumes QueueNextTrain is in your Strongly-Typed dataset
}
else
    //do some other work

The above example assumes that your Strongly-Typed DataSet has a column of type DateTime named NextTrainDepartureTime. Hope that helps!

Java Swing - how to show a panel on top of another panel?

There's another layout manager that may be of interest here: Overlay Layout Here's a simple tutorial: OverlayLayout: for layout management of components that lie on top of one another. Overlay Layout allows you to position panels on top of one another, and set a layout inside each panel. You are also able to set size and position of each panel separately.

(The reason I'm answering this question from years ago is because I have stumbled upon the same problem, and I have seen very few mentions of the Overlay Layout on StackOverflow, while it seems to be pretty well documented. Hopefully this may help someone else who keeps searching for it.)

How do I conditionally apply CSS styles in AngularJS?

There is one more option that I recently discovered that some people may find useful because it allows you to change a CSS rule within a style element - thus avoiding the need for repeated use of an angular directive such as ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.

This option makes use of a service with service variables which are set by a controller and watched by an attribute-directive I call "custom-style". This strategy could be used in many different ways, and I attempted to provide some general guidance with this fiddle.

var app = angular.module('myApp', ['ui.bootstrap']);
app.service('MainService', function(){
    var vm = this;
});
app.controller('MainCtrl', function(MainService){
    var vm = this;
    vm.ms = MainService;
});
app.directive('customStyle', function(MainService){
    return {
        restrict : 'A',
        link : function(scope, element, attr){
            var style = angular.element('<style></style>');
            element.append(style);
            scope.$watch(function(){ return MainService.theme; },
                function(){
                    var css = '';
                    angular.forEach(MainService.theme, function(selector, key){
                        angular.forEach(MainService.theme[key], function(val, k){
                            css += key + ' { '+k+' : '+val+'} ';
                        });                        
                    });
                    style.html(css);
                }, true);
        }
    };
});

Read pdf files with php

There is a php library (pdfparser) that does exactly what you want.

project website

http://www.pdfparser.org/

github

https://github.com/smalot/pdfparser

Demo page/api

http://www.pdfparser.org/demo

After including pdfparser in your project you can get all text from mypdf.pdf like so:

<?php
$parser = new \installpath\PdfParser\Parser();
$pdf    = $parser->parseFile('mypdf.pdf');  
$text = $pdf->getText();
echo $text;//all text from mypdf.pdf

?>

Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).

How can I rename a project folder from within Visual Studio?

In andersjanmyr's answer it's easier to rename the project first.

  1. Rename the project.
  2. Close the solution (save it).
  3. Rename the folders outside Visual Studio.
  4. Open the solution, ignoring the warnings.
  5. Go through all unavailable projects and set the property 'File Path' to the new location of your project file, i.e. someproject.csproj.
  6. Reload the project.

Also, after those steps are carried out, you might want to rename other references to your old project name.

In project properties, update the Assembly Name and Default Namespace.

This will update the following in the project file...

<RootNamespace>SomeProjectName</RootNamespace>
<AssemblyName>SomeProjectName</AssemblyName>

...and will get rid of the error "Namespace does not correspond to file location, should be: 'SomeProjectName'"

Rename your root namespace (if you have ReSharper right click the Namespace and go Refactor -> Rename).

Change all occurrences of your old project name in AssemblyInfo.cs.

Generate Java classes from .XSD files...?

JAXB does EXACTLY what you want. It's built into the JRE/JDK starting at 1.6

What does int argc, char *argv[] mean?

The parameters to main represent the command line parameters provided to the program when it was started. The argc parameter represents the number of command line arguments, and char *argv[] is an array of strings (character pointers) representing the individual arguments provided on the command line.

How to use the CSV MIME-type?

This code can be used to export any file, including csv

// application/octet-stream tells the browser not to try to interpret the file
header('Content-type: application/octet-stream');
header('Content-Length: ' . filesize($data));
header('Content-Disposition: attachment; filename="export.csv"');

Apply function to all elements of collection through LINQ

You could also consider going parallel, especially if you don't care about the sequence and more about getting something done for each item:

SomeIEnumerable<T>.AsParallel().ForAll( Action<T> / Delegate / Lambda )

For example:

var numbers = new[] { 1, 2, 3, 4, 5 };
numbers.AsParallel().ForAll( Console.WriteLine );

HTH.

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

I had a similar problem when posting to the WebAPI endpoint. By turning the CustomErrors=Off, i was able to see the actual error which is one of the dlls was missing.

Check which element has been clicked with jQuery

So you are doing this a bit backwards. Typically you'd do something like this:

?<div class='article'>
  Article 1
</div>
<div class='article'>
  Article 2
</div>
<div class='article'>
  Article 3
</div>?

And then in your jQuery:

$('.article').click(function(){
    article = $(this).text(); //$(this) is what you clicked!
    });?

When I see things like #search-item .search-article, #search-item .search-article, and #search-item .search-article I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.

How to show image using ImageView in Android

In res folder select the XML file in which you want to view your images,

<ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:src="@drawable/imagep1" />

Docker: Multiple Dockerfiles in project

In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.

What is the difference between README and README.md in GitHub projects?

README.md or .mkdn or .markdown denotes that the file is markdown formatted. Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text

Is there anything like .NET's NotImplementedException in Java?

As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:

public class NotYetImplementedException extends RuntimeException
{
    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException()
    {
    }

    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException(String message)
    {
        super(message);
    }
}

This approach has the following benefits:

  1. When readers see NotYetImplementedException, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.
  2. With the deprecation warning at each call site, your IDE and static code analysis tool can remind you where you still have to implement something. (This use of deprecation may feel wrong to some, but in fact deprecation is not limited to announcing removal.)
  3. The constructors are deprecated, not the class. This way, you only get a deprecation warning inside the method that needs implementing, not at the import line (JDK 9 fixed this, though).

error LNK2005, already defined?

If you want both to reference the same variable, one of them should have int k;, and the other should have extern int k;

For this situation, you typically put the definition (int k;) in one .cpp file, and put the declaration (extern int k;) in a header, to be included wherever you need access to that variable.

If you want each k to be a separate variable that just happen to have the same name, you can either mark them as static, like: static int k; (in all files, or at least all but one file). Alternatively, you can us an anonymous namespace:

namespace { 
   int k;
};

Again, in all but at most one of the files.

In C, the compiler generally isn't quite so picky about this. Specifically, C has a concept of a "tentative definition", so if you have something like int k; twice (in either the same or separate source files) each will be treated as a tentative definition, and there won't be a conflict between them. This can be a bit confusing, however, because you still can't have two definitions that both include initializers--a definition with an initializer is always a full definition, not a tentative definition. In other words, int k = 1; appearing twice would be an error, but int k; in one place and int k = 1; in another would not. In this case, the int k; would be treated as a tentative definition and the int k = 1; as a definition (and both refer to the same variable).

java.time.format.DateTimeParseException: Text could not be parsed at index 21

If your input always has a time zone of "zulu" ("Z" = UTC), then you can use DateTimeFormatter.ISO_INSTANT (implicitly):

final Instant parsed = Instant.parse(dateTime);

If time zone varies and has the form of "+01:00" or "+01:00:00" (when not "Z"), then you can use DateTimeFormatter.ISO_OFFSET_DATE_TIME:

DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);

If neither is the case, you can construct a DateTimeFormatter in the same manner as DateTimeFormatter.ISO_OFFSET_DATE_TIME is constructed.


Your current pattern has several problems:

  • not using strict mode (ResolverStyle.STRICT);
  • using yyyy instead of uuuu (yyyy will not work in strict mode);
  • using 12-hour hh instead of 24-hour HH;
  • using only one digit S for fractional seconds, but input has three.

Using JAXB to unmarshal/marshal a List<String>

User1's example worked well for me. But, as a warning, it won't work with anything other than simple String/Integer types, unless you add an @XmlSeeAlso annotation:

@XmlRootElement(name = "List")
@XmlSeeAlso(MovieTicket.class)
public class MovieTicketList {
    protected List<MovieTicket> list;

This works OK, although it prevents me from using a single generic list class across my entire application. It might also explain why this seemingly obvious class doesn't exist in the JAXB package.

Namespace not recognized (even though it is there)

If your class does not compile, even if it is in the project check these:

  1. whether class name is exactly the same
  2. whether name space is exactly the same
  3. whether class properties show build action = compile

Click in OK button inside an Alert (Selenium IDE)

The question isn't clear - is this for an alert on page load? You shouldn't see any alert dialogues when using Selenium, as it replaces alert() with its own version which just captures the message given for verification.

Selenium doesn't support alert() on page load, as it needs to patch the function in the window under test with its own version.

If you can't get rid of onload alerts from the application under test, you should look into using GUI automation to click the popups which are generated, e.g. AutoIT if you're on Windows.

Convert array of indices to 1-hot encoded numpy array

Such type of encoding are usually part of numpy array. If you are using a numpy array like this :

a = np.array([1,0,3])

then there is very simple way to convert that to 1-hot encoding

out = (np.arange(4) == a[:,None]).astype(np.float32)

That's it.

How to get a list of installed Jenkins plugins with name and version pair

If you are a Jenkins administrator you can use the Jenkins system information page:

http://<jenkinsurl>/systemInfo

Change date format in a Java string

You could try Java 8 new date, more information can be found on the Oracle documentation.

Or you can try the old one

public static Date getDateFromString(String format, String dateStr) {

    DateFormat formatter = new SimpleDateFormat(format);
    Date date = null;
    try {
        date = (Date) formatter.parse(dateStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return date;
}

public static String getDate(Date date, String dateFormat) {
    DateFormat formatter = new SimpleDateFormat(dateFormat);
    return formatter.format(date);
}

How to JSON decode array elements in JavaScript?

Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -

echo json_encode($iniData);

In Javascript, use the following :

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: "ajaxCalls.php",
            data: "dataType=ini",
            success: function(msg)
            {
                var x = eval('(' + msg + ')');
                $('#allowed').html(x.allowed);              // these are the fields which you can now easily access..
                $('#completed').html(x.completed);
                $('#running').html(x.running);
                $('#expired').html(x.expired);
                $('#balance').html(x.balance);
            }
        });
    });
</script>

Ways to circumvent the same-origin policy

Well, I used curl in PHP to circumvent this. I have a webservice running in port 82.

<?php

$curl = curl_init();
$timeout = 30;
$ret = "";
$url="http://localhost:82/put_val?val=".$_GET["val"];
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl, CURLOPT_MAXREDIRS, 20);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
$text = curl_exec($curl);
echo $text;

?>

Here is the javascript that makes the call to the PHP file

function getdata(obj1, obj2) {

    var xmlhttp;

    if (window.XMLHttpRequest)
            xmlhttp=new XMLHttpRequest();
    else
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
                document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","phpURLFile.php?eqp="+obj1+"&val="+obj2,true);
    xmlhttp.send();
}

My HTML runs on WAMP in port 80. So there we go, same origin policy has been circumvented :-)

detect key press in python?

So I made this ..kind of game.. based on this post (using msvcr library and Python 3.7).

The following is the "main function" of the game, that is detecting the keys pressed:

# Requiered libraries - - - -
import msvcrt
# - - - - - - - - - - - - - -


def _secret_key(self):
    # Get the key pressed by the user and check if he/she wins.

    bk = chr(10) + "-"*25 + chr(10)

    while True:

        print(bk + "Press any key(s)" + bk)
        #asks the user to type any key(s)

        kp = str(msvcrt.getch()).replace("b'", "").replace("'", "")
        # Store key's value.

        if r'\xe0' in kp:
            kp += str(msvcrt.getch()).replace("b'", "").replace("'", "")
            # Refactor the variable in case of multi press.

        if kp == r'\xe0\x8a':
            # If user pressed the secret key, the game ends.
            # \x8a is CTRL+F12, that's the secret key.

            print(bk + "CONGRATULATIONS YOU PRESSED THE SECRET KEYS!\a" + bk)
            print("Press any key to exit the game")
            msvcrt.getch()
            break
        else:
            print("    You pressed:'", kp + "', that's not the secret key(s)\n")
            if self.select_continue() == "n":
                if self.secondary_options():
                    self._main_menu()
                break

If you want the full source code of the porgram you can see it or download it from here:

The Secret Key Game (GitHub)

(note: the secret keypress is: Ctrl+F12)

I hope you can serve as an example and help for those who come to consult this information.

ImportError: DLL load failed: The specified module could not be found

Quick note: Check if you have other Python versions, if you have removed them, make sure you did that right. If you have Miniconda on your system then Python will not be removed easily.

What worked for me: removed other Python versions and the Miniconda, reinstalled Python and the matplotlib library and everything worked great.

How to handle onchange event on input type=file in jQuery?

Or could be:

$('input[type=file]').change(function () {
    alert("hola");
});

To be specific: $('input[type=file]#fileUpload1').change(...

Should I set max pool size in database connection string? What happens if I don't?

We can define maximum pool size in following way:

                <pool> 
               <min-pool-size>5</min-pool-size>
                <max-pool-size>200</max-pool-size>
                <prefill>true</prefill>
                <use-strict-min>true</use-strict-min>
                <flush-strategy>IdleConnections</flush-strategy>
                </pool>

Ellipsis for overflow text in dropdown boxes

quirksmode has a good description of the 'text-overflow' property, but you may need to apply some additional properties like 'white-space: nowrap'

Whilst I'm not 100% how this will behave in a select object, it could be worth trying this first:

http://www.quirksmode.org/css/textoverflow.html

Adding <script> to WordPress in <head> element

For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here.

Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.

Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.

Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.

Something along the following in a plugin file is what you are looking for:

<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI: 
Plugin URI: 
*/

function $yourJS() {
    wp_enqueue_script(
        'custom_script',
        plugins_url( '/js/your-script.js', __FILE__ ),
        array( 'jquery' )
    );
}
 add_action( 'wp_enqueue_scripts',  '$yourJS' );
 add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );

 function prefix_add_my_stylesheet() {
    wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
    wp_enqueue_style( 'prefix-style' );
  }

?>

Structure your folders as follows:

Plugin Folder
  |_ css folder
  |_ js folder
  |_ plugin.php ...contains the above code - modified of course ;D

Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.

Getting list of items inside div using Selenium Webdriver

I'm not sure if your findElements statement gets you all the divs. I would try the following:

List<WebElement> elementsRoot = driver.findElements(By.xpath("//div[@class=\"facetContainerDiv\"]/div));

for(int i = 0; i < elementsRoot.size(); ++i) {
     WebElement checkbox = elementsRoot.get(i).findElement(By.xpath("./label/input"));
     checkbox.click();
     blah blah blah
}

The idea here is that you get the root element then use another a 'sub' xpath or any selector you like to find the node element. Of course the xpath or selector may need to be adjusted to properly find the element you want.

Update Jenkins from a war file

Mine is installed under /usr/share/jenkins I thought it was installed via apt-get so might want to check there as well.

Ubuntu 12.04.1

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

This worked for me. :)

sudo keytool -importcert -file filename.cer -alias randomaliasname -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit 

How to create JNDI context in Spring Boot with Embedded Tomcat Container

I recently had the requirement to use JNDI with an embedded Tomcat in Spring Boot.
Actual answers give some interesting hints to solve my task but it was not enough as probably not updated for Spring Boot 2.

Here is my contribution tested with Spring Boot 2.0.3.RELEASE.

Specifying a datasource available in the classpath at runtime

You have multiple choices :

  • using the DBCP 2 datasource (you don't want to use DBCP 1 that is outdated and less efficient).
  • using the Tomcat JDBC datasource.
  • using any other datasource : for example HikariCP.

If you don't specify anyone of them, with the default configuration the instantiation of the datasource will throw an exception :

Caused by: javax.naming.NamingException: Could not create resource factory instance
        at org.apache.naming.factory.ResourceFactory.getDefaultFactory(ResourceFactory.java:50)
        at org.apache.naming.factory.FactoryBase.getObjectInstance(FactoryBase.java:90)
        at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:839)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:173)
        at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163)
        at javax.naming.InitialContext.lookup(InitialContext.java:417)
        at org.springframework.jndi.JndiTemplate.lambda$lookup$0(JndiTemplate.java:156)
        at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:91)
        at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:156)
        at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
        at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:96)
        at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:114)
        at org.springframework.jndi.JndiObjectTargetSource.getTarget(JndiObjectTargetSource.java:140)
        ... 39 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:264)
        at org.apache.naming.factory.ResourceFactory.getDefaultFactory(ResourceFactory.java:47)
        ... 58 common frames omitted

  • To use Apache JDBC datasource, you don't need to add any dependency but you have to change the default factory class to org.apache.tomcat.jdbc.pool.DataSourceFactory.
    You can do it in the resource declaration : resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory"); I will explain below where add this line.

  • To use DBCP 2 datasource a dependency is required:

    <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-dbcp</artifactId> <version>8.5.4</version> </dependency>

Of course, adapt the artifact version according to your Spring Boot Tomcat embedded version.

  • To use HikariCP, add the required dependency if not already present in your configuration (it may be if you rely on persistence starters of Spring Boot) such as :

    <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.1.0</version> </dependency>

and specify the factory that goes with in the resource declaration:

resource.setProperty("factory", "com.zaxxer.hikari.HikariJNDIFactory");

Datasource configuration/declaration

You have to customize the bean that creates the TomcatServletWebServerFactory instance.
Two things to do :

  • enabling the JNDI naming which is disabled by default

  • creating and add the JNDI resource(s) in the server context

For example with PostgreSQL and a DBCP 2 datasource, do that :

@Bean
public TomcatServletWebServerFactory tomcatFactory() {
    return new TomcatServletWebServerFactory() {
        @Override
        protected TomcatWebServer getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
            tomcat.enableNaming(); 
            return super.getTomcatWebServer(tomcat);
        }

        @Override 
        protected void postProcessContext(Context context) {

            // context
            ContextResource resource = new ContextResource();
            resource.setName("jdbc/myJndiResource");
            resource.setType(DataSource.class.getName());
            resource.setProperty("driverClassName", "org.postgresql.Driver");

            resource.setProperty("url", "jdbc:postgresql://hostname:port/dbname");
            resource.setProperty("username", "username");
            resource.setProperty("password", "password");
            context.getNamingResources()
                   .addResource(resource);          
        }
    };
}

Here the variants for Tomcat JDBC and HikariCP datasource.

In postProcessContext() set the factory property as explained early for Tomcat JDBC ds :

    @Override 
    protected void postProcessContext(Context context) {
        ContextResource resource = new ContextResource();       
        //...
        resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
        //...
        context.getNamingResources()
               .addResource(resource);          
    }
};

and for HikariCP :

    @Override 
    protected void postProcessContext(Context context) {
        ContextResource resource = new ContextResource();       
        //...
        resource.setProperty("factory", "com.zaxxer.hikari.HikariDataSource");
        //...
        context.getNamingResources()
               .addResource(resource);          
    }
};

Using/Injecting the datasource

You should now be able to lookup the JNDI ressource anywhere by using a standard InitialContext instance :

InitialContext initialContext = new InitialContext();
DataSource datasource = (DataSource) initialContext.lookup("java:comp/env/jdbc/myJndiResource");

You can also use JndiObjectFactoryBean of Spring to lookup up the resource :

JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.afterPropertiesSet();
DataSource object = (DataSource) bean.getObject();

To take advantage of the DI container you can also make the DataSource a Spring bean :

@Bean(destroyMethod = "")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myJndiResource");
    bean.afterPropertiesSet();
    return (DataSource) bean.getObject();
}

And so you can now inject the DataSource in any Spring beans such as :

@Autowired
private DataSource jndiDataSource;

Note that many examples on the internet seem to disable the lookup of the JNDI resource on startup :

bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet(); 

But I think that it is helpless as it invokes just after afterPropertiesSet() that does the lookup !

Python conversion from binary string to hexadecimal

Using no messy concatenations and padding :

'{:0{width}x}'.format(int(temp,2)), width=4)

Will give a hex representation with padding preserved

How to read values from properties file?

You need to put a PropertyPlaceholderConfigurer bean in your application context and set its location property.

See details here : http://www.zparacha.com/how-to-read-properties-file-in-spring/

You might have to modify your property file a bit for this thing to work.

Hope it helps.

How do I compare two DateTime objects in PHP 5.2.8?

From the official documentation:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2); // false
var_dump($date1 < $date2); // true
var_dump($date1 > $date2); // false

For PHP versions before 5.2.2 (actually for any version), you can use diff.

$datetime1 = new DateTime('2009-10-11'); // 11 October 2013
$datetime2 = new DateTime('2009-10-13'); // 13 October 2013

$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); // +2 days

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

Linux shell script for database backup

I have prepared a Shell Script to create a Backup of MYSQL database. You can use it so that we have backup of our database(s).

    #!/bin/bash
    export PATH=/bin:/usr/bin:/usr/local/bin
    TODAY=`date +"%d%b%Y_%I:%M:%S%p"`

    ################################################################
    ################## Update below values  ########################
    DB_BACKUP_PATH='/backup/dbbackup'
    MYSQL_HOST='localhost'
    MYSQL_PORT='3306'
    MYSQL_USER='auriga'
    MYSQL_PASSWORD='auriga@123'
    DATABASE_NAME=( Project_O2 o2)
    BACKUP_RETAIN_DAYS=30   ## Number of days to keep local backup copy; Enable script code in end of th script

    #################################################################
    { mkdir -p ${DB_BACKUP_PATH}/${TODAY}
        echo "
                                ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
    } || {
        echo "Can not make Directry"
        echo "Possibly Path is wrong"
    }
    { if ! mysql -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e 'exit'; then
        echo 'Failed! You may have Incorrect PASSWORD/USER ' >> ${DB_BACKUP_PATH}/Backup-Report.txt
        exit 1
    fi

        for DB in "${DATABASE_NAME[@]}"; do
            if ! mysql -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e "use "${DB}; then
                echo "Failed! Database ${DB} Not Found on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt

            else
                # echo "Backup started for database - ${DB}"            
                # mysqldump -h localhost -P 3306 -u auriga -pauriga@123 Project_O2      # use gzip..

                mysqldump -h ${MYSQL_HOST} -P ${MYSQL_PORT} -u ${MYSQL_USER} -p${MYSQL_PASSWORD} \
                          --databases ${DB} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DB}-${TODAY}.sql.gz

                if [ $? -eq 0 ]; then
                    touch ${DB_BACKUP_PATH}/Backup-Report.txt
                    echo "successfully backed-up of ${DB} on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
                    # echo "Database backup successfully completed"

                else
                    touch ${DB_BACKUP_PATH}/Backup-Report.txt
                    echo "Failed to backup of ${DB} on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
                    # echo "Error found during backup"
                    exit 1
                fi
            fi
        done
    } || {
        echo "Failed during backup"
        echo "Failed to backup on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
        # ./myshellsc.sh 2> ${DB_BACKUP_PATH}/Backup-Report.txt
    }

    ##### Remove backups older than {BACKUP_RETAIN_DAYS} days  #####

    # DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`

    # if [ ! -z ${DB_BACKUP_PATH} ]; then
    #       cd ${DB_BACKUP_PATH}
    #       if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
    #             rm -rf ${DBDELDATE}
    #       fi
    # fi

    ### End of script ####

In the script we just need to give our Username, Password, Name of Database(or Databases if more than one) also Port number if Different.

To Run the script use Command as:

sudo ./script.sc

I also Suggest that if You want to see the Result in a file Like: Failure Occurs or Successful in backing-up, then Use the Command as Below:

sudo ./myshellsc.sh 2>> Backup-Report.log

Thank You.

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

I can generate this error by setting system property trustStore to a missing jks file. For example

    System.setProperty("javax.net.ssl.keyStore", "C:/keystoreFile.jks");
    System.setProperty("javax.net.ssl.keyStorePassword", "mypassword");
    System.setProperty("javax.net.ssl.trustStore", "C:/missing-keystore.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "mypassword");

This code does not generate a FileNotFound exception for some reason, but exactly the InvalidAlgorithmParameter exception listed above.

Kind of a dumb answer, but I can reproduce.

How to include CSS file in Symfony 2 and Twig?

In case you are using Silex add the Symfony Asset as a dependency:

composer require symfony/asset

Then you may register Asset Service Provider:

$app->register(new Silex\Provider\AssetServiceProvider(), array(
    'assets.version' => 'v1',
    'assets.version_format' => '%s?version=%s',
    'assets.named_packages' => array(
        'css' => array(
            'version' => 'css2',
            'base_path' => __DIR__.'/../public_html/resources/css'
        ),
        'images' => array(
            'base_urls' => array(
                'https://img.example.com'
            )
        ),
    ),
));

Then in your Twig template file in head section:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    {% block head %}
    <link rel="stylesheet" href="{{ asset('style.css') }}" />
    {% endblock %}
</head>
<body>

</body>
</html>

Implementing a simple file download servlet

Assuming you have access to servlet as below

http://localhost:8080/myapp/download?id=7

I need to create a servlet and register it to web.xml

web.xml

<servlet>
     <servlet-name>DownloadServlet</servlet-name>
     <servlet-class>com.myapp.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name>DownloadServlet</servlet-name>
     <url-pattern>/download</url-pattern>
</servlet-mapping>

DownloadServlet.java

public class DownloadServlet extends HttpServlet {


    protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         String id = request.getParameter("id");

         String fileName = "";
         String fileType = "";
         // Find this file id in database to get file name, and file type

         // You must tell the browser the file type you are going to send
         // for example application/pdf, text/plain, text/html, image/jpg
         response.setContentType(fileType);

         // Make sure to show the download dialog
         response.setHeader("Content-disposition","attachment; filename=yourcustomfilename.pdf");

         // Assume file name is retrieved from database
         // For example D:\\file\\test.pdf

         File my_file = new File(fileName);

         // This should send the file to browser
         OutputStream out = response.getOutputStream();
         FileInputStream in = new FileInputStream(my_file);
         byte[] buffer = new byte[4096];
         int length;
         while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
         }
         in.close();
         out.flush();
    }
}

How can I change Eclipse theme?

Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins folder.

When you have done that go to

Window -> Preferences -> General -> Appearance

And change the theme from GTK (or what ever it is currently) to Dark Juno (or Dark).

That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.

Eclipse Color Themes

This adds a "Color Theme" menu item under

Window -> Preferences -> Appearance

Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark

Using regular expression in css?

Try my generic CSS regular expression

(([a-z]{5,6}.*?\))|([\d.+-]?)(?![a-z\s#.()%])(\d?\.?\d?)?[a-z\d%]+)|(url\([/"'][a-z:/.]*['")]\))|(rgb|hsl)a?\(\d+%?,?\s?\d+%?,?\s?\d+%?(,\s?\d+\.?\d?)?\)|(#(\w|[\d]){3,8})|([\w]{3,8}(?=.*-))

Demo https://regexr.com/4a22i

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

How to get document height and width without using jquery

Get document size without jQuery

document.documentElement.clientWidth
document.documentElement.clientHeight

And use this if you need Screen size

screen.width
screen.height

How to test web service using command line curl

From the documentation on http://curl.haxx.se/docs/httpscripting.html :

HTTP Authentication

curl --user name:password http://www.example.com 

Put a file to a HTTP server with curl:

curl --upload-file uploadfile http://www.example.com/receive.cgi

Send post data with curl:

curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi

Using logging in multiple modules

You could also come up with something like this!

def get_logger(name=None):
    default = "__app__"
    formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')
    log_map = {"__app__": "app.log", "__basic_log__": "file1.log", "__advance_log__": "file2.log"}
    if name:
        logger = logging.getLogger(name)
    else:
        logger = logging.getLogger(default)
    fh = logging.FileHandler(log_map[name])
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.setLevel(logging.DEBUG)
    return logger

Now you could use multiple loggers in same module and across whole project if the above is defined in a separate module and imported in other modules were logging is required.

a=get_logger("__app___")
b=get_logger("__basic_log__")
a.info("Starting logging!")
b.debug("Debug Mode")

Unable to ping vmware guest from another vmware guest

I know it is an old question, but I had a similar trouble recently. On VMware Workstation 12.+ go to Edit -> Virtual Network Editor... Select a network used by the problematic VM and make sure that "Connect a host virtual adapter to this network" checkbox is set for this network. In my case, it was not. After it was set, the host was able to ping the guest and guests were able to talk to each other.

enter image description here

PyCharm error: 'No Module' when trying to import own module (python script)

The solution for this problem without having to Mark Directory as Source Root is to Edit Run Configurations and in Execution select the option "Redirect input from" and choose script you want to run. This works because it is then treated as if the script was run interactively in this directory. However Python will still mark the module name with an error "no module named x":

Redirect input from:

When the interpreter executes the import statement, it searches for x.py in a list of directories assembled from the following sources:

  1. The directory from which the input script was run or the current directory if the interpreter is being run interactively
  2. The list of directories contained in the PYTHONPATH environment variable, if it is set.
  3. An installation-dependent list of directories configured at the time Python is installed, in my case usr/lib/python3.6 on Ubuntu.

How do you iterate through every file/directory recursively in standard C++?

You don't. The C++ standard has no concept of directories. It is up to the implementation to turn a string into a file handle. The contents of that string and what it maps to is OS dependent. Keep in mind that C++ can be used to write that OS, so it gets used at a level where asking how to iterate through a directory is not yet defined (because you are writing the directory management code).

Look at your OS API documentation for how to do this. If you need to be portable, you will have to have a bunch of #ifdefs for various OSes.

Android Get Current timestamp?

1320917972 is Unix timestamp using number of seconds since 00:00:00 UTC on January 1, 1970. You can use TimeUnit class for unit conversion - from System.currentTimeMillis() to seconds.

String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));

How to change Git log date formats

date -d @$(git log -n1 --format="%at") +%Y%m%d%H%M

Note that this will convert to your local timezone, in case that matters for your use case.

VBA Public Array : how to?

Declare array as global across subs in a application:

Public GlobalArray(10) as String
GlobalArray = Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')

Sub DisplayArray()
    Dim i As Integer

    For i = 0 to UBound(GlobalArray, 1)
        MsgBox GlobalArray(i)

    Next i
End Sub

Method 2: Pass an array to sub. Use ParamArray.

Sub DisplayArray(Name As String, ParamArray Arr() As Variant)
    Dim i As Integer

    For i = 0 To UBound(Arr())
        MsgBox Name & ": " & Arr(i)
    Next i
End Sub

ParamArray must be the last parameter.

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

I was going to leave this after this comment: Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

But Stack Overflow was formatting it weirdly.

If you don't have identical machines and are checking in node_modules, do a .gitignore on the native extensions. Our .gitignore looks like:

# Ignore native extensions in the node_modules folder (things changed by npm rebuild)
node_modules/**/*.node
node_modules/**/*.o
node_modules/**/*.a
node_modules/**/*.mk
node_modules/**/*.gypi
node_modules/**/*.target
node_modules/**/.deps/
node_modules/**/build/Makefile
node_modules/**/**/build/Makefile

Test this by first checking everything in, and then have another developer do the following:

rm -rf node_modules
git checkout -- node_modules
npm rebuild
git status

Ensure that no files changed.

How to get the Google Map based on Latitude on Longitude?

this is the javascript to display google map by passing your longitude and latitude.

<script>
    function initialize() {
      var myLatlng = new google.maps.LatLng(-34.397, 150.644);
      var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }

    function loadScript() {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
      document.body.appendChild(script);
    }

    window.onload = loadScript;


</script>

A hex viewer / editor plugin for Notepad++?

According to some comments on Super User it still works :) It just should be copied back to the plugins folder (if it's in the disabled folder) or downloaded from Plugins Central. I have downloaded it a few minutes ago and succeeded in using it.

Of course, be warned: this plugin COULD be unstable in some situations - that's why it was disabled.

unable to remove file that really exists - fatal: pathspec ... did not match any files

I know this is not the OP's problem, but I ran into the same error with an entirely different basis, so I just wanted to drop it here in case anyone else has the same. This is Windows-specific, and I assume does not affect Linux users.

I had a LibreOffice doc file, call it final report.odt. I later changed its case to Final Report.odt. In Windows, this doesn't even count as a rename. final report.odt, Final Report.odt, FiNaL RePoRt.oDt are all the same. In Linux, these are all distinct.

When I eventually went to git rm "Final Report.odt" and got the "pathspec did not match any files" error. Only when I use the original casing at the time the file was added -- git rm "final report.odt" -- did it work.

Lesson learned: to change the case I should have instead done:

git mv "final report.odt" temp.odt
git mv temp.odt "Final Report.odt"

Again, that wasn't the problem for the OP here; and wouldn't affect a Linux user, as his posts shows he clearly is. I'm just including it for others who may have this problem in Windows git and stumble onto this question.

Windows command to convert Unix line endings?

Here's a simple unix2dos.bat file that preserves blank lines and exclamation points:

@echo off
setlocal DisableDelayedExpansion
for /f "tokens=1,* delims=:" %%k in ('findstr /n "^" %1') do echo.%%l

The output goes to standard out, so redirect unix2dos.bat output to a file if so desired.

It avoids the pitfalls of other previously proposed for /f batch loop solutions by:
1) Working with delayed expansion off, to avoid eating up exclamation marks.
2) Using the for /f tokenizer itself to remove the line number from the findstr /n output lines.
(Using findstr /n is necessary to also get blank lines: They would be dropped if for /f read directly from the input file.)

But, as Jeb pointed out in a comment below, the above solution has one drawback the others don't: It drops colons at the beginning of lines.

So 2020-04-06 update just for fun, here's another 1-liner based on findstr.exe, that seems to work fine without the above drawbacks:

@echo off
setlocal DisableDelayedExpansion
for /f "tokens=* delims=0123456789" %%l in ('findstr /n "^" %1') do echo%%l

The additional tricks are:
3) Use digits 0-9 as delimiters, so that tokens=* skips the initial line number.
4) Use the colon, inserted by findstr /n after the line number, as the token separator after the echo command.

I'll leave it to Jeb to explain if there are corner cases where echo:something might fail :-)
All I can say is that this last version successfully restored line endings on my huge batch library, so exceptions, if any, must be quite rare!

How to compare strings

You need to use strcmp.

if (strcmp(string,"add") == 0){
    print("success!");
}

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

In addition to Jhonson's list, also check library's folders

In visual studio, select Tools > Options from the main menu. select Projects and Solutions > VC++ Directories. Select x64 from the Platform dropdown.

$(VCInstallDir)lib\AMD64;
$(VCInstallDir)atlmfc\lib\amd64;
$(WindowsSdkDir)lib\x64;

How can I access an internal class from an external assembly?

I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)] to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.

 Install-Package Mono.Cecil

And the code like:

static readonly string[] s_toInject = {
  // alternatively "MyAssembly, PublicKey=0024000004800000... etc."
  "MyAssembly"
};

static void Main(string[] args) {
  const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";

   var parameters = new ReaderParameters();
   var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
   foreach (var toInject in s_toInject) {
     var ca = new CustomAttribute(
       asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
                      typeof(string)})));
     ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
     asm.Assembly.CustomAttributes.Add(ca);
   }
   asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
   // note if the assembly is strongly-signed you need to resign it like
   // asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
   //   StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
   // });
}

Mount current directory as a volume in Docker on Windows 10

Here is mine which is compatible for both Win10 docker-ce & Win7 docker-toolbox. At las at the time I'm writing this :).

You can notice I prefer use /host_mnt/c instead of c:/ because I sometimes encountered trouble on docker-ce Win 10 with c:/

$WIN_PATH=Convert-Path .

#Convert for docker mount to be OK on Windows10 and Windows 7 Powershell
#Exact conversion is : remove the ":" symbol, replace all "\" by "/", remove last "/" and minor case only the disk letter
#Then for Windows10, add a /host_mnt/" at the begin of string => this way : c:\Users is translated to /host_mnt/c/Users
#For Windows7, add "//" => c:\Users is translated to //c/Users
$MOUNT_PATH=(($WIN_PATH -replace "\\","/") -replace ":","").Trim("/")

[regex]$regex='^[a-zA-Z]/'
$MOUNT_PATH=$regex.Replace($MOUNT_PATH, {$args[0].Value.ToLower()})

#Win 10
if ([Environment]::OSVersion.Version -ge (new-object 'Version' 10,0)) {
$MOUNT_PATH="/host_mnt/$MOUNT_PATH"
}
elseif ([Environment]::OSVersion.Version -ge (new-object 'Version' 6,1)) {
$MOUNT_PATH="//$MOUNT_PATH"
}

docker run -it -v "${MOUNT_PATH}:/tmp/test" busybox ls /tmp/test

Does Android keep the .apk files? if so where?

There is no standard location, however you can use the PackageManager to find out about packages and the ApplicationInfo class you can get from there has various information about a particular package: the path to its .apk, the path to its data directory, the path to a resource-only .apk (for forward locked apps), etc. Note that you may or may not have permission to read these directories depending on your relationship with the other app; however, all apps are able to read the resource .apk (which is also the real .apk for non-forward-locked app).

If you are just poking around in the shell, currently non-forward-locked apps are located in /data/app/.apk. The shell user can read a specific .apk, though it can't list the directory. In a future release the naming convention will be changed slightly, so don't count on it remaining the same, but if you get the path of the .apk from the package manager then you can use it in the shell.

How to split an integer into an array of digits?

While list(map(int, str(x))) is the Pythonic approach, you can formulate logic to derive digits without any type conversion:

from math import log10

def digitize(x):
    n = int(log10(x))
    for i in range(n, -1, -1):
        factor = 10**i
        k = x // factor
        yield k
        x -= k * factor

res = list(digitize(5243))

[5, 2, 4, 3]

One benefit of a generator is you can feed seamlessly to set, tuple, next, etc, without any additional logic.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

Try this:

$Wsdl = 'http://xxxx.xxx.xx/webservice3.asmx?WSDL';
libxml_disable_entity_loader(false); //adding this worked for me
$Client = new SoapClient($Wsdl);
//Code...

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

This is how I would start to solve this:

  1. Create a video writer:

    import cv2.cv as cv
    videowriter = cv.CreateVideoWriter( filename, fourcc, fps, frameSize)
    

    Check here for valid parameters

  2. Loop to retrieve[1] and write the frames:

    cv.WriteFrame( videowriter, frame )
    

    WriteFrame doc

[1] zenpoy already pointed in the correct direction. You just need to know that you can retrieve images from a webcam or a file :-)

Hopefully I understood the requirements correct.

How do I add one month to current date in Java?

public class StringSplit {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        date(5, 3);
        date(5, 4);
    }

    public static String date(int month, int week) {
        LocalDate futureDate = LocalDate.now().plusMonths(month).plusWeeks(week);
        String Fudate = futureDate.toString();
        String[] arr = Fudate.split("-", 3);
        String a1 = arr[0];
        String a2 = arr[1];
        String a3 = arr[2];
        String date = a3 + "/" + a2 + "/" + a1;
        System.out.println(date);
        return date;
    }
}

Output:

10/03/2020
17/03/2020

Error #2032: Stream Error

This error also occurs if you did not upload the various rsl/swc/flash-library that your swf file might expect. You may upload this RSL or missing swc or tweak your compiler options cf. http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ffe.html#WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ff5

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

answer for me was to fix a gridview control which contained a template field that had a dropdownlist which was loaded with a monstrous amount of selectable items- i replaced the DDL with a label field whose data is generated from a function. (i was originally going to allow gridview editing, but have switched to allowing edits on a separate panel displaying the DDL for that field for just that record). hope this might help someone.

How to install Python package from GitHub?

To install Python package from github, you need to clone that repository.

git clone https://github.com/jkbr/httpie.git

Then just run the setup.py file from that directory,

sudo python setup.py install

How to get the latest tag name in current branch in Git?

git log --tags --no-walk --pretty="format:%d" | sed 2q | sed 's/[()]//g' | sed s/,[^,]*$// | sed  's ......  '

IF YOU NEED MORE THAN ONE LAST TAG

(git describe --tags sometimes gives wrong hashes, i dont know why, but for me --max-count 2 doesnt work)

this is how you can get list with latest 2 tag names in reverse chronological order, works perfectly on git 1.8.4. For earlier versions of git(like 1.7.*), there is no "tag: " string in output - just delete last sed call

If you want more than 2 latest tags - change this "sed 2q" to "sed 5q" or whatever you need

Then you can easily parse every tag name to variable or so.

CSS two divs next to each other

I use a mixture of float and overflow-x:hidden. Minimal code, always works.

https://jsfiddle.net/9934sc4d/4/ - PLUS you don't need to clear your float!

.left-half{
    width:200px;
    float:left;
}
.right-half{
    overflow-x:hidden;
}

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.

What is the most efficient way to deep clone an object in JavaScript?

I think that this is the best solution if you want to generalize your object cloning algorithm.
It can be used with or without jQuery, although I recommend leaving jQuery's extend method out if you want you the cloned object to have the same "class" as the original one.

function clone(obj){
    if(typeof(obj) == 'function')//it's a simple function
        return obj;
    //of it's not an object (but could be an array...even if in javascript arrays are objects)
    if(typeof(obj) !=  'object' || obj.constructor.toString().indexOf('Array')!=-1)
        if(JSON != undefined)//if we have the JSON obj
            try{
                return JSON.parse(JSON.stringify(obj));
            }catch(err){
                return JSON.parse('"'+JSON.stringify(obj)+'"');
            }
        else
            try{
                return eval(uneval(obj));
            }catch(err){
                return eval('"'+uneval(obj)+'"');
            }
    // I used to rely on jQuery for this, but the "extend" function returns
    //an object similar to the one cloned,
    //but that was not an instance (instanceof) of the cloned class
    /*
    if(jQuery != undefined)//if we use the jQuery plugin
        return jQuery.extend(true,{},obj);
    else//we recursivley clone the object
    */
    return (function _clone(obj){
        if(obj == null || typeof(obj) != 'object')
            return obj;
        function temp () {};
        temp.prototype = obj;
        var F = new temp;
        for(var key in obj)
            F[key] = clone(obj[key]);
        return F;
    })(obj);            
}

Powershell 2 copy-item which creates a folder if doesn't exist

In PowerShell 3 and above I use the Copy-Item with New-Item.

copy-item -Path $file -Destination (new-item -type directory -force ("C:\Folder\sub\sub\" + $newSub)) -force -ea 0

I haven't tried it in ver 2.

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.

You can either remove some of the padding above and below your logo or you can add more padding above and below links.

Adding more padding should look something like this:

nav.navbar-inverse>li>a {
 padding-top: 25px;
 padding-bottom: 25px;
}

AngularJS Directive Restrict A vs E

restrict is for defining the directive type, and it can be A (Attribute), C (Class), E (Element), and M (coMment) , let's assume that the name of the directive is Doc :

Type : Usage

A = <div Doc></div>

C = <div class="Doc"></div>

E = <Doc data="book_data"></Doc>

M = <!--directive:Doc -->

Equal height rows in a flex container

If you know the items you are mapping through, you can accomplish this by doing one row at a time. I know it's a workaround, but it works.

For me I had 4 items per row, so I broke it up into two rows of 4 with each row height: 50%, get rid of flex-grow, have <RowOne /> and <RowTwo /> in a <div> with flex-column. This will do the trick

<div class='flexbox flex-column height-100-percent'>
   <RowOne class='flex height-50-percent' />
   <RowTwo class='flex height-50-percent' />
</div>

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

CURL to access a page that requires a login from a different page

After some googling I found this:

curl -c cookie.txt -d "LoginName=someuser" -d "password=somepass" https://oursite/a
curl -b cookie.txt https://oursite/b

No idea if it works, but it might lead you in the right direction.

Spring boot Security Disable security

Add following class into your code

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author vaquar khan
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/**").permitAll().anyRequest().authenticated().and().csrf().disable();
    }

}

And insie of application.properties add

security.ignored=/**
security.basic.enabled=false
management.security.enabled=false

Simplest way to do a recursive self-join?

WITH    q AS 
        (
        SELECT  *
        FROM    mytable
        WHERE   ParentID IS NULL -- this condition defines the ultimate ancestors in your chain, change it as appropriate
        UNION ALL
        SELECT  m.*
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q

By adding the ordering condition, you can preserve the tree order:

WITH    q AS 
        (
        SELECT  m.*, CAST(ROW_NUMBER() OVER (ORDER BY m.PersonId) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc
        FROM    mytable m
        WHERE   ParentID IS NULL
        UNION ALL
        SELECT  m.*,  q.bc + '.' + CAST(ROW_NUMBER() OVER (PARTITION BY m.ParentID ORDER BY m.PersonID) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q
ORDER BY
        bc

By changing the ORDER BY condition you can change the ordering of the siblings.

did you register the component correctly? For recursive components, make sure to provide the "name" option

One of the mistakes is setting components as array instead of object!

This is wrong:

<script>
import ChildComponent from './ChildComponent.vue';
export default {
  name: 'ParentComponent',
  components: [
    ChildComponent
  ],
  props: {
    ...
  }
};
</script>

This is correct:

<script>
import ChildComponent from './ChildComponent.vue';
export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  props: {
    ...
  }
};
</script>

Note: for components that use other ("child") components, you must also specify a components field!

Replace contents of factor column in R dataframe

Using dlpyr::mutate and forcats::fct_recode:

library(dplyr)
library(forcats)

iris <- iris %>%  
  mutate(Species = fct_recode(Species,
    "Virginica" = "virginica",
    "Versicolor" = "versicolor"
  )) 

iris %>% 
  count(Species)

# A tibble: 3 x 2
     Species     n
      <fctr> <int>
1     setosa    50
2 Versicolor    50
3  Virginica    50   

Adding default parameter value with type hint in Python

I recently saw this one-liner:

def foo(name: str, opts: dict=None) -> str:
    opts = {} if not opts else opts
    pass

How to convert integer to char in C?

You can try atoi() library function. Also sscanf() and sprintf() would help.

Here is a small example to show converting integer to character string:

main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
  // Now str contains the integer as characters
} 

Here for another Example

#include <stdio.h>

int main(void)
{
   char text[] = "StringX";
   int digit;
   for (digit = 0; digit < 10; ++digit)
   {
      text[6] = digit + '0';
      puts(text);
   }
   return 0;
}

/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

Java creating .jar file

Put all the 6 classes to 6 different projects. Then create jar files of all the 6 projects. In this manner you will get 6 executable jar files.

Is there a Visual Basic 6 decompiler?

I have used VB Decompiler Lite (http://www.vb-decompiler.org/) in the past, and although it does not give you the original source code, it does give you a lot of information such as method names, some variable strings, etc. With more knowledge (or with the full version) it might be possible to get even more than this.

How do I delete all the duplicate records in a MySQL table without temp tables

Thanks to jveirasv for the answer above.

If you need to remove duplicates of a specific sets of column, you can use this (if you have a timestamp in the table that vary for example)

CREATE TABLE TableA_Verify AS SELECT * FROM TableA WHERE 1 GROUP BY [COLUMN TO remove duplicates BY];

DELETE FROM TableA;

INSERT INTO TableA SELECT * FROM TAbleA_Verify;

DROP TABLE TableA_Verify;

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

Can't Autowire @Repository annotated interface in Spring Boot

I had the same issues with Repository not being found. So what I did was to move everything into 1 package. And this worked meaning that there was nothing wrong with my code. I moved the Repos & Entities into another package and added the following to SpringApplication class.

@EnableJpaRepositories("com...jpa")
@EntityScan("com...jpa")

After that, I moved the Service (interface & implementation) to another package and added the following to SpringApplication class.

@ComponentScan("com...service")

This solved my issues.

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

How to set variables in HIVE scripts

Just in case someone needs to parameterize hive query via cli.

For eg:

hive_query.sql

SELECT * FROM foo WHERE day >= '${hivevar:CURRENT_DATE}'

Now execute above sql file from cli:

hive --hivevar CURRENT_DATE="2012-09-16" -f hive_query.sql

How to split strings into text and number?

I'm always the one to bring up findall() =)

>>> strings = ['foofo21', 'bar432', 'foobar12345']
>>> [re.findall(r'(\w+?)(\d+)', s)[0] for s in strings]
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]

Note that I'm using a simpler (less to type) regex than most of the previous answers.

Compile a DLL in C/C++, then call it from another program

There is but one difference. You have to take care or name mangling win C++. But on windows you have to take care about 1) decrating the functions to be exported from the DLL 2) write a so called .def file which lists all the exported symbols.

In Windows while compiling a DLL have have to use

__declspec(dllexport)

but while using it you have to write __declspec(dllimport)

So the usual way of doing that is something like

#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif

The naming is a bit confusing, because it is often named EXPORT.. But that's what you'll find in most of the headers somwhere. So in your case you'd write (with the above #define)

int DLL_EXPORT add.... int DLL_EXPORT mult...

Remember that you have to add the Preprocessor directive BUILD_DLL during building the shared library.

Regards Friedrich

How to clear the Entry widget after a button is pressed in Tkinter?

First of all, make sure the Text is enabled, then delete your tags, and then the content.

myText.config(state=NORMAL)
myText.tag_delete ("myTags")
myText.delete(1.0, END)

When the Text is "DISABLE", the delete does not work because the Text field is in read-only mode.

How to undo "git commit --amend" done instead of "git commit"

If you have pushed the commit to remote and then erroneously amended changes to that commit this will fix your problem. Issue a git log to find the SHA before the commit. (this assumes remote is named origin). Now issue these command using that SHA.

git reset --soft <SHA BEFORE THE AMMEND>
#you now see all the changes in the commit and the amend undone

#save ALL the changes to the stash
git stash

git pull origin <your-branch> --ff-only
#if you issue git log you can see that you have the commit you didn't want to amend

git stash pop
#git status reveals only the changes you incorrectly amended

#now you can create your new unamended commit

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

Why compile Python code?

It's compiled to bytecode which can be used much, much, much faster.

The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.

Important addition by Ben Blank:

It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster.

How to get current screen width in CSS?

Use the CSS3 Viewport-percentage feature.

Viewport-Percentage Explanation

Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <title>Styles</title>_x000D_
_x000D_
    <style>_x000D_
        @media screen and (min-width: 480px) {_x000D_
            body {_x000D_
                background-color: skyblue;_x000D_
                width: 90vw;_x000D_
                height: 90vh;_x000D_
                border: groove black;_x000D_
            }_x000D_
_x000D_
            div#main {_x000D_
                font-size: 3vw;_x000D_
            }_x000D_
        }_x000D_
    </style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div id="main">_x000D_
        Viewport-Percentage Test_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Should I use Vagrant or Docker for creating an isolated environment?

I preface my reply by admitting I have no experience with Docker, other than as an avid observer of what looks to be a really neat solution that's gaining a lot of traction.

I do have a decent amount of experience with Vagrant and can highly recommend it. It's certainly a more heavyweight solution in terms of it being VM based instead of LXC based. However, I've found a decent laptop (8 GB RAM, i5/i7 CPU) has no trouble running a VM using Vagrant/VirtualBox alongside development tooling.

One of the really great things with Vagrant is the integration with Puppet/Chef/shell scripts for automating configuration. If you're using one of these options to configure your production environment, you can create a development environment which is as close to identical as you're going to get, and this is exactly what you want.

The other great thing with Vagrant is that you can version your Vagrantfile along with your application code. This means that everyone else on your team can share this file and you're guaranteed that everyone is working with the same environment configuration.

Interestingly, Vagrant and Docker may actually be complimentary. Vagrant can be extended to support different virtualization providers, and it may be possible that Docker is one such provider which gets support in the near future. See https://github.com/dotcloud/docker/issues/404 for recent discussion on the topic.

Calculate time difference in Windows batch file

A re-hash of Aacini's code because most likely you are going to set the start time as a variable and want to save that data for output:

    @echo off

    rem ******************  MAIN CODE SECTION
    set STARTTIME=%TIME%

    rem Your code goes here (remove the ping line)
    ping -n 4 -w 1 127.0.0.1 >NUL

    set ENDTIME=%TIME%

    rem ******************  END MAIN CODE SECTION


    rem Change formatting for the start and end times
    for /F "tokens=1-4 delims=:.," %%a in ("%STARTTIME%") do (
       set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
    )

    for /F "tokens=1-4 delims=:.," %%a in ("%ENDTIME%") do ( 
       IF %ENDTIME% GTR %STARTTIME% set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100" 
       IF %ENDTIME% LSS %STARTTIME% set /A "end=((((%%a+24)*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100" 
    )

    rem Calculate the elapsed time by subtracting values
    set /A elapsed=end-start

    rem Format the results for output
    set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
    if %hh% lss 10 set hh=0%hh%
    if %mm% lss 10 set mm=0%mm%
    if %ss% lss 10 set ss=0%ss%
    if %cc% lss 10 set cc=0%cc%

    set DURATION=%hh%:%mm%:%ss%,%cc%

    echo Start    : %STARTTIME%
    echo Finish   : %ENDTIME%
    echo          ---------------
    echo Duration : %DURATION% 

Output:

    Start    : 11:02:45.92
    Finish   : 11:02:48.98
             ---------------
    Duration : 00:00:03,06

source command not found in sh shell

This problem happens because jenkins Execute Shell runs the script via its /bin/sh

Consequently, /bin/sh does not know "source"

You just need to add the below line at the top of your Execute Shell in jenkins

#!/bin/bash

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

self referential struct definition?

A Structure which contain a reference to itself. A common occurrence of this in a structure which describes a node for a link list. Each node needs a reference to the next node in the chain.

struct node
{
       int data;
       struct node *next; // <-self reference
};

Standard concise way to copy a file in Java?

Now with Java 7, you can use the following try-with-resource syntax:

public static void copyFile( File from, File to ) throws IOException {

    if ( !to.exists() ) { to.createNewFile(); }

    try (
        FileChannel in = new FileInputStream( from ).getChannel();
        FileChannel out = new FileOutputStream( to ).getChannel() ) {

        out.transferFrom( in, 0, in.size() );
    }
}

Or, better yet, this can also be accomplished using the new Files class introduced in Java 7:

public static void copyFile( File from, File to ) throws IOException {
    Files.copy( from.toPath(), to.toPath() );
}

Pretty snazzy, eh?

How to create XML file with specific structure in Java

Use JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}
package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

    }
}

How do I check if string contains substring?

The includes() method determines whether one string may be found within another string, returning true or false as appropriate.

Syntax :-string.includes(searchString[, position])

searchString:-A string to be searched for within this string.

position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.

string = 'LOL';
console.log(string.includes('lol')); // returns false 
console.log(string.includes('LOL')); // returns true 

Foreign key referring to primary keys across multiple tables?

Actually I do this myself. I have a table called 'Comments' which contains comments for records in 3 other tables. Neither solution actually handles everything you probably want it to. In your case, you would do this:

Solution 1:

  1. Add a tinyint field to employees_ce and employees_sn that has a default value which is different in each table (This field represents a 'table identifier', so we'll call them tid_ce & tid_sn)

  2. Create a Unique Index on each table using the table's PK and the table id field.

  3. Add a tinyint field to your 'Deductions' table to store the second half of the foreign key (the Table ID)

  4. Create 2 foreign keys in your 'Deductions' table (You can't enforce referential integrity, because either one key will be valid or the other...but never both:

    ALTER TABLE [dbo].[Deductions]  WITH NOCHECK ADD  CONSTRAINT [FK_Deductions_employees_ce] FOREIGN KEY([id], [fk_tid])
    REFERENCES [dbo].[employees_ce] ([empid], [tid])
    NOT FOR REPLICATION 
    GO
    ALTER TABLE [dbo].[Deductions] NOCHECK CONSTRAINT [FK_600_WorkComments_employees_ce]
    GO
    ALTER TABLE [dbo].[Deductions]  WITH NOCHECK ADD  CONSTRAINT [FK_Deductions_employees_sn] FOREIGN KEY([id], [fk_tid])
    REFERENCES [dbo].[employees_sn] ([empid], [tid])
    NOT FOR REPLICATION 
    GO
    ALTER TABLE [dbo].[Deductions] NOCHECK CONSTRAINT [FK_600_WorkComments_employees_sn]
    GO
    
    employees_ce
    --------------
    empid    name     tid
    khce1   prince    1
    
    employees_sn
    ----------------
    empid    name     tid 
    khsn1   princess  2
    
    deductions
    ----------------------
    id      tid       name  
    khce1   1         gold
    khsn1   2         silver         
    ** id + tid creates a unique index **
    

Solution 2: This solution allows referential integrity to be maintained: 1. Create a second foreign key field in 'Deductions' table , allow Null values in both foreign keys, and create normal foreign keys:

    employees_ce
    --------------
    empid   name
    khce1   prince 

    employees_sn
    ----------------
    empid   name     
    khsn1   princess 

    deductions
    ----------------------
    idce    idsn      name  
    khce1   *NULL*    gold
    *NULL*  khsn1     silver         

Integrity is only checked if the column is not null, so you can maintain referential integrity.

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

What's the difference between a mock & stub?

Reading all the explanations above, let me try to condense:

  • Stub: a dummy piece of code that lets the test run, but you don't care what happens to it.
  • Mock: a dummy piece of code, that you VERIFY is called correctly as part of the test.
  • Spy: a dummy piece of code, that intercepts some calls to a real piece of code, allowing you to verify calls without replacing the entire original object.

onclick="javascript:history.go(-1)" not working in Chrome

Use Simply this line code, there is no need to put anything in href attribute:

<a href="" onclick="window.history.go(-1)"> Go TO Previous Page</a>

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

If you modify the grant tables manually (using INSERT, UPDATE, etc.), you should execute a FLUSH PRIVILEGES statement to tell the server to reload the grant tables.

PS: I wouldn't recommend to allow any host to connect for any user (especially not the root use). If you are using mysql for a client/server application, prefer a subnet address. If you are using mysql with a web server or application server, use specific IPs.

How to get the nvidia driver version from the command line?

[NOTE: I am not deleting my answer on purpose, so people see how not to do it]

If you use:

me@over_there:~$  dpkg --status nvidia-current | grep Version | cut -f 1 -d '-' | sed 's/[^.,0-9]//g'
260.19.06

you will get the version of the nVIDIA driver package installed through your distribution's packaging mechanism. But this may not be the version that is actually running as part of your kernel right now.

Find a value anywhere in a database

If you need to run such search only once then you can probably go with any of the scripts already shown in other answers. But otherwise, I’d recommend using ApexSQL Search for this. It’s a free SSMS addin and it really saved me a lot of time.

Before running any of the scripts you should customize it based on the data type you want to search. If you know you are searching for datetime column then there is no need to search through nvarchar columns. This will speed up all of the queries above.

int array to string

You can do:

 int[] arr = {0,1,2,3,0,1};
 string results = string.Join("",arr.Select(i => i.ToString()).ToArray());

That gives you your results.

Why can't I display a pound (£) symbol in HTML?

This works in all chrome, IE, Firefox.

In Database > table > field type .for example set the symbol column TO varchar(2) utf8_bin php code:

$symbol = '£';
echo mb_convert_encoding($symbol, 'UTF-8', 'HTML-ENTITIES');
or 
html_entity_decode($symbol, ENT_NOQUOTES, 'UTF-8');

And also make sure set the HTML OR XML encoding to encoding="UTF-8"

Note: You should make sure that database, document type and php code all have a same encoding

How ever the better solution would be using &pound;

C# 4.0: Convert pdf to byte[] and vice versa

using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}

How to create a folder with name as current date in batch (.bat) files

For YYYY.MM.DD format with HUN settings use following. It converts "2021. 02. 23." to "2021.02.23":

SET dirname="%date:~0,5%%date:~6,3%%date:~10,2%"
md %dirname%

jQuery - setting the selected value of a select control via its text description

Select by description for jQuery v1.6+

_x000D_
_x000D_
var text1 = 'Two';_x000D_
$("select option").filter(function() {_x000D_
  //may want to use $.trim in here_x000D_
  return $(this).text() == text1;_x000D_
}).prop('selected', true);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
  <option value="0">One</option>_x000D_
  <option value="1">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

jQuery versions below 1.6 and greater than or equal to 1.4

_x000D_
_x000D_
var text1 = 'Two';_x000D_
$("select option").filter(function() {_x000D_
  //may want to use $.trim in here_x000D_
  return $(this).text() == text1;_x000D_
}).attr('selected', true);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
  <option value="0">One</option>_x000D_
  <option value="1">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.


Previous versions

val() should handle both cases.

_x000D_
_x000D_
$('select').val('1'); // selects "Two"_x000D_
$('select').val('Two'); // also selects "Two"
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
  <option value="0">One</option>_x000D_
  <option value="1">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Restart pods when configmap updates in Kubernetes?

Another way is to stick it into the command section of the Deployment:

...
command: [ "echo", "
  option = value\n
  other_option = value\n
" ]
...

Alternatively, to make it more ConfigMap-like, use an additional Deployment that will just host that config in the command section and execute kubectl create on it while adding an unique 'version' to its name (like calculating a hash of the content) and modifying all the deployments that use that config:

...
command: [ "/usr/sbin/kubectl-apply-config.sh", "
  option = value\n
  other_option = value\n
" ]
...

I'll probably post kubectl-apply-config.sh if it ends up working.

(don't do that; it looks too bad)

nginx 502 bad gateway

I executed my localhost and the page displayed the 502 bad gateway message. This helped me:

  1. Edit /etc/php5/fpm/pool.d/www.conf
  2. Change listen = /var/run/php5-fpm.sock to listen = 127.0.0.1:9000
  3. Ensure the location is set properly in nginx.conf.
  4. Run sudo service php5-fpm restart

Maybe it will help you.

Source from: http://wildlyinaccurate.com/solving-502-bad-gateway-with-nginx-php-fpm

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

This was a Tomcat bug that resurfaced again with the Java 9 bytecode. The exact versions which fix this (for both Java 8/9 bytecode) are:

  • trunk for 9.0.0.M18 onwards
  • 8.5.x for 8.5.12 onwards
  • 8.0.x for 8.0.42 onwards
  • 7.0.x for 7.0.76 onwards

How to create a DataFrame of random integers with Pandas?

numpy.random.randint accepts a third argument (size) , in which you can specify the size of the output array. You can use this to create your DataFrame -

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Here - np.random.randint(0,100,size=(100, 4)) - creates an output array of size (100,4) with random integer elements between [0,100) .


Demo -

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

which produces:

     A   B   C   D
0   45  88  44  92
1   62  34   2  86
2   85  65  11  31
3   74  43  42  56
4   90  38  34  93
5    0  94  45  10
6   58  23  23  60
..  ..  ..  ..  ..

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

How do you use the "WITH" clause in MySQL?

I liked @Brad's answer from this thread, but wanted a way to save the results for further processing (MySql 8):

-- May need to adjust the recursion depth first
SET @@cte_max_recursion_depth = 10000 ; -- permit deeper recursion

-- Some boundaries 
set @startDate = '2015-01-01'
    , @endDate = '2020-12-31' ; 

-- Save it to a table for later use
drop table if exists tmpDates ;
create temporary table tmpDates as      -- this has to go _before_ the "with", Duh-oh! 
    WITH RECURSIVE t as (
        select @startDate as dt
      UNION
        SELECT DATE_ADD(t.dt, INTERVAL 1 DAY) FROM t WHERE DATE_ADD(t.dt, INTERVAL 1 DAY) <= @endDate
    )
    select * FROM t     -- need this to get the "with"'s results as a "result set", into the "create"
;

-- Exists?
select * from tmpDates ;

Which produces:

dt        |
----------|
2015-01-01|
2015-01-02|
2015-01-03|
2015-01-04|
2015-01-05|
2015-01-06|

How to solve javax.net.ssl.SSLHandshakeException Error?

Now I solved this issue in this way,

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream;
// Create a trust manager that does not validate certificate chains like the 
default TrustManager[] trustAllCerts = new TrustManager[] {
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            //No need to implement. 
        }
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            //No need to implement. 
        }
    }
};
// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
    System.out.println(e);
}

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

Submit Button Image

<input type="image" src="path to image" name="submit" />

UPDATE:

For button states, you can use type="submit" and then add a class to it

<input type="submit" name="submit" class="states" />

Then in css, use background images for:

.states{
background-image:url(path to url);
height:...;
width:...;
}

.states:hover{
background-position:...;
}

.states:active{
background-position:...;
}

How can I create persistent cookies in ASP.NET?

You need to add this as the last line...

HttpContext.Current.Response.Cookies.Add(userid);

When you need to read the value of the cookie, you'd use a method similar to this:

    string cookieUserID= String.Empty;

    try
    {
        if (HttpContext.Current.Request.Cookies["userid"] != null)
        {
            cookieUserID = HttpContext.Current.Request.Cookies["userid"];
        }
    }
    catch (Exception ex)
    {
       //handle error
    }

    return cookieUserID;

How to add a Java Properties file to my Java Project in Eclipse

It should work ok as it is in Unix, if you have properties file in current working directory. Another option would be adding your properties file to the classpath and getting the inputstream using this.getClass().getClassLoader().getResourceAsStream("xxxxx.properties"); More here

Pass by pointer & Pass by reference

Here is a good article on the matter - "Use references when you can, and pointers when you have to."

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

This error can be because of no SSH key on the your local machine. Check the SSH key locally:

$ cat ~/.ssh/id_rsa.pub

If above command do not give any output use below command to create ssh key(Linux/Mac):

$ ssh-keygen 

Now again run cat ~/.ssh/id_rsa.pub This is your SSH key. Copy and add this key to your SSH keys in on git. In gitlab/bitbucket go to

profile settings -> SSH Keys -> add Key

and add the key

Javascript: how to validate dates in format MM-DD-YYYY?

what isn't working about it? here's a tested version:

String.prototype.isValidDate = function()   {

    const match = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
    if (!match || match.length !== 4) {
        return false
    }

    const test = new Date(match[3], match[1] - 1, match[2]);

    return (
        (test.getMonth() == match[1] - 1) &&
        (test.getDate() == match[2]) &&
        (test.getFullYear() == match[3])
    );
}

var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
alert(date.isValidDate() ); // true

How can I parse JSON with C#?

Here are some options without using third party libraries:

// For that you will need to add reference to System.Runtime.Serialization
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"), new System.Xml.XmlDictionaryReaderQuotas());

// For that you will need to add reference to System.Xml and System.Xml.Linq
var root = XElement.Load(jsonReader);
Console.WriteLine(root.XPathSelectElement("//Name").Value);
Console.WriteLine(root.XPathSelectElement("//Address/State").Value);

// For that you will need to add reference to System.Web.Helpers
dynamic json = System.Web.Helpers.Json.Decode(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }");
Console.WriteLine(json.Name);
Console.WriteLine(json.Address.State);

See the link for more information about System.Web.Helpers.Json.

Update: Nowadays the easiest way to get the Web.Helpers is to use the NuGet package.


If you don't care about earlier windows versions you can use the classes of the Windows.Data.Json namespace:

// minimum supported version: Win 8
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
Console.WriteLine(root["Name"].GetString());
Console.WriteLine(root["Address"].GetObject()["State"].GetString());

Using Custom Domains With IIS Express

David's solution is good. But I found the <script>alert(document.domain);</script> in the page still alerts "localhost" because the Project Url is still localhost even if it has been override with http://dev.example.com. Another issue I run into is that it alerts me the port 80 has already been in use even if I have disabled the Skype using the 80 port number as recommended by David Murdoch. So I have figured out another solution that is much easier:

  1. Run Notepad as administrator, and open the C:\Windows\System32\drivers\etc\hosts, add 127.0.0.1 mydomain, and save the file;
  2. Open the web project with Visual Studio 2013 (Note: must also run as administrator), right-click the project -> Properties -> Web, (lets suppose the Project Url under the "IIS Express" option is http://localhost:33333/), then change it from http://localhost:33333/ to http://mydomain:333333/ Note: After this change, you should neither click the "Create Virtual Directory" button on the right of the Project Url box nor click the Save button of the Visual Studio as they won't be succeeded. You can save your settings after next step 3.
  3. Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config, search for "33333:localhost", then update it to "33333:mydomain" and save the file.
  4. Save your setting as mentioned in step 2.
  5. Right click a web page in your visual studio, and click "View in Browser". Now the page will be opened under http://mydomain:333333/, and <script>alert(document.domain);</script> in the page will alert "mydomain".

Note: The port number listed above is assumed to be 33333. You need to change it to the port number set by your visual studio.

Post edited: Today I tried with another domain name and got the following error: Unable to launch the IIS Express Web server. Failed to register URL... Access is denied. (0x80070005). I exit the IIS Express by right clicking the IIS Express icon at the right corner in the Windows task bar, and then re-start my visual studio as administrator, and the issue is gone.

Find if a textbox is disabled or not using jquery

 if($("element_selector").attr('disabled') || $("element_selector").prop('disabled'))
 {

    // code when element is disabled

  }

How can a file be copied?

Copying a file is a relatively straightforward operation as shown by the examples below, but you should instead use the shutil stdlib module for that.

def copyfileobj_example(source, dest, buffer_size=1024*1024):
    """      
    Copy a file from source to dest. source and dest
    must be file-like objects, i.e. any object with a read or
    write method, like for example StringIO.
    """
    while True:
        copy_buffer = source.read(buffer_size)
        if not copy_buffer:
            break
        dest.write(copy_buffer)

If you want to copy by filename you could do something like this:

def copyfile_example(source, dest):
    # Beware, this example does not handle any edge cases!
    with open(source, 'rb') as src, open(dest, 'wb') as dst:
        copyfileobj_example(src, dst)

Is there any JSON Web Token (JWT) example in C#?

I've never used it but there is a JWT implementation on NuGet.

Package: https://nuget.org/packages/JWT

Source: https://github.com/johnsheehan/jwt

.NET 4.0 compatible: https://www.nuget.org/packages/jose-jwt/

You can also go here: https://jwt.io/ and click "libraries".

Adding an external directory to Tomcat classpath

What I suggest you do is add a META-INF directory with a MANIFEST.MF file in .war file.

Please note that according to servlet spec, it must be a .war file and not .war directory for the META-INF/MANIFEST.MF to be read by container.

Edit the MANIFEST.MF Class-Path property to C:\app_config\java_app:

See Using JAR Files: The Basics (Understanding the Manifest)

Enjoy.

How do I add a new column to a Spark DataFrame (using PySpark)?

The simplest way to add a column is to use "withColumn". Since the dataframe is created using sqlContext, you have to specify the schema or by default can be available in the dataset. If the schema is specified, the workload becomes tedious when changing every time.

Below is an example that you can consider:

from pyspark.sql import SQLContext
from pyspark.sql.types import *
sqlContext = SQLContext(sc) # SparkContext will be sc by default 

# Read the dataset of your choice (Already loaded with schema)
Data = sqlContext.read.csv("/path", header = True/False, schema = "infer", sep = "delimiter")

# For instance the data has 30 columns from col1, col2, ... col30. If you want to add a 31st column, you can do so by the following:
Data = Data.withColumn("col31", "Code goes here")

# Check the change 
Data.printSchema()

How to display a database table on to the table in the JSP page

Tracking ID Track
    <br>
    <%String id = request.getParameter("track_id");%>
       <%if (id.length() == 0) {%>
    <b><h1>Please Enter Tracking ID</h1></b>
    <% } else {%>
    <div class="container">
        <table border="1" class="table" >
            <thead>
                <tr class="warning" >
                    <td ><h4>Track ID</h4></td>
                    <td><h4>Source</h4></td>
                    <td><h4>Destination</h4></td>
                    <td><h4>Current Status</h4></td>

                </tr>
            </thead>
            <%
                try {
                    connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                    statement = connection.createStatement();
                    String sql = "select * from track where track_id="+ id;
                    resultSet = statement.executeQuery(sql);
                    while (resultSet.next()) {
            %>
            <tr class="info">
                <td><%=resultSet.getString("track_id")%></td>
                <td><%=resultSet.getString("source")%></td>
                <td><%=resultSet.getString("destination")%></td>
                <td><%=resultSet.getString("status")%></td>
            </tr>
            <%
                    }
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            %>
        </table>

        <%}%>
</body>

What does "<>" mean in Oracle

In mysql extended version, <> gives out error. You are using mysql_query Eventually, you have to use extended version of my mysql. Old will be replaced in future browser. Rather use something like

$con = mysqli_connect("host", "username", "password", "databaseName");

mysqli_query($con, "select orderid != 650");

What does %5B and %5D in POST requests stand for?

The data would probably have been posted originally from a web form looking a bit like this (but probably much more complicated):

<form action="http://example.com" method="post">

  User login    <input name="user[login]"    /><br />
  User password <input name="user[password]" /><br />

  <input type="submit" />
</form>

If the method were "get" instead of "post", clicking the submit button would take you to a URL looking a bit like this:

http://example.com/?user%5Blogin%5D=username&user%5Bpassword%5D=123456

or:

http://example.com/?user[login]=username&user[password]=123456

The web server on the other end will likely take the user[login] and user[password] parameters, and make them into a user object with login and password fields containing those values.

Is it possible to indent JavaScript code in Notepad++?

JSTool is the best for stability.

Steps:

  1. Select menu Plugins>Plugin Manager>Show Plugin Manager
  2. Check to JSTool checkbox > Install > Restart Notepad++
  3. Open js file > Plugins > JSTool > JSFormat
    screenshot

Reference:

PHP: trying to create a new line with "\n"

the html element break line depend of it's white-space style property. in the most of the elements the default white-space is auto, which mean break line when the text come to the width of the element. if you want the text break by \n you have to give to the parent element the style: white space: pre-line, which will read the \n and break the line, or white-space: pre which will also read \t etc. note: to write \n as break-line and not as a string , you have to use a double quoted string ("\n") if you not wanna use a white space, you always welcome to use the HTML Element for break line, which is <br/>

Move an item inside a list?

l = list(...)
if item in l:
    l.remove(item) #  checks if the item to be moved is present in the list 
l.insert(new_index,item)

Concatenate text files with Windows command line, dropping leading lines

The help for copy explains that wildcards can be used to concatenate multiple files into one.

For example, to copy all .txt files in the current folder that start with "abc" into a single file named xyz.txt:

copy abc*.txt xyz.txt

How to set ssh timeout?

If all else fails (including not having the timeout command) the concept in this shell script will work:

 #!/bin/bash
 set -u
 ssh $1 "sleep 10 ; uptime" > /tmp/outputfile 2>&1 & PIDssh=$!
 Count=0
 while test $Count -lt 5 && ps -p $PIDssh > /dev/null
 do
    echo -n .
    sleep 1
    Count=$((Count+1))
 done
 echo ""

 if ps -p $PIDssh > /dev/null
 then
    echo "ssh still running, killing it"
    kill -HUP $PIDssh
 else
    echo "Exited"
 fi

Change color inside strings.xml

You do not set such attributes in strings.xml type of files. You need to set it in your code. or (which is better solution) create style with colors you want and apply to your TextView

PHP: How to check if image file exists?

Read first 5 bytes form HTTP using fopen() and fread() then use this:

DEFINE("GIF_START","GIF");
DEFINE("PNG_START",pack("C",0x89)."PNG");
DEFINE("JPG_START",pack("CCCCCC",0xFF,0xD8,0xFF,0xE0,0x00,0x10)); 

to detect image.

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

including above solution if still facing issue try as below, Considerign the case where escape is not supported for TS.

blob = new Blob(["\ufeff", csv_content]); // this will make symbols to appears in excel 

for csv_content you can try like below.

function b64DecodeUnicode(str: any) {        
        return decodeURIComponent(atob(str).split('').map((c: any) => {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    }

How to set a parameter in a HttpServletRequest?

From your question, I think what you are trying to do is to store something (an object, a string...) to foward it then to another servlet, using RequestDispatcher(). To do this you don't need to set a paramater but an attribute using

void setAttribute(String name, Object o);

and then

Object getAttribute(String name);

IndentationError: unexpected indent error

As the error says you have not correctly indented code, check_exists_sql is not aligned with line above it cursor = db.cursor() .

Also use 4 spaces for indentation.

Read this http://diveintopython.net/getting_to_know_python/indenting_code.html

jQuery: how to find first visible input/select/textarea excluding buttons?

Here is my solution. The code should be easy enough to follow but here is the idea:

  • get all inputs, selects, and textareas
  • filter out all buttons and hidden fields
  • filter to only enabled, visible fields
  • select the first one
  • focus the selected field

The code:

function focusFirst(parent) {
    $(parent).find('input, textarea, select')
        .not('input[type=hidden],input[type=button],input[type=submit],input[type=reset],input[type=image],button')
        .filter(':enabled:visible:first')
        .focus();
}

Then simply call focusFirst with your parent element or selector.

Selector:

focusFirst('form#aspnetForm');

Element:

var el = $('form#aspnetForm');
focusFirst(el);

What is getattr() exactly and how do I use it?

A pretty common use case for getattr is mapping data to functions.

For instance, in a web framework like Django or Pylons, getattr makes it straightforward to map a web request's URL to the function that's going to handle it. If you look under the hood of Pylons's routing, for instance, you'll see that (by default, at least) it chops up a request's URL, like:

http://www.example.com/customers/list

into "customers" and "list". Then it searches for a controller class named CustomerController. Assuming it finds the class, it creates an instance of the class and then uses getattr to get its list method. It then calls that method, passing it the request as an argument.

Once you grasp this idea, it becomes really easy to extend the functionality of a web application: just add new methods to the controller classes, and then create links in your pages that use the appropriate URLs for those methods. All of this is made possible by getattr.