Programs & Examples On #Llblgenpro

LLBLGen is an Object Relational Mapper (O/RM) for .NET. With it you can generate your data access layer for multiple O/RM frameworks (LLBLGen Pro Runtime Framework, Entity Framework, Linq to Sql, and NHibernate 2.x / 3.0 (hbm.xml and FluentNHibernate)).

How to see if an object is an array without using reflection?

There is no subtyping relationship between arrays of primitive type, or between an array of a primitive type and array of a reference type. See JLS 4.10.3.

Therefore, the following is incorrect as a test to see if obj is an array of any kind:

// INCORRECT!
public boolean isArray(final Object obj) {
    return obj instanceof Object[];
}

Specifically, it doesn't work if obj is 1-D array of primitives. (It does work for primitive arrays with higher dimensions though, because all array types are subtypes of Object. But it is moot in this case.)

I use Google GWT so I am not allowed to use reflection :(

The best solution (to the isArray array part of the question) depends on what counts as "using reflection".

  • In GWT, calling obj.getClass().isArray() does not count as using reflection1, so that is the best solution.

  • Otherwise, the best way of figuring out whether an object has an array type is to use a sequence of instanceof expressions.

    public boolean isArray(final Object obj) {
        return obj instanceof Object[] || obj instanceof boolean[] ||
           obj instanceof byte[] || obj instanceof short[] ||
           obj instanceof char[] || obj instanceof int[] ||
           obj instanceof long[] || obj instanceof float[] ||
           obj instanceof double[];
    }
    
  • You could also try messing around with the name of the object's class as follows, but the call to obj.getClass() is bordering on reflection.

    public boolean isArray(final Object obj) {
        return obj.getClass().toString().charAt(0) == '[';
    }
    

1 - More precisely, the Class.isArray method is listed as supported by GWT in this page.

What is "android.R.layout.simple_list_item_1"?

This is a part of the android OS. Here is the actual version of the defined XML file.

simple_list_item_1:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/listItemFirstLineStyle"
    android:paddingTop="2dip"
    android:paddingBottom="3dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

simple_list_item_2:

<TwoLineListItem xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="2dip"
    android:paddingBottom="2dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:id="@android:id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="?android:attr/listItemFirstLineStyle"/>

    <TextView android:id="@android:id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@android:id/text1"
        style="?android:attr/listItemSecondLineStyle" />

</TwoLineListItem> 

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.

Rename a column in MySQL

In mysql your query should be like

ALTER TABLE table_name change column_1 column_2 Data_Type;

you have written the query in Oracle.

Is Ruby pass by reference or by value?

Parameters are a copy of the original reference. So, you can change values, but cannot change the original reference.

Put Excel-VBA code in module or sheet?

I would suggest separating your code based on the functionality and purpose specific to each sheet or module. In this manner, you would only put code relative to a sheet's UI inside the sheet's module and only put code related to modules in respective modules. Also, use separate modules to encapsulate code that is shared or reused among several different sheets.

For example, let's say you multiple sheets that are responsible for displaying data from a database in a special way. What kinds of functionality do we have in this situation? We have functionality related to each specific sheet, tasks related to getting data from the database, and tasks related to populating a sheet with data. In this case, I might start with a module for the data access, a module for populating a sheet with data, and within each sheet I'd have code for accessing code in those modules.

It might be laid out like this.

Module: DataAccess:

Function GetData(strTableName As String, strCondition1 As String) As Recordset
    'Code Related to getting data from the database'
End Function

Module: PopulateSheet:

Sub PopulateASheet(wsSheet As Worksheet, rs As Recordset)
    'Code to populate a worksheet '
End Function

Sheet: Sheet1 Code:

Sub GetDataAndPopulate()
    'Sample Code'
     Dim rs As New Recordset
     Dim ws As Worksheet
     Dim strParam As String
     Set ws = ActiveSheet
     strParam = ws.Range("A1").Value

     Set rs = GetData("Orders",strParam)

     PopulateASheet ws, rs
End Sub

Sub Button1_Click()
    Call GetDataAndPopulate
End Sub

C++ printing spaces or tabs given a user input integer

I just happened to look for something similar and came up with this:

std::cout << std::setfill(' ') << std::setw(n) << ' ';

How to disable keypad popup when on edittext?

Use the following code, write it under onCreate()

InputMethodManager inputManager = (InputMethodManager)
                                   getSystemService(Context.INPUT_METHOD_SERVICE); 
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                   InputMethodManager.HIDE_NOT_ALWAYS);         
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Nullable property to entity field, Entity Framework through Code First

Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method

This worked for me though:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
    base.OnModelCreating(modelBuilder);
}

Convert character to ASCII code in JavaScript

If you have only one char and not a string, you can use:

'\n'.charCodeAt();

omitting the 0...

It used to be significantly slower than 'n'.charCodeAt(0), but I've tested it now and I do not see any difference anymore (executed 10 billions times with and without the 0). Tested for performance only in Chrome and Firefox.

printf formatting (%d versus %u)

%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Convert char to int in C#

Principle:

char foo = '2';
int bar = foo & 15;

The binary of the ASCII charecters 0-9 is:

0   -   0011 0000
1   -   0011 0001
2   -   0011 0010
3   -   0011 0011
4   -   0011 0100
5   -   0011 0101
6   -   0011 0110
7   -   0011 0111
8   -   0011 1000
9   -   0011 1001

and if you take in each one of them the first 4 LSB (using bitwise AND with 8'b00001111 that equals to 15) you get the actual number (0000 = 0,0001=1,0010=2,... )

Usage:

public static int CharToInt(char c)
{
    return 0b0000_1111 & (byte) c;
}

How can I move all the files from one folder to another using the command line?

robocopy seems to be the most versatile. See it's other options in the help

robocopy /?
robocopy SRC DST /E /MOV

var functionName = function() {} vs function functionName() {}

In terms of code maintenance cost, named functions are more preferable:

  • Independent from the place where they are declared (but still limited by scope).
  • More resistant to mistakes like conditional initialization (you are still able to override if wanted to).
  • The code becomes more readable by allocating local functions separately of scope functionality. Usually in the scope the functionality goes first, followed by declarations of local functions.
  • In a debugger you will clearly see the function name on the call stack instead of an "anonymous/evaluated" function.

I suspect more PROS for named functions are follow. And what is listed as an advantage of named functions is a disadvantage for anonymous ones.

Historically, anonymous functions appeared from the inability of JavaScript as a language to list members with named functions:

{
    member:function() { /* How do I make "this.member" a named function? */
    }
}

How can I disable an <option> in a <select> based on its value in JavaScript?

For some reason other answers are unnecessarily complex, it's easy to do it in one line in pure JavaScript:

Array.prototype.find.call(selectElement.options, o => o.value === optionValue).disabled = true;

or

selectElement.querySelector('option[value="'+optionValue.replace(/["\\]/g, '\\$&')+'"]').disabled = true;

The performance depends on the number of the options (the more the options, the slower the first one) and whether you can omit the escaping (the replace call) from the second one. Also the first one uses Array.find and arrow functions that are not available in IE11.

How to use range-based for() loop with std::map?

If you only want to see the keys/values from your map and like using boost, you can use the boost adaptors with the range based loops:

for (const auto& value : myMap | boost::adaptors::map_values)
{
    std::cout << value << std::endl;
}

there is an equivalent boost::adaptors::key_values

http://www.boost.org/doc/libs/1_51_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html

Adding an onclick function to go to url in JavaScript?

HTML

<input type="button" value="My Button" 
onclick="location.href = 'https://myurl'" />

MVC

<input type="button" value="My Button" 
onclick="location.href='@Url.Action("MyAction", "MyController", new { id = 1 })'" />

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

My solution:

Option Explicit
Public datHora As Date

Function Cronometro(action As Integer) As Integer 
'This return the seconds between two >calls
Cronometro = 0
  If action = 1 Then 'Start
    datHora = Now
  End If
  If action = 2 Then 'Time until that moment
    Cronometro = DateDiff("s", datHora, Now)
  End If
End Function

How to use? Easy...

dummy= Cronometro(1) ' This starts the timer

seconds= Cronometro(2) ' This returns the seconds between the first call and this one

bash assign default value

Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples

${parameter-default}, ${parameter:-default}

If parameter not set, use default. After the call, parameter is still not set.
Both forms are almost equivalent. The extra : makes a difference only when parameter has been declared, but is null.

unset EGGS
echo 1 ${EGGS-spam}   # 1 spam
echo 2 ${EGGS:-spam}  # 2 spam

EGGS=
echo 3 ${EGGS-spam}   # 3
echo 4 ${EGGS:-spam}  # 4 spam

EGGS=cheese
echo 5 ${EGGS-spam}   # 5 cheese
echo 6 ${EGGS:-spam}  # 6 cheese

${parameter=default}, ${parameter:=default}

If parameter not set, set parameter value to default.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

# sets variable without needing to reassign
# colons suppress attempting to run the string
unset EGGS
: ${EGGS=spam}
echo 1 $EGGS     # 1 spam
unset EGGS
: ${EGGS:=spam}
echo 2 $EGGS     # 2 spam

EGGS=
: ${EGGS=spam}
echo 3 $EGGS     # 3        (set, but blank -> leaves alone)
EGGS=
: ${EGGS:=spam}
echo 4 $EGGS     # 4 spam

EGGS=cheese
: ${EGGS:=spam}
echo 5 $EGGS     # 5 cheese
EGGS=cheese
: ${EGGS=spam}
echo 6 $EGGS     # 6 cheese

${parameter+alt_value}, ${parameter:+alt_value}

If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

unset EGGS
echo 1 ${EGGS+spam}  # 1
echo 2 ${EGGS:+spam} # 2

EGGS=
echo 3 ${EGGS+spam}  # 3 spam
echo 4 ${EGGS:+spam} # 4

EGGS=cheese
echo 5 ${EGGS+spam}  # 5 spam
echo 6 ${EGGS:+spam} # 6 spam

Adding a favicon to a static HTML page

I know its older post but still posting for someone like me. This worked for me

<link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />

put your favicon icon on root directory..

Getting URL hash location, and using it in jQuery

I'm using this to address the security implications noted in @CMS's answer.

// example 1: www.example.com/index.html#foo

// load correct subpage from URL hash if it exists
$(window).on('load', function () {
    var hash = window.location.hash;
    if (hash) {
        hash = hash.replace('#',''); // strip the # at the beginning of the string
        hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
        hash = '#' + hash; // hash now equals #foo with example 1

        // do stuff with hash
        $( 'ul' + hash + ':first' ).show();
        // etc...
    }
});

Set the maximum character length of a UITextField

I have implemented a UITextField Extension to add a maxLength property to it.

It's based on Xcode 6 IBInspectables, so you can set the maxLength limit on the Interface builder.

Here is the implementation:

UITextField+MaxLength.h

#import <UIKit/UIKit.h>

@interface UITextField_MaxLength : UITextField<UITextFieldDelegate>

@property (nonatomic)IBInspectable int textMaxLength;
@end

UITextField+MaxLength.m

#import "UITextField+MaxLength.h"

@interface UITextField_MaxLength()

@property (nonatomic, assign) id <UITextFieldDelegate> superDelegate;

@end

@implementation UITextField_MaxLength

- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    //validate the length, only if it's set to a non zero value
    if (self.textMaxLength>0) {
        if(range.length + range.location > textField.text.length)
            return NO;

        if (textField.text.length+string.length - range.length>self.textMaxLength) {
            return NO;
        }
    }

    //if length validation was passed, query the super class to see if the delegate method is implemented there
    if (self.superDelegate && [self.superDelegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
        return [self.superDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
    }
    else{
        //if the super class does not implement the delegate method, simply return YES as the length validation was passed
        return YES;
    }
}

- (void)setDelegate:(id<UITextFieldDelegate>)delegate {
    if (delegate == self)
        return;
    self.superDelegate = delegate;
    [super setDelegate:self];
}

//forward all non overriden delegate methods
- (id)forwardingTargetForSelector:(SEL)aSelector {
    if ([self.superDelegate  respondsToSelector:aSelector])
        return self.superDelegate;

    return [super forwardingTargetForSelector:aSelector];
}

- (BOOL)respondsToSelector:(SEL)aSelector {
    if ([self.superDelegate respondsToSelector:aSelector])
        return YES;

    return [super respondsToSelector:aSelector];
}
@end

Track a new remote branch created on GitHub

If you don't have an existing local branch, it is truly as simple as:

git fetch
git checkout <remote-branch-name>

For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page, just do this:

git checkout feature/Main_Page

This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:

git checkout -t <remote>/<remote-branch-name>

If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.

Set background color in PHP?

You must use CSS. Can't be done with PHP.

Time complexity of accessing a Python dict

You are not correct. dict access is unlikely to be your problem here. It is almost certainly O(1), unless you have some very weird inputs or a very bad hashing function. Paste some sample code from your application for a better diagnosis.

Add custom icons to font awesome

Similar approach to @Samuel-bergström:

  • Download Fontawesome SVG https://github.com/FortAwesome/Font-Awesome/blob/master/src/assets/font-awesome/fonts/fontawesome-webfont.svg
  • Download FontForge http://fontforge.github.io/en-US/downloads/
  • Download Inkscape
  • Open Inskscape and create a single layer shape as your new font icon
  • Save SVG file, Close Inkscape
  • Open FontForge (If you have multiple monitors, use Windows-LeftArrow, to reposition as they have strange SWING java windows that go off monitor, and have modal problems with popups - I had to check my task bar for some)
  • File | Open fontawesome-webfont.svg
  • File | Import
  • Scroll to the bottom, Right Click on Icon | Glyph Info
  • Update Glyph Name to uniFXXX (XXX is something like 501, a higher number than the highest Unicode used in v4.5 of FontAwesome)
  • Unicode Vlaue U+fXXX
  • Click OK
  • File | Save
  • File | Generate Fonts ...
  • Close FontForge
  • Open your web project
  • Copy your font files to the (in my project) "\Content\fonts\" folder.
  • Edit "\Content\styles\fa\path.less" to be like:

_x000D_
_x000D_
@font-face {_x000D_
      font-family: 'FontAwesome';_x000D_
      //src: url('@{fa-font-path}/fontawesome-webfont.eot?v=@{fa-version}');_x000D_
      src: _x000D_
     //url('@{fa-font-path}/fontawesome-webfont.eot?#iefix&v=@{fa-version}') format('embedded-opentype'),_x000D_
        //url('@{fa-font-path}/fontawesome-webfont.woff2?v=@{fa-version}') format('woff2'),_x000D_
        url('@{fa-font-path}/fontawesomeregular.woff?v=@{fa-version}') format('woff'),_x000D_
        url('@{fa-font-path}/fontawesomeregular.ttf?v=@{fa-version}') format('truetype'),_x000D_
        url('@{fa-font-path}/fontawesomeregular.svg?v=@{fa-version}#fontawesomeregular') format('svg');_x000D_
    //  src: url('@{fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts_x000D_
      font-weight: normal;_x000D_
      font-style: normal;_x000D_
    }
_x000D_
_x000D_
_x000D_

I know it may be 'controversial' to comment out other file types, but happy to hear how to generate .eot or .otf files in the comments.

  • and finally, as Samuel mentions, update your CSS/LESS with:

    .fa-XXX:before { content: "\f501"; }

How can I query for null values in entity framework?

Personnally, I prefer:

var result = from entry in table    
             where (entry.something??0)==(value??0)                    
              select entry;

over

var result = from entry in table
             where (value == null ? entry.something == null : entry.something == value)
             select entry;

because it prevents repetition -- though that's not mathematically exact, but it fits well most cases.

Java - Using Accessor and Mutator methods

You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

public class IDCard {
    public String name, fileName;
    public int id;

    public IDCard(final String name, final String fileName, final int id) {
        this.name = name;
        this.fileName = fileName
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

You can the create an IDCard and use the accessor like this:

final IDCard card = new IDCard();
card.getName();

Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

If you use the static keyword then those variables are common across every instance of IDCard.

A couple of things to bear in mind:

  1. don't add useless comments - they add code clutter and nothing else.
  2. conform to naming conventions, use lower case of variable names - name not Name.

jQuery scroll to ID from different page

You basically need to do this:

  • include the target hash into the link pointing to the other page (href="other_page.html#section")
  • in your ready handler clear the hard jump scroll normally dictated by the hash and as soon as possible scroll the page back to the top and call jump() - you'll need to do this asynchronously
  • in jump() if no event is given, make location.hash the target
  • also this technique might not catch the jump in time, so you'll better hide the html,body right away and show it back once you scrolled it back to zero

This is your code with the above added:

var jump=function(e)
{
   if (e){
       e.preventDefault();
       var target = $(this).attr("href");
   }else{
       var target = location.hash;
   }

   $('html,body').animate(
   {
       scrollTop: $(target).offset().top
   },2000,function()
   {
       location.hash = target;
   });

}

$('html, body').hide();

$(document).ready(function()
{
    $('a[href^=#]').bind("click", jump);

    if (location.hash){
        setTimeout(function(){
            $('html, body').scrollTop(0).show();
            jump();
        }, 0);
    }else{
        $('html, body').show();
    }
});

Verified working in Chrome/Safari, Firefox and Opera. I don't know about IE though.

How to get the selected date of a MonthCalendar control in C#

For those who are still trying, this link helped me out, too; it just puts it all together:

http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx

private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);

//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;

//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

How to disable Home and other system buttons in Android?

Frankly it is not possible to disable the home button at least on new api levels , that is from 4.0 onwards. It is also not advisable to do that. You can however, block the back button by overriding the

public void onBackPressed() {
    // do not call super onBackPressed.
}

in order to override the home button, you could use a timer for example, and after every time check if the main screen is your screen or not, or your package is on top or not, (i am sure you will get links to it), and display your activity using the flag single_top.

That way , even if the home button is pressed you will be able to bring your app to the top.

Also make sure that the app has a way to exit, because such kind of apps can really be annoying and should never be developed.

Happy coding.

P.S: It is not possible to intercept the home event, when the home button is pressed.

You can use on attach to window methods and also keyguard methods, but not for api levels from 4.0 onwards.

Best way to replace multiple characters in a string?

You may consider writing a generic escape function:

def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])

>>> esc = mk_esc('&#')
>>> print esc('Learn & be #1')
Learn \& be \#1

This way you can make your function configurable with a list of character that should be escaped.

Perl - Multiple condition if statement without duplicating code?

if (   ($name eq "tom" and $password eq "123!")
    or ($name eq "frank" and $password eq "321!")) {

    print "You have gained access.";
}
else {
    print "Access denied!";
}

Checking if a SQL Server login already exists

Here's a way to do this in SQL Server 2005 and later without using the deprecated syslogins view:

IF NOT EXISTS 
    (SELECT name  
     FROM master.sys.server_principals
     WHERE name = 'LoginName')
BEGIN
    CREATE LOGIN [LoginName] WITH PASSWORD = N'password'
END

The server_principals view is used instead of sql_logins because the latter doesn't list Windows logins.

If you need to check for the existence of a user in a particular database before creating them, then you can do this:

USE your_db_name

IF NOT EXISTS
    (SELECT name
     FROM sys.database_principals
     WHERE name = 'Bob')
BEGIN
    CREATE USER [Bob] FOR LOGIN [Bob] 
END

Splitting string with pipe character ("|")

Using Pattern.quote()

String[] value_split = rat_values.split(Pattern.quote("|"));

//System.out.println(Arrays.toString(rat_values.split(Pattern.quote("|")))); //(FOR GETTING OUTPUT)

Using Escape characters(for metacharacters)

String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)

Using StringTokenizer(For avoiding regular expression issues)

public static String[] splitUsingTokenizer(String Subject, String Delimiters) 
{
     StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
     ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
     while(StrTkn.hasMoreTokens())
     {
       ArrLis.add(StrTkn.nextToken());
     }
     return ArrLis.toArray(new String[0]);
}

Using Pattern class(java.util.regex.Pattern)

Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)

Output

[Food 1 ,  Service 3 ,  Atmosphere 3 ,  Value for money 1 ]

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

This problem usually occurs when you are trying to update an entity. For example you have an entity that contains a field called DateCreated which is [Required] and when you insert record, no error is returned but when you want to Update that particular entity, you the get the

datetime2 conversion out of range error.

Now here is the solution:

On your edit view, i.e. edit.cshtml for MVC users all you need to do is add a hidden form field for your DateCreated just below the hidden field for the primary key of the edit data.

Example:

@Html.HiddenFor(model => model.DateCreated)

Adding this to your edit view, you'll never have that error I assure you.

PHP Using RegEx to get substring of a string

$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);

This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.

php.net/preg-match

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

There are many other answers to this question, but still, the following works best for me, as I needed a command line solution:

vim -u NONE -c 'e ++ff=dos' -c 'w ++ff=unix' -c q myfile

Explanation:

  • Without loading any .vimrc files, open myfile
  • Run :e ++ff=dos to force a reload of the entire file as dos line endings.
  • Run :w ++ff=unix to write the file using unix line endings
  • Quit vim

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

There's one big difference between CLOCK_REALTIME and MONOTONIC. CLOCK_REALTIME can jump forward or backward according to NTP. By default, NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but NTP cannot cause the monotonic clock to jump forward or backward.

How to add icon to mat-icon-button

Just add the <mat-icon> inside mat-button or mat-raised-button. See the example below. Note that I am using material icon instead of your svg for demo purpose:

<button mat-button>
    <mat-icon>mic</mat-icon>
    Start Recording
</button>

OR

<button mat-raised-button color="accent">
    <mat-icon>mic</mat-icon>
    Start Recording
</button>

Here is a link to stackblitz demo.

How to create full path with node's fs.mkdirSync?

Now with NodeJS >= 10.12.0, you can use fs.mkdirSync(path, { recursive: true }) fs.mkdirSync

How do I get the opposite (negation) of a Boolean in Python?

If you are trying to implement a toggle, so that anytime you re-run a persistent code its being negated, you can achieve that as following:

try:
    toggle = not toggle
except NameError:
    toggle = True

Running this code will first set the toggle to True and anytime this snippet ist called, toggle will be negated.

Spring Security redirect to previous page after successful login

I found Utku Özdemir's solution works to some extent, but kind of defeats the purpose of the saved request since the session attribute will take precedence over it. This means that redirects to secure pages will not work as intended - after login you will be sent to the page you were on instead of the redirect target. So as an alternative you could use a modified version of SavedRequestAwareAuthenticationSuccessHandler instead of extending it. This will allow you to have better control over when to use the session attribute.

Here is an example:

private static class MyCustomLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest == null) {
            HttpSession session = request.getSession();
            if (session != null) {
                String redirectUrl = (String) session.getAttribute("url_prior_login");
                if (redirectUrl != null) {
                    session.removeAttribute("url_prior_login");
                    getRedirectStrategy().sendRedirect(request, response, redirectUrl);
                } else {
                    super.onAuthenticationSuccess(request, response, authentication);
                }
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }

            return;
        }

        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);

            return;
        }

        clearAuthenticationAttributes(request);

        // Use the DefaultSavedRequest URL
        String targetUrl = savedRequest.getRedirectUrl();
        logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }
}

Also, you don't want to save the referrer when authentication has failed, since the referrer will then be the login page itself. So check for the error param manually or provide a separate RequestMapping like below.

@RequestMapping(value = "/login", params = "error")
public String loginError() {
    // Don't save referrer here!
}

MySQL - how to front pad zip code with "0"?

LPAD works with VARCHAR2 as it does not put spaces for left over bytes. LPAD changes leftover/null bytes to zeros on LHS SO datatype should be VARCHAR2

MySQL LIKE IN()?

This would be correct:

SELECT * FROM table WHERE field regexp concat_ws("|",(
"111",
"222",
"333"
));

How can I disable the UITableView selection?

If you want selection to only flash, not remain in the selected state, you can call, in

didSelectRowAtIndexPath

the following

[tableView deselectRowAtIndexPath:indexPath animated:YES];

so it will flash the selected state and revert.

Always show vertical scrollbar in <select>

add:

overflow-y: scroll

in your css bud.

Difference between java HH:mm and hh:mm on SimpleDateFormat

Actually the last one is not weird. Code is setting the timezone for working instead of working2.

SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).

Fixing this error gives:

24:00:00
00:00:00
01:00:00

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

Beautiful Soup and extracting a div and its contents by ID

have you tried soup.findAll("div", {"id": "articlebody"})?

sounds crazy, but if you're scraping stuff from the wild, you can't rule out multiple divs...

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Users who have one of the 3 countries

SELECT DISTINCT user_id
FROM table
WHERE ancestry IN('England','France','Germany')

Users who have all 3 countries

SELECT DISTINCT A.userID
FROM table A
   INNER JOIN table B on A.user_id = B.user_id
   INNER JOIN table C on A.user_id = C.user_id
WHERE A.ancestry = 'England'
   AND B.ancestry = 'Germany'
   AND C.ancestry = 'France'

jQuery - Fancybox: But I don't want scrollbars!

Add iframe: { scrolling : 'no' } as option

example

$.fancybox({
href: 'yourUrl.html',
width: 800,
height: 415,
autoSize: false,
type : 'iframe',
iframe: {
scrolling : 'no',
preload   : true
}});

How to write std::string to file?

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

How can I get href links from HTML using Python?

Using requests with BeautifulSoup and Python 3:

import requests 
from bs4 import BeautifulSoup


page = requests.get('http://www.website.com')
bs = BeautifulSoup(page.content, features='lxml')
for link in bs.findAll('a'):
    print(link.get('href'))

Which UUID version to use?

Postgres documentation describes the differences between UUIDs. A couple of them:

V3:

uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

V4:

uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

How do I separate an integer into separate digits in an array in JavaScript?

(123456789).toString(10).split("")

^^ this will return an array of strings

(123456789).toString(10).split("").map(function(t){return parseInt(t)})

^^ this will return an array of ints

COALESCE with Hive SQL

Hive supports bigint literal since 0.8 version. So, additional "L" is enough:

COALESCE(column, 0L)

How do I authenticate a WebClient request?

Public Function getWeb(ByRef sURL As String) As String
    Dim myWebClient As New System.Net.WebClient()

    Try
        Dim myCredentialCache As New System.Net.CredentialCache()
        Dim myURI As New Uri(sURL)
        myCredentialCache.Add(myURI, "ntlm", System.Net.CredentialCache.DefaultNetworkCredentials)
        myWebClient.Encoding = System.Text.Encoding.UTF8
        myWebClient.Credentials = myCredentialCache
        Return myWebClient.DownloadString(myURI)
    Catch ex As Exception
        Return "Exception " & ex.ToString()
    End Try
End Function

Algorithm to detect overlapping periods

You can create a reusable Range pattern class :

public class Range<T> where T : IComparable
{
    readonly T min;
    readonly T max;

    public Range(T min, T max)
    {
        this.min = min;
        this.max = max;
    }

    public bool IsOverlapped(Range<T> other)
    {
        return Min.CompareTo(other.Max) < 0 && other.Min.CompareTo(Max) < 0;
    }

    public T Min { get { return min; } }
    public T Max { get { return max; } }
}

You can add all methods you need to merge ranges, get intersections and so on...

JAXB: How to ignore namespace during unmarshalling XML document?

I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.

That means:

  • Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.
  • Define a XMLReader which will set the content handler

then link the two together:

public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException 
{
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have
    }
}

Convert String to SecureString

below method helps to convert string to secure string

private SecureString ConvertToSecureString(string password)
{
    if (password == null)
        throw new ArgumentNullException("password");

    var securePassword = new SecureString();

    foreach (char c in password)
        securePassword.AppendChar(c);

    securePassword.MakeReadOnly();
    return securePassword;
}

what is the difference between GROUP BY and ORDER BY in sql

  1. GROUP BY will aggregate records by the specified column which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc.). ORDER BY alters the order in which items are returned.
  2. If you do SELECT IsActive, COUNT(*) FROM Customers GROUP BY IsActive you get a count of active and inactive customers. The group by aggregated the results based on the field you specified. If you do SELECT * FROM Customers ORDER BY Name then you get the result list sorted by the customer’s name.
  3. If you GROUP, the results are not necessarily sorted; although in many cases they may come out in an intuitive order, that's not guaranteed by the GROUP clause. If you want your groups sorted, always use an explicitly ORDER BY after the GROUP BY.
  4. Grouped data cannot be filtered by WHERE clause. Order data can be filtered by WHERE clause.

How to change value of a request parameter in laravel

If you need to customize the request

$data = $request->all();

you can pass the name of the field and the value

$data['product_ref_code'] = 1650;

and finally pass the new request

$last = Product::create($data);

How to replace master branch in Git, entirely, from another branch?

I found this to be the best way of doing this (I had an issue with my server not letting me delete).

On the server that hosts the origin repository, type the following from a directory inside the repository:

git config receive.denyDeleteCurrent ignore

On your workstation:

git branch -m master vabandoned                 # Rename master on local
git branch -m newBranch master                  # Locally rename branch newBranch to master
git push origin :master                         # Delete the remote's master
git push origin master:refs/heads/master        # Push the new master to the remote
git push origin abandoned:refs/heads/abandoned  # Push the old master to the remote

Back on the server that hosts the origin repository:

git config receive.denyDeleteCurrent true

Credit to the author of blog post http://www.mslinn.com/blog/?p=772

How to make the corners of a button round?

Is there an easy way to achieve this in Android?

Yes, today there is, and it is very simple.
Just use the MaterialButton in the Material Components library with the app:cornerRadius attribute.

Something like:

    <com.google.android.material.button.MaterialButton
        android:text="BUTTON"
        app:cornerRadius="8dp"
        ../>

enter image description here

It is enough to obtain a Button with rounded corners.

You can use one of Material button styles. For example:

<com.google.android.material.button.MaterialButton
    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
    .../>

enter image description here

Also starting from the version 1.1.0 you can also change the shape of your button. Just use the shapeAppearanceOverlay attribute in the button style:

  <style name="MyButtonStyle" parent="Widget.MaterialComponents.Button">
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Button.Rounded</item>
  </style>

  <style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">16dp</item>
  </style>

Then just use:

<com.google.android.material.button.MaterialButton
   style="@style/MyButtonStyle"
   .../>

You can also apply the shapeAppearanceOverlay in the xml layout:

<com.google.android.material.button.MaterialButton
   app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Rounded"
   .../>

The shapeAppearance allows also to have different shape and dimension for each corner:

<style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerFamilyTopRight">cut</item>
    <item name="cornerFamilyBottomRight">cut</item>
    <item name="cornerSizeTopLeft">32dp</item>
    <item name="cornerSizeBottomLeft">32dp</item>
</style>

enter image description here

This Handler class should be static or leaks might occur: IncomingHandler

With the help of @Sogger's answer, I created a generic Handler:

public class MainThreadHandler<T extends MessageHandler> extends Handler {

    private final WeakReference<T> mInstance;

    public MainThreadHandler(T clazz) {
        // Remove the following line to use the current thread.
        super(Looper.getMainLooper());
        mInstance = new WeakReference<>(clazz);
    }

    @Override
    public void handleMessage(Message msg) {
        T clazz = mInstance.get();
        if (clazz != null) {
            clazz.handleMessage(msg);
        }
    }
}

The interface:

public interface MessageHandler {

    void handleMessage(Message msg);

}

I'm using it as follows. But I'm not 100% sure if this is leak-safe. Maybe someone could comment on this:

public class MyClass implements MessageHandler {

    private static final int DO_IT_MSG = 123;

    private MainThreadHandler<MyClass> mHandler = new MainThreadHandler<>(this);

    private void start() {
        // Do it in 5 seconds.
        mHandler.sendEmptyMessageDelayed(DO_IT_MSG, 5 * 1000);
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case DO_IT_MSG:
                doIt();
                break;
        }
    }

    ...

}

jQuery removing '-' character from string

$mylabel.text("-123456");
var string = $mylabel.text().replace('-', '');

if you have done it that way variable string now holds "123456"

you can also (i guess the better way) do this...

$mylabel.text("-123456");
$mylabel.text(function(i,v){
   return v.replace('-','');
});

Dynamically add event listener

Here's my workaround:

I created a library with Angular 6. I added a common component commonlib-header which is used like this in an external application.

Note the serviceReference which is the class (injected in the component constructor(public serviceReference: MyService) that uses the commonlib-header) that holds the stringFunctionName method:

<commonlib-header
    [logo]="{ src: 'assets/img/logo.svg', alt: 'Logo', href: '#' }"
    [buttons]="[{ index: 0, innerHtml: 'Button', class: 'btn btn-primary', onClick: [serviceReference, 'stringFunctionName', ['arg1','arg2','arg3']] }]">
    </common-header>

The library component is programmed like this. The dynamic event is added in the onClick(fn: any) method:

export class HeaderComponent implements OnInit {

 _buttons: Array<NavItem> = []

 @Input()
  set buttons(buttons: Array<any>) {
    buttons.forEach(navItem => {
      let _navItem = new NavItem(navItem.href, navItem.innerHtml)

      _navItem.class = navItem.class

      _navItem.onClick = navItem.onClick // this is the array from the component @Input properties above

      this._buttons[navItem.index] = _navItem
    })
  }

  constructor() {}

  ngOnInit() {}

  onClick(fn: any){
    let ref = fn[0]
    let fnName = fn[1]
    let args = fn[2]

    ref[fnName].apply(ref, args)
  }

The reusable header.component.html:

<div class="topbar-right">
  <button *ngFor="let btn of _buttons"
    class="{{ btn.class }}"
    (click)="onClick(btn.onClick)"
    [innerHTML]="btn.innerHtml | keepHtml"></button>
</div>

How do I install and use curl on Windows?

  • Download curl for windows from the path : https://curl.haxx.se/windows/
  • Unzip and you will find the ..\bin\curl.exe
  • Add ...\bin\ to your path variable for easy global access

Android webview launches browser when calling loadurl

use like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dedline);

    WebView myWebView = (WebView) findViewById(R.id.webView1);
    myWebView.setWebViewClient(new WebViewClient());
    myWebView.loadUrl("https://google.com");
}

Take nth column in a text file

If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr and/or cut or something. ...

(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)

...
while read line ; 
do 
    lineCols=( $line ) ;
    echo "${lineCols[0]}"
    echo "${lineCols[1]}"
done < $myFQFileToRead ; 
...

Service vs IntentService in the Android platform

If someone can show me an example of something that can be done with an IntentService and can not be done with a Service and the other way around.

By definition, that is impossible. IntentService is a subclass of Service, written in Java. Hence, anything an IntentService does, a Service could do, by including the relevant bits of code that IntentService uses.

Starting a service with its own thread is like starting an IntentService. Is it not?

The three primary features of an IntentService are:

  • the background thread

  • the automatic queuing of Intents delivered to onStartCommand(), so if one Intent is being processed by onHandleIntent() on the background thread, other commands queue up waiting their turn

  • the automatic shutdown of the IntentService, via a call to stopSelf(), once the queue is empty

Any and all of that could be implemented by a Service without extending IntentService.

How do I check whether input string contains any spaces?

You can use regex “\\s”

Example program to count number of spaces (Java 9 and above)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

    Pattern pattern = Pattern.compile("\\s", Pattern.CASE_INSENSITIVE);        
    Matcher matcher = pattern.matcher("stackoverflow is a good place to get all my answers");        

    long matchCount = matcher.results().count();   
 
    if(matchCount > 0) 
      System.out.println("Match found " + matchCount + " times.");           
    else 
      System.out.println("Match not found");        
  }
}

For Java 8 and below you can use matcher.find() in a while loop and increment the count. For example,

int count = 0;
while (matcher.find()) {
  count ++;
}

Open and write data to text file using Bash?

I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.

#!/bin/bash

# Open file descriptor (fd) 3 for read/write on a text file.
exec 3<> poem.txt

    # Let's print some text to fd 3
    echo "Roses are red" >&3
    echo "Violets are blue" >&3
    echo "Poems are cute" >&3
    echo "And so are you" >&3

# Close fd 3
exec 3>&-

Then cat the file on terminal

$ cat poem.txt
Roses are red
Violets are blue
Poems are cute
And so are you

This example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd's then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in /proc/sys/file-max or /proc/sys/fs/file-max but using any fd above 9 is dangerous as it could conflict with fd's used by the shell internally. So don't bother and only use fd's 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways :)

Anyhow, fd's can be used in a lot of interesting ways.

Why use String.Format?

String.Format adds many options in addition to the concatenation operators, including the ability to specify the specific format of each item added into the string.

For details on what is possible, I'd recommend reading the section on MSDN titled Composite Formatting. It explains the advantage of String.Format (as well as xxx.WriteLine and other methods that support composite formatting) over normal concatenation operators.

Flutter plugin not installed error;. When running flutter doctor

I had the same issue but fixed just after running these commands:

flutter channel dev
flutter doctor
flutter channel master
flutter doctor

Best way to format integer as string with leading zeros?

You have at least two options:

  • str.zfill: lambda n, cnt=2: str(n).zfill(cnt)
  • % formatting: lambda n, cnt=2: "%0*d" % (cnt, n)

If on Python >2.5, see a third option in clorz's answer.

[ :Unexpected operator in shell programming

There is no mistake in your bash script. But you are executing it with sh which has a less extensive syntax ;)

So, run bash ./choose.sh instead :)

split python source code into multiple files?

Sure!

#file  -- test.py --
myvar = 42
def test_func():
    print("Hello!")

Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH) Note that the current directory is always in PYTHONPATH, so if use_test is being run from the same directory where test.py lives, you're all set:

#file -- use_test.py --
import test
test.test_func()  #prints "Hello!"
print (test.myvar)  #prints 42

from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar)     #Exception (NameError)

from test import *
test_func() #prints "Hello"
print(myvar)      #prints 42

There's a lot more you can do than just that through the use of special __init__.py files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Python != operation vs "is not"

== is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their __eq__ or __cmp__ methods.)

is is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the is operation.

You use is (and is not) for singletons, like None, where you don't care about objects that might want to pretend to be None or where you want to protect against objects breaking when being compared against None.

How to track down access violation "at address 00000000"

It's probably because you are directly or indirectly through a library call accessing a NULL pointer. In this particular case, it looks like you've jumped to a NULL address, which is a b bit hairier.

In my experience, the easiest way to track these down are to run it with a debugger, and dump a stack trace.

Alternatively, you can do it "by hand" and add lots of logging until you can track down exactly which function (and possibly LOC) this violation occurred in.

Take a look at Stack Tracer, which might help you improve your debugging.

Get the records of last month in SQL server

A simple query which works for me is:

select * from table where DATEADD(month, 1,DATEFIELD) >= getdate()

How to detect current state within directive

If you are using ui-router, try $state.is();

You can use it like so:

$state.is('stateName');

Per the documentation:

$state.is ... similar to $state.includes, but only checks for the full state name.

Why do access tokens expire?

A couple of scenarios might help illustrate the purpose of access and refresh tokens and the engineering trade-offs in designing an oauth2 (or any other auth) system:

Web app scenario

In the web app scenario you have a couple of options:

  1. if you have your own session management, store both the access_token and refresh_token against your session id in session state on your session state service. When a page is requested by the user that requires you to access the resource use the access_token and if the access_token has expired use the refresh_token to get the new one.

Let's imagine that someone manages to hijack your session. The only thing that is possible is to request your pages.

  1. if you don't have session management, put the access_token in a cookie and use that as a session. Then, whenever the user requests pages from your web server send up the access_token. Your app server could refresh the access_token if need be.

Comparing 1 and 2:

In 1, access_token and refresh_token only travel over the wire on the way between the authorzation server (google in your case) and your app server. This would be done on a secure channel. A hacker could hijack the session but they would only be able to interact with your web app. In 2, the hacker could take the access_token away and form their own requests to the resources that the user has granted access to. Even if the hacker gets a hold of the access_token they will only have a short window in which they can access the resources.

Either way the refresh_token and clientid/secret are only known to the server making it impossible from the web browser to obtain long term access.

Let's imagine you are implementing oauth2 and set a long timeout on the access token:

In 1) There's not much difference here between a short and long access token since it's hidden in the app server. In 2) someone could get the access_token in the browser and then use it to directly access the user's resources for a long time.

Mobile scenario

On the mobile, there are a couple of scenarios that I know of:

  1. Store clientid/secret on the device and have the device orchestrate obtaining access to the user's resources.

  2. Use a backend app server to hold the clientid/secret and have it do the orchestration. Use the access_token as a kind of session key and pass it between the client and the app server.

Comparing 1 and 2

In 1) Once you have clientid/secret on the device they aren't secret any more. Anyone can decompile and then start acting as though they are you, with the permission of the user of course. The access_token and refresh_token are also in memory and could be accessed on a compromised device which means someone could act as your app without the user giving their credentials. In this scenario the length of the access_token makes no difference to the hackability since refresh_token is in the same place as access_token. In 2) the clientid/secret nor the refresh token are compromised. Here the length of the access_token expiry determines how long a hacker could access the users resources, should they get hold of it.

Expiry lengths

Here it depends upon what you're securing with your auth system as to how long your access_token expiry should be. If it's something particularly valuable to the user it should be short. Something less valuable, it can be longer.

Some people like google don't expire the refresh_token. Some like stackflow do. The decision on the expiry is a trade-off between user ease and security. The length of the refresh token is related to the user return length, i.e. set the refresh to how often the user returns to your app. If the refresh token doesn't expire the only way they are revoked is with an explicit revoke. Normally, a log on wouldn't revoke.

Hope that rather length post is useful.

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

One convenient trick to entering elapsed times into Excel is to have two zeros and a colon before the number of minutes, details follow. For copy and paste operations into Excel without have to worry about formatting at all one can use the format 00:XX:XX where XX are two digits totaling < 60. In that case, Excel will echo 0:XX:XX in the cell contents displayed and store the data as 12:XX:XX AM. If one pastes data in a 00:XXX:XX format into Excel, or 00:XX:XX where either XX > 59 this will be converted into a fraction of a day.

For example, 00:121:12 becomes 0.0841666666666667, which if multiplied by the number of seconds in a day, 86,400, becomes 7272 s. Next, 00:21:12 would by default show 0:21:12 stored as 12:21:12 AM. Finally, 00:21:60 becomes 0.0152777777777778, also a fraction of a day.

This suggestion is made merely to avoid having to worry about specific formatting in Excel, and letting the program worry about it. Note, for Excel data internally formatted as 12:XX:XX AM one can only use certain Excel commands, for example, one can take an average. However, subtraction will only work when the result is a positive number. Such that converting times into seconds, fractions of a day, or other real number is suggested for access to more complete arithmetic operation coverage.

For example, if one has a column of mixed time formats, or times that are negative and will not display, if one changes the number formatting to General, all the times will be converted to fractions of a day.

Parse (split) a string in C++ using string delimiter (standard C++)

You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token.

Example:

std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
  • The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found.

  • The substr(size_t pos = 0, size_t n = npos) function returns a substring of the object, starting at position pos and of length npos.


If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length());):

s.erase(0, s.find(delimiter) + delimiter.length());

This way you can easily loop to get each token.

Complete Example

std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";

size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
    token = s.substr(0, pos);
    std::cout << token << std::endl;
    s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;

Output:

scott
tiger
mushroom

What are DDL and DML?

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.

Examples: SELECT, UPDATE, INSERT statements


DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.

Examples: CREATE, ALTER, DROP statements

Visit this site for more info: http://blog.sqlauthority.com/2008/01/15/sql-server-what-is-dml-ddl-dcl-and-tcl-introduction-and-examples/

Apple Cover-flow effect using jQuery or other library?

jCoverflip was just released and is very customizable.

Array Length in Java

Arrays are allocated memory at compile time in java, so they are static, the elements not explicitly set or modified are set with the default values. You could use some code like this, though it is not recommended as it does not count default values, even if you explicitly initialize them that way, it is also likely to cause bugs down the line. As others said, when looking for the actual size, ".length" must be used instead of ".length()".

public int logicalArrayLength(type[] passedArray) {
    int count = 0;
    for (int i = 0; i < passedArray.length; i++) {
        if (passedArray[i] != defaultValue) {
            count++;
        }
    }
    return count;
}

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

JavaScript listener, "keypress" doesn't detect backspace?

My numeric control:

function CheckNumeric(event) {
    var _key = (window.Event) ? event.which : event.keyCode;
    if (_key > 95 && _key < 106) {
        return true;
    }
    else if (_key > 47 && _key < 58) {
        return true;
    }
    else {
        return false;
    }
}

<input type="text" onkeydown="return CheckNumerick(event);" />

try it

BackSpace key code is 8

Android Studio - Unable to find valid certification path to requested target

Even though this question is very old, many must be facing the same issue, so I would like to state how I fixed this.

The problem is classpath 'com.android.tools.build:gradle:0.13.2' By above line in build.gradle you are asking it to find a particular version of gradle but this version is not there in your machine. The best it to change the above line to

classpath 'com.android.tools.build:gradle:+'

C# - Making a Process.Start wait until the process has start-up

Here an implementation that uses a System.Threading.Timer. Maybe a bit much for its purpose.

    private static bool StartProcess(string filePath, string processName)
    {
        if (!File.Exists(filePath))
            throw new InvalidOperationException($"Unknown filepath: {(string.IsNullOrEmpty(filePath) ? "EMPTY PATH" : filePath)}");

        var isRunning = false;

        using (var resetEvent = new ManualResetEvent(false))
        {

            void Callback(object state)
            {
                if (!IsProcessActive(processName)) return;
                isRunning = true;
                // ReSharper disable once AccessToDisposedClosure
                resetEvent.Set();
            }

            using (new Timer(Callback, null, 0, TimeSpan.FromSeconds(0.5).Milliseconds))
            {
                Process.Start(filePath);
                WaitHandle.WaitAny(new WaitHandle[] { resetEvent }, TimeSpan.FromSeconds(9));
            }
        }

        return isRunning;
    }

    private static bool StopProcess(string processName)
    {
        if (!IsProcessActive(processName)) return true;

        var isRunning = true;

        using (var resetEvent = new ManualResetEvent(false))
        {

            void Callback(object state)
            {
                if (IsProcessActive(processName)) return;
                isRunning = false;
                // ReSharper disable once AccessToDisposedClosure
                resetEvent.Set();
            }

            using (new Timer(Callback, null, 0, TimeSpan.FromSeconds(0.5).Milliseconds))
            {
                foreach (var process in Process.GetProcessesByName(processName))
                    process.Kill();
                WaitHandle.WaitAny(new WaitHandle[] { resetEvent }, TimeSpan.FromSeconds(9));
            }
        }

        return isRunning;
    }

    private static bool IsProcessActive(string processName)
    {
        return Process.GetProcessesByName(processName).Any();
    }

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

Error in strings.xml file in Android

1. for error: unescaped apostrophe in string

what I found is that AAPT2 tool points to wrong row in xml, sometimes. So you should correct whole strings.xml file

In Android Studio, in problem file use :

Edit->find->replace

Then write in first field \' (or \&,>,\<,\")
in second put '(or &,>,<,")
then replace each if needed.(or "reptlace all" in case with ')
Then in first field again put '(or &,>,<,")
and in second write \'
then replace each if needed.(or "replace all" in case with ')

2. for other problematic symbols
I use to comment each next half part +rebuild until i won't find the wrong sign.

E.g. an escaped word "\update" unexpectedly drops such error :)

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

After hours of analysis reading tons of logs and internet, finally found problem.

If you use docker and php 7.4 (my case) you probably get error because default security level in OpenSSL it too high for wsdl cert. Even if you disable verify and allow self-signed in SoapClient options.

You need lower seclevel in /etc/ssl/openssl.cnf from DEFAULT@SECLEVEL=2 to

DEFAULT@SECLEVEL=1

Or just add into Dockerfile

RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf

Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876


You can verify it by run on container

curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl

Before that change I got error:

SSL routines:tls_process_ske_dhe:dh key too small

CSS '>' selector; what is it?

It declares parent reference, look at this page for definition:

http://www.w3.org/TR/CSS2/selector.html#child-selectors

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

The one major thing I think people are leaving out is that Build and Clean are both tasks that are performed based on Visual Studio's knowledge of your Project/Solution. I see a lot of complaining that Clean doesn't work or leaves leftover files or is not trustworthy, when in fact, the reasons you say it isn't trustworthy actually makes it more trustworthy.

Clean will only remove (clean) files and/or directories that Visual Studio or the compiler themselves have in fact created. If you copy your own files or files/folder structures get created from an outside tool or source, then Visual Studio doesn't "know they exist" and therefore, should not touch them.

Can you imagine if the Clean operation basically performed a "del *.*" ? This could be catastrophic.

Build performs a compile on changed or necessary projects.

Rebuild performs a compile regardless of change or what's necessary.

Clean removes files/folders it has created in the past, but leaves anything that it didn't have anything to do with, initially.

I hope this elaborates a bit and helps.

How to create a video from images with FFmpeg?

-pattern_type glob

This great option makes it easier to select the images in many cases.

Slideshow video with one image per second

ffmpeg -framerate 1 -pattern_type glob -i '*.png' \
  -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4

Add some music to it, cutoff when the presumably longer audio when the images end:

ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
  -c:a copy -shortest -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4

Here are two demos on YouTube:

Be a hippie and use the Theora patent-unencumbered video format:

ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
  -c:a copy -shortest -c:v libtheora -r 30 -pix_fmt yuv420p out.ogg

Your images should of course be sorted alphabetically, typically as:

0001-first-thing.jpg
0002-second-thing.jpg
0003-and-third.jpg

and so on.

I would also first ensure that all images to be used have the same aspect ratio, possibly by cropping them with imagemagick or nomacs beforehand, so that ffmpeg will not have to make hard decisions. In particular, the width has to be divisible by 2, otherwise conversion fails with: "width not divisible by 2".

Normal speed video with one image per frame at 30 FPS

ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
  -c:v libx264 -pix_fmt yuv420p out.mp4

Here's what it looks like:

GIF generated with: https://askubuntu.com/questions/648603/how-to-create-an-animated-gif-from-mp4-video-via-command-line/837574#837574

Add some audio to it:

ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
  -i audio.ogg -c:a copy -shortest -c:v libx264 -pix_fmt yuv420p out.mp4

Result: https://www.youtube.com/watch?v=HG7c7lldhM4

These are the test media I've used:a

wget -O opengl-rotating-triangle.zip https://github.com/cirosantilli/media/blob/master/opengl-rotating-triangle.zip?raw=true
unzip opengl-rotating-triangle.zip
cd opengl-rotating-triangle
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg

Images generated with: How to use GLUT/OpenGL to render to a file?

It is cool to observe how much the video compresses the image sequence way better than ZIP as it is able to compress across frames with specialized algorithms:

  • opengl-rotating-triangle.mp4: 340K
  • opengl-rotating-triangle.zip: 7.3M

Convert one music file to a video with a fixed image for YouTube upload

Answered at: https://superuser.com/questions/700419/how-to-convert-mp3-to-youtube-allowed-video-format/1472572#1472572

Full realistic slideshow case study setup step by step

There's a bit more to creating slideshows than running a single ffmpeg command, so here goes a more interesting detailed example inspired by this timeline.

Get the input media:

mkdir -p orig
cd orig
wget -O 1.png https://upload.wikimedia.org/wikipedia/commons/2/22/Australopithecus_afarensis.png
wget -O 2.jpg https://upload.wikimedia.org/wikipedia/commons/6/61/Homo_habilis-2.JPG
wget -O 3.jpg https://upload.wikimedia.org/wikipedia/commons/c/cb/Homo_erectus_new.JPG
wget -O 4.png https://upload.wikimedia.org/wikipedia/commons/1/1f/Homo_heidelbergensis_-_forensic_facial_reconstruction-crop.png
wget -O 5.jpg https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Sabaa_Nissan_Militiaman.jpg/450px-Sabaa_Nissan_Militiaman.jpg
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg
cd ..

# Convert all to PNG for consistency.
# https://unix.stackexchange.com/questions/29869/converting-multiple-image-files-from-jpeg-to-pdf-format
# Hardlink the ones that are already PNG.
mkdir -p png
mogrify -format png -path png orig/*.jpg
ln -P orig/*.png png

Now we have a quick look at all image sizes to decide on the final aspect ratio:

identify png/*

which outputs:

png/1.png PNG 557x495 557x495+0+0 8-bit sRGB 653KB 0.000u 0:00.000
png/2.png PNG 664x800 664x800+0+0 8-bit sRGB 853KB 0.000u 0:00.000
png/3.png PNG 544x680 544x680+0+0 8-bit sRGB 442KB 0.000u 0:00.000
png/4.png PNG 207x238 207x238+0+0 8-bit sRGB 76.8KB 0.000u 0:00.000
png/5.png PNG 450x600 450x600+0+0 8-bit sRGB 627KB 0.000u 0:00.000

so the classic 480p (640x480 == 4/3) aspect ratio seems appropriate.

Do one conversion with minimal resizing to make widths even (TODO automate for any width, here I just manually looked at identify output and reduced width and height by one):

mkdir -p raw
convert png/1.png -resize 556x494 raw/1.png
ln -P png/2.png png/3.png png/4.png png/5.png raw
ffmpeg -framerate 1 -pattern_type glob -i 'raw/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p raw.mp4

This produces terrible output, because as seen from:

ffprobe raw.mp4

ffmpeg just takes the size of the first image, 556x494, and then converts all others to that exact size, breaking their aspect ratio.

Now let's convert the images to the target 480p aspect ratio automatically by cropping as per ImageMagick: how to minimally crop an image to a certain aspect ratio?

mkdir -p auto
mogrify -path auto -geometry 640x480^ -gravity center -crop 640x480+0+0 png/*.png
ffmpeg -framerate 1 -pattern_type glob -i 'auto/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p auto.mp4

So now, the aspect ratio is good, but inevitably some cropping had to be done, which kind of cut up interesting parts of the images.

The other option is to pad with black background to have the same aspect ratio as shown at: Resize to fit in a box and set background to black on "empty" part

mkdir -p black
ffmpeg -framerate 1 -pattern_type glob -i 'black/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p black.mp4

Generally speaking though, you will ideally be able to select images with the same or similar aspect ratios to avoid those problems in the first place.

About the CLI options

Note however that despite the name, -glob this is not as general as shell Glob patters, e.g.: -i '*' fails: https://trac.ffmpeg.org/ticket/3620 (apparently because filetype is deduced from extension).

-r 30 makes the -framerate 1 video 30 FPS to overcome bugs in players like VLC for low framerates: VLC freezes for low 1 FPS video created from images with ffmpeg Therefore it repeats each frame 30 times to keep the desired 1 image per second effect.

Next steps

You will also want to:

TODO: learn to cut and concatenate multiple audio files into the video without intermediate files, I'm pretty sure it's possible:

Tested on

ffmpeg 3.4.4, vlc 3.0.3, Ubuntu 18.04.

Bibliography

How to get only filenames within a directory using c#?

You could use the DirectoryInfo and FileInfo classes.

//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");

//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;

Convert np.array of type float64 to type uint8 scaling values

A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2], the code right now would scale that to have intensities of [0, 128, 255]. You want these to remain small after converting to np.uint8.

Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type (dtype) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value.

So with the above, do the following modifications to your code:

import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

Note that I've additionally converted the image into np.float64 in case the incoming data type is not so and to maintain floating-point precision when doing the division.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

Try this it works!

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M3</version>
                <configuration>
                <testFailureIgnore>true</testFailureIgnore>
                <shutdown>kill</shutdown> <!-- Use it if required-->
                </configuration>
            </plugin>

How to select all the columns of a table except one column?

  1. Generate your select query with any good autocomplete editor of your database.
  2. copy and paste your select query in a reserved method (function) and return its ResultSet to your main program or do your stuff in the same method.
  3. call this method each time whenever you require

How to redirect output of an already running process

Dupx

Dupx is a simple *nix utility to redirect standard output/input/error of an already running process.

Motivation

I've often found myself in a situation where a process I started on a remote system via SSH takes much longer than I had anticipated. I need to break the SSH connection, but if I do so, the process will die if it tries to write something on stdout/error of a broken pipe. I wish I could suspend the process with ^Z and then do a

bg %1 >/tmp/stdout 2>/tmp/stderr 

Unfortunately this will not work (in shells I know).

http://www.isi.edu/~yuri/dupx/

MySQL: how to get the difference between two timestamps in seconds

You could use the TIMEDIFF() and the TIME_TO_SEC() functions as follows:

SELECT TIME_TO_SEC(TIMEDIFF('2010-08-20 12:01:00', '2010-08-20 12:00:00')) diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

You could also use the UNIX_TIMESTAMP() function as @Amber suggested in an other answer:

SELECT UNIX_TIMESTAMP('2010-08-20 12:01:00') - 
       UNIX_TIMESTAMP('2010-08-20 12:00:00') diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

If you are using the TIMESTAMP data type, I guess that the UNIX_TIMESTAMP() solution would be slightly faster, since TIMESTAMP values are already stored as an integer representing the number of seconds since the epoch (Source). Quoting the docs:

When UNIX_TIMESTAMP() is used on a TIMESTAMP column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.

Keep in mind that TIMEDIFF() return data type of TIME. TIME values may range from '-838:59:59' to '838:59:59' (roughly 34.96 days)

jQuery - simple input validation - "empty" and "not empty"

You could do this

$("#input").blur(function(){
    if($(this).val() == ''){
        alert('empty'); 
    }
});

http://jsfiddle.net/jasongennaro/Y5P9k/1/

When the input has lost focus that is .blur(), then check the value of the #input.

If it is empty == '' then trigger the alert.

Jest spyOn function called

You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const instance = app.instance()
    const spy = jest.spyOn(instance, 'myClickFunc')

    instance.forceUpdate();    

    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

Remove empty elements from an array in Javascript

Another way to do it is to take advantage of the length property of the array : pack the non-null items on the 'left' of the array, then reduce the length. It is an in-place algorithm -does not allocates memory, too bad for the garbage collector-, and it has very good best/average/worst case behaviour.

This solution, compared to others here, is between 2 to 50 times faster on Chrome, and 5 to 50 times faster on Firefox, as you might see here : http://jsperf.com/remove-null-items-from-array

The code below adds the non-enumerable 'removeNull' method to the Array, which returns 'this' for daisy-chaining :

var removeNull = function() {
    var nullCount = 0           ;
    var length    = this.length ;
    for (var i=0, len=this.length; i<len; i++) { if (!this[i]) {nullCount++} }
    // no item is null
    if (!nullCount) { return this}
    // all items are null
    if (nullCount == length) { this.length = 0; return this }
    // mix of null // non-null
    var idest=0, isrc=length-1;
    length -= nullCount ;                
    while (true) {
         // find a non null (source) slot on the right
         while (!this[isrc])  { isrc--; nullCount--; } 
         if    (!nullCount) { break }       // break if found all null
         // find one null slot on the left (destination)
         while ( this[idest]) { idest++  }  
         // perform copy
         this[idest]=this[isrc];
         if (!(--nullCount)) {break}
         idest++;  isrc --; 
    }
    this.length=length; 
    return this;
};  

Object.defineProperty(Array.prototype, 'removeNull', 
                { value : removeNull, writable : true, configurable : true } ) ;

A Space between Inline-Block List Items

Solution:

ul {
    font-size: 0;
}

ul li {
    font-size: 14px;
    display: inline-block;
}

You must set parent font size to 0

Directly export a query to CSV using SQL Developer

After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..

How to change the color of a SwitchCompat from AppCompat library

To have greater control of the track color (no API controlled alpha changes), I extended SwitchCompat and style the elements programmatically:

    public class CustomizedSwitch extends SwitchCompat {

    public CustomizedSwitch(Context context) {
        super(context);
        initialize(context);
    }

    public CustomizedSwitch(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context);
    }

    public CustomizedSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    public void initialize(Context context) {
        // DisplayMeasurementConverter is just a utility to convert from dp to px and vice versa
        DisplayMeasurementConverter displayMeasurementConverter = new DisplayMeasurementConverter(context);
        // Sets the width of the switch
        this.setSwitchMinWidth(displayMeasurementConverter.dpToPx((int) getResources().getDimension(R.dimen.tp_toggle_width)));
        // Setting up my colors
        int mediumGreen = ContextCompat.getColor(context, R.color.medium_green);
        int mediumGrey = ContextCompat.getColor(context, R.color.medium_grey);
        int alphaMediumGreen = Color.argb(127, Color.red(mediumGreen), Color.green(mediumGreen), Color.blue(mediumGreen));
        int alphaMediumGrey = Color.argb(127, Color.red(mediumGrey), Color.green(mediumGrey), Color.blue(mediumGrey));
        // Sets the tints for the thumb in different states
        DrawableCompat.setTintList(this.getThumbDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        mediumGreen,
                        ContextCompat.getColor(getContext(), R.color.light_grey)
                }));
        // Sets the tints for the track in different states
        DrawableCompat.setTintList(this.getTrackDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        alphaMediumGreen,
                        alphaMediumGrey
                }));
    }
}

Whenever I want to use the CustomizedSwitch, I just add one to my xml file.

LDAP filter for blank (empty) attribute

This article http://technet.microsoft.com/en-us/library/ee198810.aspx led me to the solution. The only change is the placement of the exclamation mark.

(!manager=*)

It seems to be working just as wanted.

django templates: include and extends

This should do the trick for you: put include tag inside of a block section.

page1.html:

{% extends "base1.html" %}

{% block foo %}
   {% include "commondata.html" %}
{% endblock %}

page2.html:

{% extends "base2.html" %}

{% block bar %}
   {% include "commondata.html" %}
{% endblock %}

error while loading shared libraries: libncurses.so.5:

To install ncurses-compat-libs on Fedora 24 helped me on this issue (unable to start adb error while loading shared libraries: libncurses.so.5)

spring data jpa @query and pageable

Considering that the UrnMapping class is mapped to the internal_uddi table, I would suggest this:

@Repository
public interface UrnMappingRepository extends JpaRepository<UrnMapping, Long> {

    @Query(value = "select iu from UrnMapping iu where iu.urn like %:text% or iu.contact like %:text%")
    Page<UrnMapping> fullTextSearch(@Param("text") String text, Pageable pageable);
}

Please note that you might have to turn off native queries with dynamic requests.

How to debug an apache virtual host configuration?

I recently had some issues with a VirtualHost. I used a2ensite to enable a host but before running a restart (which would kill the server on fail) I ran

apache2ctl -S

Which gives you some info about what's going on with your virtual hosts. It's not perfect, but it helps.

Could not open input file: artisan

After installing composer, you need to create the project:

composer create-project laravel/laravel /path/to/tour/project

You can see the documentation, for your php version the lastest Laravel you can install is 5.0.

Now days here is the lastest version and require > php7.0. Here is the documentation.

How to merge specific files from Git branches

What I've done is a bit manual, but I:

  1. Merged the branches normally; Reverted the merge with revert;
  2. Checked out all my files to HEAD~1, that is, their state in the merge commit;
  3. Rebased my commits to hide this hackery from the commit history.

Ugly? Yes. Easy to remember? Also yes.

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Bootstrap 3 - Responsive mp4-video

Simply add class="img-responsive" to the video tag. I'm doing this on a current project, and it works. It doesn't need to be wrapped in anything.

<video class="img-responsive" src="file.mp4" autoplay loop/>

pandas: to_numeric for multiple columns

You can use:

print df.columns[5:]
Index([u'2004', u'2005', u'2006', u'2007', u'2008', u'2009', u'2010', u'2011',
       u'2012', u'2013', u'2014'],
      dtype='object')

for col in  df.columns[5:]:
    df[col] = pd.to_numeric(df[col], errors='coerce')

print df
       GeoName      ComponentName  IndustryId  IndustryClassification  \
37926  Alabama  Real GDP by state           9                     213   
37951  Alabama  Real GDP by state          34                      42   
37932  Alabama  Real GDP by state          15                     327   

                                      Description  2004   2005   2006   2007  \
37926               Support activities for mining    99     98    117    117   
37951                            Wholesale  trade  9898  10613  10952  11034   
37932  Nonmetallic mineral products manufacturing   980    968    940   1084   

        2008  2009  2010  2011  2012  2013     2014  
37926    115    87    96    95   103   102      NaN  
37951  11075  9722  9765  9703  9600  9884  10199.0  
37932    861   724   714   701   589   641      NaN  

Another solution with filter:

print df.filter(like='20')
       2004   2005   2006   2007   2008  2009  2010  2011  2012  2013   2014
37926    99     98    117    117    115    87    96    95   103   102   (NA)
37951  9898  10613  10952  11034  11075  9722  9765  9703  9600  9884  10199
37932   980    968    940   1084    861   724   714   701   589   641   (NA)

for col in  df.filter(like='20').columns:
    df[col] = pd.to_numeric(df[col], errors='coerce')
print df
       GeoName      ComponentName  IndustryId  IndustryClassification  \
37926  Alabama  Real GDP by state           9                     213   
37951  Alabama  Real GDP by state          34                      42   
37932  Alabama  Real GDP by state          15                     327   

                                      Description  2004   2005   2006   2007  \
37926               Support activities for mining    99     98    117    117   
37951                            Wholesale  trade  9898  10613  10952  11034   
37932  Nonmetallic mineral products manufacturing   980    968    940   1084   

        2008  2009  2010  2011  2012  2013     2014  
37926    115    87    96    95   103   102      NaN  
37951  11075  9722  9765  9703  9600  9884  10199.0  
37932    861   724   714   701   589   641      NaN  

How to call a function from a string stored in a variable?

Dynamic function names and namespaces

Just to add a point about dynamic function names when using namespaces.

If you're using namespaces, the following won't work except if your function is in the global namespace:

namespace greetings;

function hello()
{
    // do something
}

$myvar = "hello";
$myvar(); // interpreted as "\hello();"

What to do?

You have to use call_user_func() instead:

// if hello() is in the current namespace
call_user_func(__NAMESPACE__.'\\'.$myvar);

// if hello() is in another namespace
call_user_func('mynamespace\\'.$myvar);

How to get image height and width using java?

This is a rewrite of the great post by @Kay, which throws IOException and provides an early exit:

/**
 * Gets image dimensions for given file 
 * @param imgFile image file
 * @return dimensions of image
 * @throws IOException if the file is not a known image
 */
public static Dimension getImageDimension(File imgFile) throws IOException {
  int pos = imgFile.getName().lastIndexOf(".");
  if (pos == -1)
    throw new IOException("No extension for file: " + imgFile.getAbsolutePath());
  String suffix = imgFile.getName().substring(pos + 1);
  Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
  while(iter.hasNext()) {
    ImageReader reader = iter.next();
    try {
      ImageInputStream stream = new FileImageInputStream(imgFile);
      reader.setInput(stream);
      int width = reader.getWidth(reader.getMinIndex());
      int height = reader.getHeight(reader.getMinIndex());
      return new Dimension(width, height);
    } catch (IOException e) {
      log.warn("Error reading: " + imgFile.getAbsolutePath(), e);
    } finally {
      reader.dispose();
    }
  }

  throw new IOException("Not a known image file: " + imgFile.getAbsolutePath());
}

I guess my rep is not high enough for my input to be considered worthy as a reply.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

You can also check the local changelog to verify whether or not OpenSSL is patched against the vulnerability with the following command:

rpm -q --changelog openssl | grep CVE-2014-0224

If a result is not returned, then you must patch OpenSSL.

http://www.liquidweb.com/kb/update-and-patch-openssl-for-the-ccs-injection-vulnerability/

Parsing a CSV file using NodeJS

fs = require('fs');
fs.readFile('FILENAME WITH PATH','utf8', function(err,content){
if(err){
    console.log('error occured ' +JSON.stringify(err));
 }
 console.log('Fileconetent are ' + JSON.stringify(content));
})

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

Complementing @Bob Jarvis and @dmikam answer, Postgres don't perform a good plan when you don't use LATERAL, below a simulation, in both cases the query data results are the same, but the cost are very different

Table structure

CREATE TABLE ITEMS (
    N INTEGER NOT NULL,
    S TEXT NOT NULL
);

INSERT INTO ITEMS
  SELECT
    (random()*1000000)::integer AS n,
    md5(random()::text) AS s
  FROM
    generate_series(1,1000000);

CREATE INDEX N_INDEX ON ITEMS(N);

Performing JOIN with GROUP BY in subquery without LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    GROUP BY N
) I2 ON I2.N = I.N
WHERE I.N IN (243477, 997947);

The results

Merge Join  (cost=0.87..637500.40 rows=23 width=37)
  Merge Cond: (i.n = items.n)
  ->  Index Scan using n_index on items i  (cost=0.43..101.28 rows=23 width=37)
        Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..626631.11 rows=861418 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..593016.93 rows=10000000 width=4)

Using LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN LATERAL (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    WHERE N = I.N
    GROUP BY N
) I2 ON 1=1 --I2.N = I.N
WHERE I.N IN (243477, 997947);

Results

Nested Loop  (cost=9.49..1319.97 rows=276 width=37)
  ->  Bitmap Heap Scan on items i  (cost=9.06..100.20 rows=23 width=37)
        Recheck Cond: (n = ANY ('{243477,997947}'::integer[]))
        ->  Bitmap Index Scan on n_index  (cost=0.00..9.05 rows=23 width=0)
              Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..52.79 rows=12 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..52.64 rows=12 width=4)
              Index Cond: (n = i.n)

My Postgres version is PostgreSQL 10.3 (Debian 10.3-1.pgdg90+1)

wkhtmltopdf: cannot connect to X server

This solved the issue for me:

sudo apt-get install xvfb
xvfb-run --server-args="-screen 0, 1024x768x24" wkhtmltopdf file1.html file2.pdf

How to throw RuntimeException ("cannot find symbol")

An Exception is an Object like any other in Java. You need to use the new keyword to create a new Exception before you can throw it.

throw new RuntimeException();

Optionally you could also do the following:

RuntimeException e = new RuntimeException();
throw e;

Both code snippets are equivalent.

Link to the tutorials for completeness.

Find an element by class name, from a known parent element

var element = $("#parentDiv .myClassNameOfInterest")

How to Edit a row in the datatable

Try the SetField method:

By passing column object :

table.Rows[rowIndex].SetField(column, value);

By Passing column index :

table.Rows[rowIndex].SetField(0 /*column index*/, value);

By Passing column name as string :

table.Rows[rowIndex].SetField("product_name" /*columnName*/, value);

How to call Makefile from another Makefile?

http://www.gnu.org/software/make/manual/make.html#Recursion

 subsystem:
         cd subdir && $(MAKE)

or, equivalently, this :

 subsystem:
         $(MAKE) -C subdir

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect

    <?php

$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion        = $_POST['seccion'];
$precio         = $_POST['precio'];
$fecha          = $_POST['fecha'];
$importado      = $_POST['importado'];
$paisdeorigen   = $_POST['paisdeorigen'];
try {

  $server = 'mysql: host=localhost; dbname=usuarios';
  $user   = 'root';
  $pass   = '';
  $base   = new PDO($server, $user, $pass);

  $base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $base->query("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $base->exec("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $sql = "
  INSERT INTO productos
  (CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
  VALUES
  (:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
  $result = $base->prepare($sql);
//  se pasan por parametros aqui
  $result->bindParam(':c_art', $codigoarticulo);
  $result->bindParam(':n_art', $nombrearticulo);
  $result->bindParam(':sec', $seccion);
  $result->bindParam(':pre', $precio);
  $result->bindParam(':fecha_art', $fecha);
  $result->bindParam(':import', $importado);
  $result->bindParam(':p_orig', $paisdeorigen);
  $result->execute();
  echo 'Articulo agregado';
} catch (Exception $e) {

  echo 'Error';
  echo $e->getMessage();
} finally {

}

?>

Compute row average in pandas

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

What is Java Servlet?

A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide.

Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.

How to comment lines in rails html.erb files?

This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


  1. CONTIGUOUS NON-PRINTING Ruby Code

    • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

    • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

    • DETAILS:

      Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

        <%# if flash[:myErrors] %>
          <%# if flash[:myErrors].any? %>
            <%# if @post.id.nil? %>
              <%# if @myPost!=-1 %>
                <%# @post = @myPost %>
              <%# else %>
                <%# @post = Post.new %>
              <%# end %>
            <%# end %>
          <%# end %>
        <%# end %>
      

      YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

        <%# 
          if flash[:myErrors] then
            if flash[:myErrors].any? then
              if @post.id.nil? then
                if @myPost!=-1 then
                  @post = @myPost 
                else 
                  @post = Post.new 
                end 
              end 
            end 
          end 
        %>
      

ClassNotFoundException: org.slf4j.LoggerFactory

Try downloading jar from here

You can find, it holds the class you need.

EDIT

Seems like the website has changed its structure. You need to choose which jar file you need for your project.

For slf4j-api jar file for latest version as of now, please visit this link

For slf4j-simple jar file for latest version as of now, please visit this link

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

I also had the error error/constitute.c/ReadImage/453 when trying to convert an eps to a gif with image magick. I tried the solution proposed by sNICkerssss but still had errors (though different from the first one)e error/constitute.c/ReadImage/412 What solved the problem was to put read to other entries

 <policy domain="coder" rights="read" pattern="PS" />
 <policy domain="coder" rights="read" pattern="EPS" />
 <policy domain="coder" rights="read" pattern="PDF" />
 <policy domain="coder" rights="read" pattern="XPS" />
 <policy domain="coder" rights="read|write" pattern="LABEL" />

Cannot download Docker images behind a proxy

To extend Arun's answer, for this to work in CentOS 7, I had to remove the "export" commands. So edit

/etc/sysconfig/docker

And add:

HTTP_PROXY="http://<proxy_host>:<proxy_port>"
HTTPS_PROXY="https://<proxy_host>:<proxy_port>"
http_proxy="${HTTP_PROXY}"
https_proxy="${HTTPS_PROXY}"

Then restart Docker:

sudo service docker restart

The source is this blog post.

Unit testing with Spring Security

I would take a look at Spring's abstract test classes and mock objects which are talked about here. They provide a powerful way of auto-wiring your Spring managed objects making unit and integration testing easier.

Aligning rotated xticklabels with their respective xticks

If you dont want to modify the xtick labels, you can just use:

plt.xticks(rotation=45)

Android SDK manager won't open

I'd encountered the same problem. When running the android.bat I found the solution (if Java is installed in the 'normal' Windows directory, ie 'program files') you need to put quotes surrounding "c:/program files/" etc etc. Otherwise it cannot find java on "C:/program". (me dislikes spaces)

How to access the GET parameters after "?" in Express?

Use req.query, for getting he value in query string parameter in the route. Refer req.query. Say if in a route, http://localhost:3000/?name=satyam you want to get value for name parameter, then your 'Get' route handler will go like this :-

app.get('/', function(req, res){
    console.log(req.query.name);
    res.send('Response send to client::'+req.query.name);

});

extract column value based on another column pandas dataframe

df[df['B']==3]['A'], assuming df is your pandas.DataFrame.

Function overloading in Python: Missing

You don't need function overloading, as you have the *args and **kwargs arguments.

The fact is that function overloading is based on the idea that passing different types you will execute different code. If you have a dynamically typed language like Python, you should not distinguish by type, but you should deal with interfaces and their compliance with the code you write.

For example, if you have code that can handle either an integer, or a list of integers, you can try iterating on it and if you are not able to, then you assume it's an integer and go forward. Of course it could be a float, but as far as the behavior is concerned, if a float and an int appear to be the same, then they can be interchanged.

Can I invoke an instance method on a Ruby module without including it?

Another way to do it if you "own" the module is to use module_function.

module UsefulThings
  def a
    puts "aaay"
  end
  module_function :a

  def b
    puts "beee"
  end
end

def test
  UsefulThings.a
  UsefulThings.b # Fails!  Not a module method
end

test

Force flushing of output to a file while bash script is still running

Buffering of output depends on how your program /homedir/MyScript is implemented. If you find that output is getting buffered, you have to force it in your implementation. For example, use sys.stdout.flush() if it's a python program or use fflush(stdout) if it's a C program.

What's default HTML/CSS link color?

In CSS you can use the color string currentColor inside a link to eg make the border the same color as your default link color:

.example {
    border: 1px solid currentColor;
}

How to show/hide JPanels in a JFrame?

If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.

jpanel1.setVisible(false);

How can I use Oracle SQL developer to run stored procedures?

I am not sure how to see the actual rows/records that come back.

Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.

In SQL Developer, you can execute a procedure that returns a ref cursor as follows

var rc refcursor
exec proc_name(:rc)

After that, if you execute the following, it will show the results from the cursor:

print rc

Allow anonymous authentication for a single folder in web.config?

Use <location> configuration tag, and <allow users="?"/> to allow anonymous only or <allow users="*"/> for all:

<configuration>
   <location path="Path/To/Public/Folder">
      <system.web>
         <authorization>
            <allow users="?"/>
         </authorization>
      </system.web>
   </location>
</configuration>

Twitter Bootstrap Multilevel Dropdown Menu

This example is from http://bootsnipp.com/snippets/featured/multi-level-dropdown-menu-bs3

Works for me in Bootstrap v3.1.1.

HTML

<div class="container">
<div class="row">
    <h2>Multi level dropdown menu in Bootstrap 3</h2>
    <hr>
    <div class="dropdown">
        <a id="dLabel" role="button" data-toggle="dropdown" class="btn btn-primary" data-target="#" href="/page.html">
            Dropdown <span class="caret"></span>
        </a>
        <ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
          <li><a href="#">Some action</a></li>
          <li><a href="#">Some other action</a></li>
          <li class="divider"></li>
          <li class="dropdown-submenu">
            <a tabindex="-1" href="#">Hover me for more options</a>
            <ul class="dropdown-menu">
              <li><a tabindex="-1" href="#">Second level</a></li>
              <li class="dropdown-submenu">
                <a href="#">Even More..</a>
                <ul class="dropdown-menu">
                    <li><a href="#">3rd level</a></li>
                    <li><a href="#">3rd level</a></li>
                </ul>
              </li>
              <li><a href="#">Second level</a></li>
              <li><a href="#">Second level</a></li>
            </ul>
          </li>
        </ul>
    </div>
</div>

CSS

.dropdown-submenu {
position: relative;
}

.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
-webkit-border-radius: 0 6px 6px 6px;
-moz-border-radius: 0 6px 6px;
border-radius: 0 6px 6px 6px;
}

.dropdown-submenu:hover>.dropdown-menu {
display: block;
}

.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #ccc;
margin-top: 5px;
margin-right: -10px;
}

.dropdown-submenu:hover>a:after {
border-left-color: #fff;
}

.dropdown-submenu.pull-left {
float: none;
}

.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
-webkit-border-radius: 6px 0 6px 6px;
-moz-border-radius: 6px 0 6px 6px;
border-radius: 6px 0 6px 6px;
}

Systrace for Windows

strace is available from Cygwin in the cygwin package. You can download it from a Cygwin mirror, for example:

http://mirrors.sonic.net/cygwin/x86_64/release/cygwin/cygwin-2.0.2-1.tar.xz
#      |                      |                              |     |
#      +-----------+----------+                              +--+--+
#                  |                                            |
#               mirror                                       version

strace is one of the few Cygwin programs that does not rely on the Cygwin DLL, so you should be able to just copy strace.exe to where you want and use it.

Proxies with Python 'Requests' module

I have found that urllib has some really good code to pick up the system's proxy settings and they happen to be in the correct form to use directly. You can use this like:

import urllib

...
r = requests.get('http://example.org', proxies=urllib.request.getproxies())

It works really well and urllib knows about getting Mac OS X and Windows settings as well.

How to pass an array within a query string?

A query string carries textual data so there is no option but to explode the array, encode it correctly and pass it in a representational format of your choice:

p1=value1&pN=valueN...
data=[value1,...,valueN]
data={p1:value1,...,pN:valueN}

and then decode it in your server side code.

I want my android application to be only run in portrait mode?

In Android Manifest File, put attribute for your <activity> that android:screenOrientation="portrait"

Component is part of the declaration of 2 modules

In this scenario, create another shared module in that import all the component which is being used in multiple module.

In shared component. declare those component. And then import shared module in appmodule as well as in other module where you want to access. It will work 100% , I did this and got it working.

@NgModule({
    declarations: [HeaderComponent, NavigatorComponent],
    imports: [
        CommonModule, BrowserModule,
        AppRoutingModule,
        BrowserAnimationsModule,
        FormsModule,
    ] 
})
export class SharedmoduleModule { }
const routes: Routes = [
{
    path: 'Parent-child-relationship',
    children: [
         { path: '', component: HeaderComponent },
         { path: '', component: ParrentChildComponent }
    ]
}];
@NgModule({
    declarations: [ParrentChildComponent, HeaderComponent],
    imports: [ RouterModule.forRoot(routes), CommonModule, SharedmoduleModule ],
    exports: [RouterModule]
})
export class TutorialModule {
}
imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    MatInputModule,
    MatButtonModule,
    MatSelectModule,
    MatIconModule,
    SharedmoduleModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Is there a no-duplicate List implementation out there?

You should seriously consider dhiller's answer:

  1. Instead of worrying about adding your objects to a duplicate-less List, add them to a Set (any implementation), which will by nature filter out the duplicates.
  2. When you need to call the method that requires a List, wrap it in a new ArrayList(set) (or a new LinkedList(set), whatever).

I think that the solution you posted with the NoDuplicatesList has some issues, mostly with the contains() method, plus your class does not handle checking for duplicates in the Collection passed to your addAll() method.

Subset data to contain only columns whose names match a condition

You can also use starts_with and dplyr's select() like so:

df <- df %>% dplyr:: select(starts_with("ABC"))

semaphore implementation

Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.

Some of the corrections you must make are:

1) You must make a variable of semaphore type

sem_t semvar;

2) The functions sem_wait(), sem_post() require the semaphore variable but you are passing the semaphore id, which makes no sense.

sem_wait(&semvar);
   //your critical section code
sem_post(&semvar);

3) You are passing the semaphore to sem_wait() and sem_post() without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.

ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
     perror("Semaphore failed to initialize");

Study the semaphore API's from the man page and go through this example.

How to use PHP's password_hash to hash and verify passwords

Using password_hash is the recommended way to store passwords. Don't separate them to DB and files.

Let's say we have the following input:

$password = $_POST['password'];

You first hash the password by doing this:

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

Then see the output:

var_dump($hashed_password);

As you can see it's hashed. (I assume you did those steps).

Now you store this hashed password in your database, ensuring your password column is large enough to hold the hashed value (at least 60 characters or longer). When a user asks to log them in, you check the password input with this hash value in the database, by doing this:

// Query the database for username and password
// ...

if(password_verify($password, $hashed_password)) {
    // If the password inputs matched the hashed password in the database
    // Do something, you know... log them in.
} 

// Else, Redirect them back to the login page.

Official Reference

How do I vertically center an H1 in a div?

This is the jQuery method. Looks like overkill but it calculates the offset.

<html>
<head>
<title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://raw.github.com/dreamerslab/jquery.center/master/jquery.center.js"></script>
    <script type="text/javascript">
        $(function(){

            $('#jquery-center').center();

        });
    </script>

</head>
<body>
    <div id="jquery-center" style="position:absolute;">
       <h1>foo</h1>
    </div>
</body>
</html>

Remove ALL styling/formatting from hyperlinks

As Chris said before me, just an a should override. For example:

a { color:red; }
a:hover { color:blue; }
.nav a { color:green; }

In this instance the .nav a would ALWAYS be green, the :hover wouldn't apply to it.

If there's some other rule affecting it, you COULD use !important, but you shouldn't. It's a bad habit to fall into.

.nav a { color:green !important; } /*I'm a bad person and shouldn't use !important */

Then it'll always be green, irrelevant of any other rule.

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

How would I get everything before a : in a string Python

Using index:

>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'

The index will give you the position of : in string, then you can slice it.

If you want to use regex:

>>> import re
>>> re.match("(.*?):",string).group()
'Username'                       

match matches from the start of the string.

you can also use itertools.takewhile

>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'

How to remove trailing and leading whitespace for user-provided input in a batch file?

I had to create a Function.

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION


set "TextString=    Purple Cows are flying in the Air Tonight         "
echo REM ^^Notice there is whitespace at the start and end of the TextString
echo "!TextString!"
CALL:trimWhiteSpace "!TextString!" OutPutString
echo Resulting Trimmed Text: "!OutPutString!"
echo REM ^^Now there should be no White space at the start or end.

Exit /B

Add this to the bottom of your batch file:

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B


::TRIM FUNCTIONS AREA::
:: USAGE:
:: trimWhiteSpace "!InputText!" OutputText
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: trimWhiteSpace "!InputText!" !OutputText!
:: ^^Because it has a ! around the OutPutText
:: Make Sure to add " around the InputText when running the call.
:: If you don't add the " then it will only accept the first word before a space.
::Example:
::  set "TextString=    Purple Cows are flying in the Air Tonight         "
::  echo REM ^^Notice there is whitespace at the start and end of the TextString
::  echo "!TextString!"
::  CALL:trimWhiteSpace "!TextString!" OutPutString
::  echo Resulting Trimmed Text: "!OutPutString!"
::  echo REM ^^Now there should be no White space at the start or end.

:trimWhiteSpace
set textToTrim=%~1
CALL:trimWhiteSpaceOnTheRight "!textToTrim!" OutPutString
SET textToTrim=!OutPutString!
CALL:trimWhiteSpaceOnTheLeft "!textToTrim!" OutPutString
SET %2=!OutPutString!
GOTO:EOF

:trimWhiteSpaceOnTheRight
set str=%~1
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
SET %2=%str%
GOTO:EOF

:trimWhiteSpaceOnTheLeft
set str=%~1
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
SET %2=%str%
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

How to get POSTed JSON in Flask?

This is the way I would do it and it should be

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.get_json(silent=True)
    # print(content) # Do your processing
    return uuid

With silent=True set, the get_json function will fail silently when trying to retrieve the json body. By default this is set to False. If you are always expecting a json body (not optionally), leave it as silent=False.

Setting force=True will ignore the request.headers.get('Content-Type') == 'application/json' check that flask does for you. By default this is also set to False.

See flask documentation.

I would strongly recommend leaving force=False and make the client send the Content-Type header to make it more explicit.

Hope this helps!

how can I Update top 100 records in sql server

What's even cooler is the fact that you can use an inline Table-Valued Function to select which (and how many via TOP) row(s) to update. That is:

UPDATE MyTable
SET Column1=@Value1
FROM tvfSelectLatestRowOfMyTableMatchingCriteria(@Param1,@Param2,@Param3)

For the table valued function you have something interesting to select the row to update like:

CREATE FUNCTION tvfSelectLatestRowOfMyTableMatchingCriteria
(
    @Param1 INT,
    @Param2 INT,
    @Param3 INT
)
RETURNS TABLE AS RETURN
(
    SELECT TOP(1) MyTable.*
    FROM MyTable
    JOIN MyOtherTable
      ON ...
    JOIN WhoKnowsWhatElse
      ON ...
    WHERE MyTable.SomeColumn=@Param1 AND ...
    ORDER BY MyTable.SomeDate DESC
)

..., and there lies (in my humble opinion) the true power of updating only top selected rows deterministically while at the same time simplifying the syntax of the UPDATE statement.

How to install plugin for Eclipse from .zip

If you are reading this because you are getting error while updating from the "Install new Software" menu, then you need to do this

  1. Go to the location from where you want to update ex. http://update.eclemma.org/
  2. Download everything in the same order just as it is on site (every folder)
  3. Go to "Install new software", but instead of pasting the url of site paste the location of your harddrive where you downloaded the contents

please note: add the suffix file:/// to the location
ex. file:///C:/Users/harry/Downloads/eclox/

Maybe not the best solution but this gets the work done :)

Get names of all keys in the collection

Here is the sample worked in Python: This sample returns the results inline.

from pymongo import MongoClient
from bson.code import Code

mapper = Code("""
    function() {
                  for (var key in this) { emit(key, null); }
               }
""")
reducer = Code("""
    function(key, stuff) { return null; }
""")

distinctThingFields = db.things.map_reduce(mapper, reducer
    , out = {'inline' : 1}
    , full_response = True)
## do something with distinctThingFields['results']

iOS app 'The application could not be verified' only on one device

Just had the same problem and I found out that the issue is with expired certificate. My app was distributed (AdHoc) through firebase and few days ago app was working just fine. Today I've realized that I can't install it because 'The application could not be verified'.

Finally I realized that certificate that I was using for app signing has expired 2 days ago. You need to upload it again and you'll be able to install it.

Effective swapping of elements of an array in Java

Try this:

    int lowIndex = 0;
    int highIndex = elements.length-1;

    while(lowIndex < highIndex) {
        T lowVal = elements[lowIndex];
        T highVal = elements[highIndex];
        elements[lowIndex] = highVal;
        elements[highIndex] = lowVal;

        lowIndex += 1;
        highIndex -=1;
    }

PHP find difference between two datetimes

The code below will show difference for found values only, i.e., if years = 0, then it will not show years.


$diffs = [
    'years' => 'y',
    'months' => 'm',
    'days' => 'd',
    'hours' => 'h',
    'minutes' => 'i',
    'seconds' => 's'
];

$interval = $timeout->diff($timein);
$diffArr = [];
foreach ($diffs as $k => $v) {
    $d = $interval->format('%' . $v);
    if ($d > 0) {
        $diffArr[] = $d . ' ' . $k;
    }
}    
$diffStr = implode(', ', $diffArr);
echo 'Difference: ' . ($diffStr == '' ? '0' : $diffStr) . PHP_EOL;

div with dynamic min-height based on browser window height

As mentioned elsewhere, the CSS function calc() can work nicely here. It is now mostly supported. You could use like:

.container
{
    min-height: 70%;
    min-height: -webkit-calc(100% - 300px);
    min-height: -moz-calc(100% - 300px);
    min-height: calc(100% - 300px);
}

Adding an .env file to React Project

If in case you are getting the values as undefined, then you should consider restarting the node server and recompile again.

Install numpy on python3.3 - Install pip for python3

On fedora/rhel/centos you need to

sudo yum install -y python3-devel

before

mkvirtualenv -p /usr/bin/python3.3 test-3.3
pip install numpy

otherwise you'll get

SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel.

Bootstrap 3 Align Text To Bottom of Div

You can do this:

CSS:

#container {
    height:175px;
}

#container h3{
    position:absolute;
    bottom:0;
    left:0;
}

Then in HTML:

<div class="row">
    <div class="col-sm-6">
        <img src="//placehold.it/600x300" alt="Logo" />
    </div>
    <div id="container" class="col-sm-6">
        <h3>Some Text</h3>
    </div>
</div>

EDIT: add the <

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

Reporting Services permissions on SQL Server R2 SSRS

in my case this error resolved by adding permission level to root folder .

i previously only granted permission in 2 place. one in site setting and one in a new folder that has custom permission .

but the user permission to browse the root folder was also required. Note The "Folder setting" in root folder

another time i had similar problem and adding users in the following windows group SQLServerReportServerUser$servername$MSRS10_50.MSSQLSERVER and running IE as Administrator or turning off UAC resolved my problem .

"sed" command in bash

Here sed is replacing all occurrences of % with $ in its standard input.

As an example

$ echo 'foo%bar%' | sed -e 's,%,$,g'

will produce "foo$bar$".

Can I stop 100% Width Text Boxes from extending beyond their containers?

If you don't need to do it dynamically (for example, your form is of a fixed width) you can just set the width of child <input> elements to the width of their container minus any decorations like padding, margin, border, etc.:

 // the parent div here has a width of 200px:
.form-signin input[type="text"], .form-signin input[type="password"], .form-signin input[type="email"], .form-signin input[type="number"] {
  font-size: 16px;
  height: auto;
  display: block;
  width: 280px;
  margin-bottom: 15px;
  padding: 7px 9px;
}

What is stdClass in PHP?

Its also worth noting that by using Casting you do not actually need to create an object as in the answer given by @Bandula. Instead you can simply cast your array to an object and the stdClass is returned. For example:

$array = array(
    'Property1'=>'hello',
    'Property2'=>'world',
    'Property3'=>'again',
);

$obj = (object) $array;
echo $obj->Property3;

Output: again

window.open target _self v window.location.href?

Hopefully someone else is saved by reading this.

We encountered an issue with webkit based browsers doing:

window.open("webpage.htm", "_self");

The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:

location.href = "webpage.html";

all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

The steps I needed to perform were:

  1. Add reference to System.Web.Http.WebHost.
  2. Add App_Start\WebApiConfig.cs (see code snippet below).
  3. Import namespace System.Web.Http in Global.asax.cs.
  4. Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.
  5. Add a controller deriving from System.Web.Http.ApiController.

I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.

App_Start\WebApiConfig.cs:

using System.Web.Http;

class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });
    }
}

Global.asax.cs:

using System.Web.Http;

...

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Update 10.16.2015:

Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

For Intellij IDEA version 11.0.2

File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.

Next goto Build | Build artifacts --> choose your artifact.

source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/

How do you get centered content using Twitter Bootstrap?

You need to adjust with the .span.

Example:

<div class="container-fluid">
  <div class="row-fluid">
    <div class="span4"></div>
    <!--/span-->
    <div class="span4" align="center">
      <div class="hero-unit" align="center">
        <h3>Sign In</h3>
        <form>
          <div class="input-prepend">
            <span class="add-on"><i class="icon-envelope"></i> </span>
            <input class="span6" type="text" placeholder="Email address">
          </div>
          <div class="input-prepend">
            <span class="add-on"><i class="icon-key"></i> </span>
            <input class="span6" type="password" placeholder="Password">
          </div>
        </form>
      </div>
    </div>
    <!-- /span -->
    <div class="span4"></div>
  </div>
  <!-- /row -->
</div>

Set custom attribute using JavaScript

For people coming from Google, this question is not about data attributes - OP added a non-standard attribute to their HTML object, and wondered how to set it.

However, you should not add custom attributes to your properties - you should use data attributes - e.g. OP should have used data-icon, data-url, data-target, etc.

In any event, it turns out that the way you set these attributes via JavaScript is the same for both cases. Use:

ele.setAttribute(attributeName, value);

to change the given attribute attributeName to value for the DOM element ele.

For example:

document.getElementById("someElement").setAttribute("data-id", 2);

Note that you can also use .dataset to set the values of data attributes, but as @racemic points out, it is 62% slower (at least in Chrome on macOS at the time of writing). So I would recommend using the setAttribute method instead.

Pass react component as props

Using this.props.children is the idiomatic way to pass instantiated components to a react component

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div or span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>

If what you want to do is to pass a children-like parameter as a prop, you can do that:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.

How can I set the opacity or transparency of a Panel in WinForms?

This does work for me. In below example, Alpha range can be a value between 0 to 255. Previously, I made a mistake by thinking that it must be a value of percentage.

Dim x as integer = 230 Panel1.BackColor = Color.FromArgb(x, Color.Blue)

Put byte array to JSON and vice versa

Amazingly now org.json now lets you put a byte[] object directly into a json and it remains readable. you can even send the resulting object over a websocket and it will be readable on the other side. but i am not sure yet if the size of the resulting object is bigger or smaller than if you were converting your byte array to base64, it would certainly be neat if it was smaller.

It seems to be incredibly hard to measure how much space such a json object takes up in java. if your json consists merely of strings it is easily achievable by simply stringifying it but with a bytearray inside it i fear it is not as straightforward.

stringifying our json in java replaces my bytearray for a 10 character string that looks like an id. doing the same in node.js replaces our byte[] for an unquoted value reading <Buffered Array: f0 ff ff ...> the length of the latter indicates a size increase of ~300% as would be expected

How to delete multiple values from a vector?

You can use setdiff.

Given

a <- sample(1:10)
remove <- c(2, 3, 5)

Then

> a
 [1] 10  8  9  1  3  4  6  7  2  5
> setdiff(a, remove)
[1] 10  8  9  1  4  6  7

Can a unit test project load the target application's app.config file?

In Visual Studio 2008 I added the app.config file to the test project as an existing item and selected copy as link in order to make sure it's not duplicated. That way I only have one copy in my solution. With several test projects it comes in really handy!

Add Existing Item

Add As Link