Programs & Examples On #Fluentvalidation

Fluent Validation is an ASP.NET MVC integrated validation framework that allows the developer to set validation rules using expressions. It is testable and completely compatible with the inversion of control (dependency injection) pattern and TDD (test-driven development) technique.

Make a DIV fill an entire table cell

I does not watch here an old CSS-trick for <div> inside <td>. Hence I remind: simple set some minimal value for width, but what-you-need for min-width. For example:

<div style="width: 3px; min-width: 99%;">

The td's width, in that case, is up to you.

Appending to 2D lists in Python

[[]]*3 is not the same as [[], [], []].

It's as if you'd said

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.

Postgres: clear entire database before re-creating / re-populating from bash script

I'd just drop the database and then re-create it. On a UNIX or Linux system, that should do it:

$ dropdb development_db_name
$ createdb developmnent_db_name

That's how I do it, actually.

Show animated GIF

For loading animated gifs stored in a source package (in the source code), this worked for me:

URL url = MyClass.class.getResource("/res/images/animated.gif");
ImageIcon imageIcon = new ImageIcon(url);
JLabel label = new JLabel(imageIcon);

Relation between CommonJS, AMD and RequireJS?

It is quite normal to organize JavaScript program modular into several files and to call child-modules from the main js module.

The thing is JavaScript doesn't provide this. Not even today in latest browser versions of Chrome and FF.

But, is there any keyword in JavaScript to call another JavaScript module?

This question may be a total collapse of the world for many because the answer is No.


In ES5 ( released in 2009 ) JavaScript had no keywords like import, include, or require.

ES6 saves the day ( released in 2015 ) proposing the import keyword ( https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/import ), but no browser implements this.

If you use Babel 6.18.0 and transpile with ES2015 option only

import myDefault from "my-module";

you will get require again.

"use strict";
var _myModule = require("my-module");
var _myModule2 = _interopRequireDefault(_myModule);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

This is because require means the module will be loaded from Node.js. Node.js will handle everything from system level file read to wrapping functions into the module.

Because in JavaScript functions are the only wrappers to represent the modules.

I'm a lot confused about CommonJS and AMD?

Both CommonJS and AMD are just two different techniques how to overcome the JavaScript "defect" to load modules smart.

Right way to reverse a pandas DataFrame?

This works:

    for i,r in data[::-1].iterrows():
        print(r['Odd'], r['Even'])

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

  1. return None or return can be used to exit out of a function or program, both does the same thing
  2. quit() function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter.
    import site
    
    def func():
        print("Hi")
        quit()
        print("Bye")
  1. exit() function can be used, similar to quit() but the use is discouraged for making real world applications.
import site
    
    def func():
        print("Hi")
        exit()
        print("Bye")
  1. sys.exit([arg]) function can be used and need to import sys module for that, this function can be used for real world applications unlike the other two functions.
import sys 
  height = 150
  
if height < 165: # in cm 
      
    # exits the program 
    sys.exit("Height less than 165")     
else: 
    print("You ride the rollercoaster.") 
  1. os._exit(n) function can be used to exit from a process, and need to import os module for that.

Inner join of DataTables in C#

this function will join 2 tables with a known join field, but this cannot allow 2 fields with the same name on both tables except the join field, a simple modification would be to save a dictionary with a counter and just add number to the same name filds.

public static DataTable JoinDataTable(DataTable dataTable1, DataTable dataTable2, string joinField)
{
    var dt = new DataTable();
    var joinTable = from t1 in dataTable1.AsEnumerable()
                            join t2 in dataTable2.AsEnumerable()
                                on t1[joinField] equals t2[joinField]
                            select new { t1, t2 };

    foreach (DataColumn col in dataTable1.Columns)
        dt.Columns.Add(col.ColumnName, typeof(string));

    dt.Columns.Remove(joinField);

    foreach (DataColumn col in dataTable2.Columns)
        dt.Columns.Add(col.ColumnName, typeof(string));

    foreach (var row in joinTable)
    {
        var newRow = dt.NewRow();
        newRow.ItemArray = row.t1.ItemArray.Union(row.t2.ItemArray).ToArray();
        dt.Rows.Add(newRow);
    }
    return dt;
}

How to pass multiple checkboxes using jQuery ajax post

From the jquery docs for POST (3rd example):

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like

var data = { 'user_ids[]' : []};
$(":checked").each(function() {
  data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);

How to lock specific cells but allow filtering and sorting

Lorie's answer is good, but if a user selects a range that contains locked and unlocked cells, the data in the locked/protected cells can be deleted.

Isaac's answer is great, but doesn't work if the user highlights a range that has both locked and unlocked cells.

I modified Isaac's code a bit to undo changes if ANY of the cells in the target range are locked. It also displays a message explaining why the action was undone. Combined with Lorie's answer, I was able to achieve the desired result of being able to sort/filter a protected sheet, while still allowing a user to make changes to an unprotected cell.

Follow the instructions in Lorie's answer, then put the following code in the worksheet module:

Private Sub Worksheet_Change(ByVal Target As Range)
    For Each i In Target
       If i.Locked = True Then
            Application.EnableEvents = False
            Application.Undo
            Application.EnableEvents = True
            MsgBox "Your action was undone because it made changes to a locked cell.", , "Action Undone"
        Exit For
        End If
    Next i
End Sub

How to display Toast in Android?

Here's another one:

refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(),getText(R.string.refresh_btn_pushed),Toast.LENGTH_LONG).show();
            }
        });

Where Toast is:

Toast.makeText(getBaseContext(),getText(R.string.refresh_btn_pushed),Toast.LENGTH_LONG).show();

& strings.xml:

<string name="refresh_btn_pushed">"Refresh was Clicked..."</string>

How to check if one of the following items is in a list?

This will do it in one line.

>>> a=[2,3,4]
>>> b=[1,2]
>>> bool(sum(map(lambda x: x in b, a)))
True

Javascript/DOM: How to remove all events of a DOM object?

you can add function and remove all other click by assign them

_x000D_
_x000D_
btn1 = document.querySelector(".btn-1")
btn1.addEventListener("click" , _=>{console.log("hello")})
btn1.addEventListener("click" , _=>{console.log("How Are you ?")})

btn2 = document.querySelector(".btn-2")
btn2.onclick = _=>{console.log("Hello")}
btn2.onclick = _=>{console.log("Bye")}
_x000D_
<button class="btn-1">Hello to Me</button>
<button class="btn-2">Hello to Bye</button>
_x000D_
_x000D_
_x000D_

Java 8: Difference between two LocalDateTime in multiple units

I found the best way to do this is with ChronoUnit.

long minutes = ChronoUnit.MINUTES.between(fromDate, toDate);
long hours = ChronoUnit.HOURS.between(fromDate, toDate);

Additional documentation is here: https://docs.oracle.com/javase/tutorial/datetime/iso/period.html

Why should I use the keyword "final" on a method parameter in Java?

I use final all the time on parameters.

Does it add that much? Not really.

Would I turn it off? No.

The reason: I found 3 bugs where people had written sloppy code and failed to set a member variable in accessors. All bugs proved difficult to find.

I'd like to see this made the default in a future version of Java. The pass by value/reference thing trips up an awful lot of junior programmers.

One more thing.. my methods tend to have a low number of parameters so the extra text on a method declaration isn't an issue.

How to detect if a string contains at least a number?

Use this:

SELECT * FROM Table WHERE Column LIKE '%[0-9]%'

MSDN - LIKE (Transact-SQL)

string comparison in batch file

While @ajv-jsy's answer works most of the time, I had the same problem as @MarioVilas. If one of the strings to be compared contains a double quote ("), the variable expansion throws an error.

Example:

@echo off
SetLocal

set Lhs="
set Rhs="

if "%Lhs%" == "%Rhs%" echo Equal

Error:

echo was unexpected at this time.

Solution:

Enable delayed expansion and use ! instead of %.

@echo off
SetLocal EnableDelayedExpansion

set Lhs="
set Rhs="

if !Lhs! == !Rhs! echo Equal

:: Surrounding with double quotes also works but appears (is?) unnecessary.
if "!Lhs!" == "!Rhs!" echo Equal

I have not been able to break it so far using this technique. It works with empty strings and all the symbols I threw at it.

Test:

@echo off
SetLocal EnableDelayedExpansion

:: Test empty string
set Lhs=
set Rhs=
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

:: Test symbols
set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

You can use Replace instead of INSERT ... ON DUPLICATE KEY UPDATE.

Replace whole line containing a string using Sed

The accepted answer did not work for me for several reasons:

  • my version of sed does not like -i with a zero length extension
  • the syntax of the c\ command is weird and I couldn't get it to work
  • I didn't realize some of my issues are coming from unescaped slashes

So here is the solution I came up with which I think should work for most cases:

function escape_slashes {
    sed 's/\//\\\//g' 
}

function change_line {
    local OLD_LINE_PATTERN=$1; shift
    local NEW_LINE=$1; shift
    local FILE=$1

    local NEW=$(echo "${NEW_LINE}" | escape_slashes)
    sed -i .bak '/'"${OLD_LINE_PATTERN}"'/s/.*/'"${NEW}"'/' "${FILE}"
    mv "${FILE}.bak" /tmp/
}

So the sample usage to fix the problem posed:

change_line "TEXT_TO_BE_REPLACED" "This line is removed by the admin." yourFile

How do I get the Date & Time (VBS)

To expound on Numenor's answer you can do something like, Format(Now(),"HH:mm:ss") using these custom date/time formating options


For everyone who is tempted to downvote this answer please be aware that the question was originally tagged VB and vbscript hence my answer, the VB tag was edited out leaving only the vbscript tag. The OP accepted this answer which I take to mean that it gave him the information that he needed.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

This probably because of your gzip version incompatibility.

Check these points first:

which gzip

/usr/bin/gzip or /bin/gzip

It should be either /bin/gzip or /usr/bin/gzip. If your gzip points to some other gzip application please try by removing that path from your PATH env variable.

Next is

gzip -V

gzip 1.3.5 (2002-09-30)

Your problem can be resolve with these check points.

How to terminate the script in JavaScript?

Place the debugger; keyword in your JavaScript code where you want to stop the execution. Then open your favorite browser's developer tools and reload the page. Now it should pause automatically. Open the Sources section of your tools: the debugger; keyword is highlighted and you have the option to resume script execution.

I hope it helps.

More information at:

How can I turn a DataTable to a CSV?

In case anyone else stumbles on this, I was using File.ReadAllText to get CSV data and then I modified it and wrote it back with File.WriteAllText. The \r\n CRLFs were fine but the \t tabs were ignored when Excel opened it. (All solutions in this thread so far use a comma delimiter but that doesn't matter.) Notepad showed the same format in the resulting file as in the source. A Diff even showed the files as identical. But I got a clue when I opened the file in Visual Studio with a binary editor. The source file was Unicode but the target was ASCII. To fix, I modified both ReadAllText and WriteAllText with third argument set as System.Text.Encoding.Unicode, and from there Excel was able to open the updated file.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Those notices are because you don't have the used variable defined and my_index key was not present into $my_array variable.

Those notices were triggered every time, because your code is not correct, but probably you didn't have the reporting of notices on.

Solve the bugs:

$my_variable_name = "Variable name"; // defining variable
echo "My variable value is: " . $my_variable_name;

if(isset($my_array["my_index"])){
    echo "My index value is: " . $my_array["my_index"]; // check if my_index is set 
}

Another way to get this out:

ini_set("error_reporting", false)

How to display text in pygame?

You can create a surface with text on it. For this take a look at this short example:

pygame.font.init() # you have to call this at the start, 
                   # if you want to use this module.
myfont = pygame.font.SysFont('Comic Sans MS', 30)

This creates a new object on which you can call the render method.

textsurface = myfont.render('Some Text', False, (0, 0, 0))

This creates a new surface with text already drawn onto it. At the end you can just blit the text surface onto your main screen.

screen.blit(textsurface,(0,0))

Bear in mind, that everytime the text changes, you have to recreate the surface again, to see the new text.

Generate a random number in a certain range in MATLAB

Generate values from the uniform distribution on the interval [a, b].

      r = a + (b-a).*rand(100,1);

Get time in milliseconds using C#

Using Stopwatch class we can achieve it from System.Diagnostics.

Stopwatch stopwatch  = new Stopwatch();
stopwatch.Start();
stopwatch.Stop();
Debug.WriteLine(stopwatch.ElapsedMilliseconds);

How to create a new text file using Python

# Method 1
f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
    # File closed automatically

There are many more methods but these two are most common. Hope this helped!

Remove the newline character in a list read from a file

You could actually put the newlines to good use by reading the entire file into memory as a single long string and then use them to split that into the list of grades.

with open("grades.dat") as input:
    grades = [line.split(",") for line in input.read().splitlines()]
etc...

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

May be its irrelevant answer but its working in my case...don't know what was wrong on my server...I just enable error log on Ubuntu 16.04 server.

//For PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);

Syntax error on print with Python 3

It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.

print('Hello world!')

state machines tutorials

I prefer using function pointers over gigantic switch statements, but in contrast to qrdl's answer I normally don't use explicit return codes or transition tables.

Also, in most cases you'll want a mechanism to pass along additional data. Here's an example state machine:

#include <stdio.h>

struct state;
typedef void state_fn(struct state *);

struct state
{
    state_fn * next;
    int i; // data
};

state_fn foo, bar;

void foo(struct state * state)
{
    printf("%s %i\n", __func__, ++state->i);
    state->next = bar;
}

void bar(struct state * state)
{
    printf("%s %i\n", __func__, ++state->i);
    state->next = state->i < 10 ? foo : 0;
}

int main(void)
{
    struct state state = { foo, 0 };
    while(state.next) state.next(&state);
}

How to edit default dark theme for Visual Studio Code?

The file you are looking for is at,

Microsoft VS Code\resources\app\extensions\theme-defaults\themes

on Windows and search for filename dark_vs.json to locate it on any other system.


Update:

With new versions of VSCode you don't need to hunt for the settings file to customize the theme. Now you can customize your color theme with the workbench.colorCustomizations and editor.tokenColorCustomizations user settings. Documentation on the matter can be found here.

No 'Access-Control-Allow-Origin' header is present on the requested resource error

If you use Google Chrome browser you can hack with an extension.

You can find a Chrome extension that will modify CORS headers on the fly in your application. Obviously, this is Chrome only, but I like that it works with zero changes anywhere at all.

You can use it for debugging your app on a local machine (if everything works in production).

Notice: If URL becomes broken the extension name is Access-Control-Allow-Origin: *. I recommend you to disable this extension when you not working on your stuff, because, for example, youtube does not work with this extension.

How can I exclude $(this) from a jQuery selector?

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

Java: unparseable date exception

I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.

This from the accepted answer helped me solve this problem:

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern

The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema

I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

I solved this problem by ORDERING my source data (xls, csv, whatever) such that the longest text values on at the top of the file. Excel is great. use the LEN() function on your challenging column. Order by that length value with the longest value on top of your dataset. Save. Try the import again.

.keyCode vs. .which

I'd recommend event.key currently. MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

event.KeyCode and event.which both have nasty deprecated warnings at the top of their MDN pages:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which

For alphanumeric keys, event.key appears to be implemented identically across all browsers. For control keys (tab, enter, escape, etc), event.key has the same value across Chrome/FF/Safari/Opera but a different value in IE10/11/Edge (IEs apparently use an older version of the spec but match each other as of Jan 14 2018).

For alphanumeric keys a check would look something like:

event.key === 'a'

For control characters you'd need to do something like:

event.key === 'Esc' || event.key === 'Escape'

I used the example here to test on multiple browsers (I had to open in codepen and edit to get it to work with IE10): https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

event.code is mentioned in a different answer as a possibility, but IE10/11/Edge don't implement it, so it's out if you want IE support.

C++ cast to derived class

Think like this:

class Animal { /* Some virtual members */ };
class Dog: public Animal {};
class Cat: public Animal {};


Dog     dog;
Cat     cat;
Animal& AnimalRef1 = dog;  // Notice no cast required. (Dogs and cats are animals).
Animal& AnimalRef2 = cat;
Animal* AnimalPtr1 = &dog;
Animal* AnimlaPtr2 = &cat;

Cat&    catRef1 = dynamic_cast<Cat&>(AnimalRef1);  // Throws an exception  AnimalRef1 is a dog
Cat*    catPtr1 = dynamic_cast<Cat*>(AnimalPtr1);  // Returns NULL         AnimalPtr1 is a dog
Cat&    catRef2 = dynamic_cast<Cat&>(AnimalRef2);  // Works
Cat*    catPtr2 = dynamic_cast<Cat*>(AnimalPtr2);  // Works

// This on the other hand makes no sense
// An animal object is not a cat. Therefore it can not be treated like a Cat.
Animal  a;
Cat&    catRef1 = dynamic_cast<Cat&>(a);    // Throws an exception  Its not a CAT
Cat*    catPtr1 = dynamic_cast<Cat*>(&a);   // Returns NULL         Its not a CAT.

Now looking back at your first statement:

Animal   animal = cat;    // This works. But it slices the cat part out and just
                          // assigns the animal part of the object.
Cat      bigCat = animal; // Makes no sense.
                          // An animal is not a cat!!!!!
Dog      bigDog = bigCat; // A cat is not a dog !!!!

You should very rarely ever need to use dynamic cast.
This is why we have virtual methods:

void makeNoise(Animal& animal)
{
     animal.DoNoiseMake();
}

Dog    dog;
Cat    cat;
Duck   duck;
Chicken chicken;

makeNoise(dog);
makeNoise(cat);
makeNoise(duck);
makeNoise(chicken);

The only reason I can think of is if you stored your object in a base class container:

std::vector<Animal*>  barnYard;
barnYard.push_back(&dog);
barnYard.push_back(&cat);
barnYard.push_back(&duck);
barnYard.push_back(&chicken);

Dog*  dog = dynamic_cast<Dog*>(barnYard[1]); // Note: NULL as this was the cat.

But if you need to cast particular objects back to Dogs then there is a fundamental problem in your design. You should be accessing properties via the virtual methods.

barnYard[1]->DoNoiseMake();

Get UserDetails object from Security Context in Spring MVC controller

If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {

    ModelAndView mv = new ModelAndView("index");

    String userName = "not logged in"; // Any default user  name
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        userName = principal.getName();
    }

    mv.addObject("username", userName);

    // By adding a little code (same way) you can check if user has any
    // roles you need, for example:

    boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
    mv.addObject("isAdmin", fAdmin);

    return mv;
}

Note "HttpServletRequest request" parameter added.

Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

How to filter multiple values (OR operation) in angularJS

Please try this

var m = angular.module('yourModuleName');
m.filter('advancefilter', ['$filter', function($filter){
    return function(data, text){
        var textArr = text.split(' ');
        angular.forEach(textArr, function(test){
            if(test){
                  data = $filter('filter')(data, test);
            }
        });
        return data;
    }
}]);

How can I store JavaScript variable output into a PHP variable?

in your view:

  <?php $value = '<p id="course_id"></p>';?>

javascript code:

  var course = document.getElementById("courses").value;
  
 document.getElementById("course_id").innerHTML = course;

I get conflicting provisioning settings error when I try to archive to submit an iOS app

Find .xcodeproj file and open it with a text editor

Find fields below and make them like this

CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";

PROVISIONING_PROFILE = "";

PROVISIONING_PROFILE_SPECIFIER = "";

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

_x000D_
_x000D_
$("h3").text("context")
_x000D_
_x000D_
_x000D_

Just use method "text()".

The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

http://api.jquery.com/text/

Read a text file line by line in Qt

Here's the example from my code. So I will read a text from 1st line to 3rd line using readLine() and then store to array variable and print into textfield using for-loop :

QFile file("file.txt");

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    QString line[3] = in.readLine();
    for(int i=0; i<3; i++)
    {
        ui->textEdit->append(line[i]);
    }

SQL Server: Filter output of sp_who2

There's quite a few good sp_who3 user stored procedures out there - I'm sure Adam Machanic did a really good one, AFAIK.

Adam calls it Who Is Active: http://whoisactive.com

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To use aliases on eloquent models modify your code like this:

Item
    ::from( 'items as items_alias' )
    ->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
    ->select( DB::raw( 'items_alias.*' ) )
    ->get();

This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result. Adding DB::raw prevents laravel from adding table prefixes to aliases.

XCOPY switch to create specified directory if it doesn't exist?

Try /E

To get a full list of options: xcopy /?

Copy array by value

When we want to copy an array using the assignment operator ( = ) it doesn't create a copy it merely copies the pointer/reference to the array. For example:

_x000D_
_x000D_
const oldArr = [1,2,3];_x000D_
_x000D_
const newArr = oldArr;  // now oldArr points to the same place in memory _x000D_
_x000D_
console.log(oldArr === newArr);  // Points to the same place in memory thus is true_x000D_
_x000D_
const copy = [1,2,3];_x000D_
_x000D_
console.log(copy === newArr);  // Doesn't point to the same place in memory and thus is false
_x000D_
_x000D_
_x000D_

Often when we transform data we want to keep our initial datastructure (e.g. Array) intact. We do this by making a exact copy of our array so this one can be transformed while the initial one stays intact.

Ways of copying an array:

_x000D_
_x000D_
const oldArr = [1,2,3];_x000D_
_x000D_
// Uses the spread operator to spread out old values into the new array literal_x000D_
const newArr1 = [...oldArr];_x000D_
_x000D_
// Slice with no arguments returns the newly copied Array_x000D_
const newArr2 = oldArr.slice();_x000D_
_x000D_
// Map applies the callback to every element in the array and returns a new array_x000D_
const newArr3 = oldArr.map((el) => el);_x000D_
_x000D_
// Concat is used to merge arrays and returns a new array. Concat with no args copies an array_x000D_
const newArr4 = oldArr.concat();_x000D_
_x000D_
// Object.assign can be used to transfer all the properties into a new array literal_x000D_
const newArr5 = Object.assign([], oldArr);_x000D_
_x000D_
// Creating via the Array constructor using the new keyword_x000D_
const newArr6 = new Array(...oldArr);_x000D_
_x000D_
// For loop_x000D_
function clone(base) {_x000D_
 const newArray = [];_x000D_
    for(let i= 0; i < base.length; i++) {_x000D_
     newArray[i] = base[i];_x000D_
 }_x000D_
 return newArray;_x000D_
}_x000D_
_x000D_
const newArr7 = clone(oldArr);_x000D_
_x000D_
console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);
_x000D_
_x000D_
_x000D_

Be careful when arrays or objects are nested!:

When arrays are nested the values are copied by reference. Here is an example of how this could lead to issues:

_x000D_
_x000D_
let arr1 = [1,2,[1,2,3]]_x000D_
_x000D_
let arr2 = [...arr1];_x000D_
_x000D_
arr2[2][0] = 5;  // we change arr2_x000D_
_x000D_
console.log(arr1);  // arr1 is also changed because the array inside arr1 was copied by reference
_x000D_
_x000D_
_x000D_

So don't use these methods when there are objects or arrays inside your array you want to copy. i.e. Use these methods on arrays of primitives only.

If you do want to deepclone a javascript array use JSON.parse in conjunction with JSON.stringify, like this:

_x000D_
_x000D_
let arr1 = [1,2,[1,2,3]]_x000D_
_x000D_
let arr2 = JSON.parse(JSON.stringify(arr1)) ;_x000D_
_x000D_
arr2[2][0] = 5;_x000D_
_x000D_
console.log(arr1);  // now I'm not modified because I'm a deep clone
_x000D_
_x000D_
_x000D_

Performance of copying:

So which one do we choose for optimal performance. It turns out that the most verbose method, the for loop has the highest performance. Use the for loop for really CPU intensive copying (large/many arrays).

After that the .slice() method also has decent performance and is also less verbose and easier for the programmer to implement. I suggest to use .slice() for your everyday copying of arrays which aren't very CPU intensive. Also avoid using the JSON.parse(JSON.stringify(arr)) (lots of overhead) if no deep clone is required and performance is an issue.

Source performance test

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

Thanks to Andrey-Egorov and this answer, I've managed to do it in C#

IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string value = (string)js.ExecuteScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

cin and getline skipping input

Here, the '\n' left by cin, is creating issues.

do {
    system("cls");
    manageCustomerMenu();
    cin >> choice;               #This cin is leaving a trailing \n
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

This \n is being consumed by next getline in createNewCustomer(). You should use getline instead -

do {
    system("cls");
    manageCustomerMenu();
    getline(cin, choice)               
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

I think this would resolve the issue.

Access Form - Syntax error (missing operator) in query expression

Put [] around any field names that had spaces (as Dreden says) and save your query, close it and reopen it.

Using Access 2016, I still had the error message on new queries after I added [] around any field names... until the Query was saved.

Once the Query is saved (and visible in the Objects' List), closed and reopened, the error message disappears. This seems to be a bug from Access.

Postgres DB Size Command

You can get the names of all the databases that you can connect to from the "pg_datbase" system table. Just apply the function to the names, as below.

select t1.datname AS db_name,  
       pg_size_pretty(pg_database_size(t1.datname)) as db_size
from pg_database t1
order by pg_database_size(t1.datname) desc;

If you intend the output to be consumed by a machine instead of a human, you can cut the pg_size_pretty() function.

How to add buttons like refresh and search in ToolBar in Android?

To control the location of the title you may want to set a custom font as explained here (by twaddington): Link

Then to relocate the position of the text, in updateMeasureState() you would add p.baselineShift += (int) (p.ascent() * R); Similarly in updateDrawState() add tp.baselineShift += (int) (tp.ascent() * R); Where R is double between -1 and 1.

SQL Stored Procedure: If variable is not null, update statement

Another approach when you have many updates would be to use COALESCE:

UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET    
    [ABC]  = COALESCE(@ABC, [ABC]),
    [ABCD] = COALESCE(@ABCD, [ABCD])

When should I use a trailing slash in my URL?

Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.

How return error message in spring mvc @Controller

Evaluating the error response from another service invocated...

This was my solution for evaluating the error:

try {
        return authenticationFeign.signIn(userDto, dataRequest);
    }catch(FeignException ex){

        //ex.status();

        if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
            System.out.println("is a error 401");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity<>(HttpStatus.OK);

    }

How do you put an image file in a json object?

Use data URL scheme: https://en.wikipedia.org/wiki/Data_URI_scheme

In this case you use that string directly in html : <img src="data:image/png;base64,iVBOR....">

Parse JSON String into List<string>

I use this JSON Helper class in my projects. I found it on the net a year ago but lost the source URL. So I am pasting it directly from my project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
/// <summary>
/// JSON Serialization and Deserialization Assistant Class
/// </summary>
public class JsonHelper
{
    /// <summary>
    /// JSON Serialization
    /// </summary>
    public static string JsonSerializer<T> (T t)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, t);
        string jsonString = Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        return jsonString;
    }
    /// <summary>
    /// JSON Deserialization
    /// </summary>
    public static T JsonDeserialize<T> (string jsonString)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }
}

You can use it like this: Create the classes as Craig W. suggested.

And then deserialize like this

RootObject root = JSONHelper.JsonDeserialize<RootObject>(json);

Converting a string to a date in JavaScript

_x000D_
_x000D_
function dateConvertor(date){
   var options = { weekday: "long",  
                    year: "numeric",  
                    month: "short",  
                    day: "numeric" };  

   var newDateFormat = new Date(date).toLocaleDateString("en-US", options); 
   var newTimeFormat = new Date(date).toLocaleTimeString();  
   var dateAndTime = newDateFormat +' ' + newTimeFormat        
  return dateAndTime
}


console.log(dateConvertor("2021-01-19T18:30:00.000Z"));
_x000D_
_x000D_
_x000D_

Validate Dynamically Added Input fields

You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.

And here is my solution that I've tested and it works:

<script type="text/javascript">
   $(document).ready(function() {
        var numberIncr = 1; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
            numberIncr++;
        }

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });            

            // prevent default submit action         
            event.preventDefault();

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
                console.log("validates");
            } else {
                console.log("does not validate");
            }
        })

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator
        $('form.commentForm').validate();

   });


</script>

And the html form part:

<form class="commentForm" method="get" action="">
    <div>

        <p id="inputs">    
            <input class="comment" name="name0" />
        </p>

    <input class="submit" type="submit" value="Submit" />
    <input type="button" value="add" id="addInput" />

    </div>
</form>

Good luck! Please approve answer if it suits you!

C++ floating point to integer type conversions

Check out the boost NumericConversion library. It will allow to explicitly control how you want to deal with issues like overflow handling and truncation.

How do I create a slug in Django?

Use prepopulated_fields in your admin class:

class ArticleAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}

admin.site.register(Article, ArticleAdmin)

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

When you generate a JAXB model from an XML Schema, global elements that correspond to named complex types will have that metadata captured as an @XmlElementDecl annotation on a create method in the ObjectFactory class. Since you are creating the JAXBContext on just the DocumentType class this metadata isn't being processed. If you generated your JAXB model from an XML Schema then you should create the JAXBContext on the generated package name or ObjectFactory class to ensure all the necessary metadata is processed.

Example solution:

JAXBContext jaxbContext = JAXBContext.newInstance(my.generatedschema.dir.ObjectFactory.class);
DocumentType documentType = ((JAXBElement<DocumentType>) jaxbContext.createUnmarshaller().unmarshal(inputStream)).getValue();

Evaluate a string with a switch in C++

A switch statement can only be used for integral values, not for values of user-defined type. And even if it could, your input operation doesn't work, either.

You might want this:

#include <string>
#include <iostream>


std::string input;

if (!std::getline(std::cin, input)) { /* error, abort! */ }

if (input == "Option 1")
{
    // ... 
}
else if (input == "Option 2")
{ 
   // ...
}

// etc.

Is a DIV inside a TD a bad idea?

If you want to use position: absolute; on the div with position: relative; on the td you will run into issues. FF, safari, and chrome (mac, not PC though) will not position the div relative to the td (like you would expect) this is also true for divs with display: table-whatever; so if you want to do that you need two divs, one for the container width: 100%; height: 100%; and no border so it fills the td without any visual impact. and then the absolute one.

other than that why not just split the cell?

Invoking JavaScript code in an iframe from the parent page

Assume your iFrame's id is "targetFrame" and the function you want to call is targetFunction():

document.getElementById('targetFrame').contentWindow.targetFunction();

You can also access the frame using window.frames instead of document.getElementById.

// this option does not work in most of latest versions of chrome and Firefox
window.frames[0].frameElement.contentWindow.targetFunction(); 

Changing Placeholder Text Color with Swift

crubio's answer update for Swift 4

Select the UITextField and open the identity inspector on the right:

Click on the plus button and add a new runtime attribute: placeholderLabel.textColor (instead of _placeholderLabel.textColor)

Use Color as type and select the color.

If you run your project, you will see the changes.

Listing contents of a bucket with boto3

This is similar to an 'ls' but it does not take into account the prefix folder convention and will list the objects in the bucket. It's left up to the reader to filter out prefixes which are part of the Key name.

In Python 2:

from boto.s3.connection import S3Connection

conn = S3Connection() # assumes boto.cfg setup
bucket = conn.get_bucket('bucket_name')
for obj in bucket.get_all_keys():
    print(obj.key)

In Python 3:

from boto3 import client

conn = client('s3')  # again assumes boto.cfg setup, assume AWS S3
for key in conn.list_objects(Bucket='bucket_name')['Contents']:
    print(key['Key'])

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Why does Git treat this text file as a binary file?

I had a similar issue as I pasted some text from a binary Kafka message, which inserted non-visible character and caused git to think the file is binary.

I found the offending characters by searching the file using regex [^ -~\n\r\t]+.

  • [ match characters in this set
  • ^ match characters not in this set
  • -~ matches all characters from ' ' (space) to '~'
  • \n newline
  • \r carriage return
  • \t tab
  • ] close set
  • + match one or more of these characters

WPF: simple TextBox data binding

Name2 is a field. WPF binds only to properties. Change it to:

public string Name2 { get; set; }

Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:

partial class Window1 : Window, INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName)
  {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }

  private string _name2;

  public string Name2
  {
    get { return _name2; }
    set
    {
      if (value != _name2)
      {
         _name2 = value;
         OnPropertyChanged("Name2");
      }
    }
  }
}

You should consider moving this to a separate data object rather than on your Window class.

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Now there is official FAQ for using Google Play in How do I install Google Play Services?, here the FAQ text:

For intellectual property reasons, Google Play Services are not included by default in Genymotion virtual devices. However, if you really need them, you can use the packages provided by OpenGapps. Simply follow these steps:

  1. Visit opengapps.org
  2. Select x86 as platform
  3. Choose the Android version corresponding to your virtual device
  4. Select nano as variant
  5. Download the zip file
  6. Drag & Drop the zip installer in new Genymotion virtual device (2.7.2 and above only)
  7. Follow the pop-up instructions

Please note Genymobile Inc. and Genymotion assume no liability whatsoever resulting from the download, install and use of Google Play Services within your virtual devices. You are solely responsible for the use and assume all liability related thereto. Moreover, we disclaim any warranties of any kind for a particular purpose regarding the compatibility of the OpenGapps packages with any version of Genymotion.

How to convert wstring into string?

Solution from: http://forums.devshed.com/c-programming-42/wstring-to-string-444006.html

std::wstring wide( L"Wide" ); 
std::string str( wide.begin(), wide.end() );

// Will print no problemo!
std::cout << str << std::endl;

Beware that there is no character set conversion going on here at all. What this does is simply to assign each iterated wchar_t to a char - a truncating conversion. It uses the std::string c'tor:

template< class InputIt >
basic_string( InputIt first, InputIt last,
              const Allocator& alloc = Allocator() );

As stated in comments:

values 0-127 are identical in virtually every encoding, so truncating values that are all less than 127 results in the same text. Put in a chinese character and you'll see the failure.

-

the values 128-255 of windows codepage 1252 (the Windows English default) and the values 128-255 of unicode are mostly the same, so if that's teh codepage you're using most of those characters should be truncated to the correct values. (I totally expected á and õ to work, I know our code at work relies on this for é, which I will soon fix)

And note that code points in the range 0x80 - 0x9F in Win1252 will not work. This includes , œ, ž, Ÿ, ...

How to solve PHP error 'Notice: Array to string conversion in...'

You are using <input name='C[]' in your HTML. This creates an array in PHP when the form is sent.

You are using echo $_POST['C']; to echo that array - this will not work, but instead emit that notice and the word "Array".

Depending on what you did with the rest of the code, you should probably use echo $_POST['C'][0];

How to find a value in an excel column by vba code Cells.Find

Just use

Dim Cell As Range
Columns("B:B").Select
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    'do it something

Else
    'do it another thing
End If

What does "xmlns" in XML mean?

It means XML namespace.

Basically, every element (or attribute) in XML belongs to a namespace, a way of "qualifying" the name of the element.

Imagine you and I both invent our own XML. You invent XML to describe people, I invent mine to describe cities. Both of us include an element called name. Yours refers to the person’s name, and mine to the city name—OK, it’s a little bit contrived.

<person>
    <name>Rob</name>
    <age>37</age>
    <homecity>
        <name>London</name>
        <lat>123.000</lat>
        <long>0.00</long>
    </homecity>
</person>

If our two XMLs were combined into a single document, how would we tell the two names apart? As you can see above, there are two name elements, but they both have different meanings.

The answer is that you and I would both assign a namespace to our XML, which we would make unique:

<personxml:person xmlns:personxml="http://www.your.example.com/xml/person"
                  xmlns:cityxml="http://www.my.example.com/xml/cities">
    <personxml:name>Rob</personxml:name>
    <personxml:age>37</personxml:age>
    <cityxml:homecity>
        <cityxml:name>London</cityxml:name>
        <cityxml:lat>123.000</cityxml:lat>
        <cityxml:long>0.00</cityxml:long>
    </cityxml:homecity>
</personxml:person>

Now we’ve fully qualified our XML, there is no ambiguity as to what each name element means. All of the tags that start with personxml: are tags belonging to your XML, all the ones that start with cityxml: are mine.

There are a few points to note:

  • If you exclude any namespace declarations, things are considered to be in the default namespace.

  • If you declare a namespace without the identifier, that is, xmlns="http://somenamespace", rather than xmlns:rob="somenamespace", it specifies the default namespace for the document.

  • The actual namespace itself, often a IRI, is of no real consequence. It should be unique, so people tend to choose a IRI/URI that they own, but it has no greater meaning than that. Sometimes people will place the schema (definition) for the XML at the specified IRI, but that is a convention of some people only.

  • The prefix is of no consequence either. The only thing that matters is what namespace the prefix is defined as. Several tags beginning with different prefixes, all of which map to the same namespace are considered to be the same.

    For instance, if the prefixes personxml and mycityxml both mapped to the same namespace (as in the snippet below), then it wouldn't matter if you prefixed a given element with personxml or mycityxml, they'd both be treated as the same thing by an XML parser. The point is that an XML parser doesn't care what you've chosen as the prefix, only the namespace it maps too. The prefix is just an indirection pointing to the namespace.

    <personxml:person 
         xmlns:personxml="http://example.com/same/url"
         xmlns:mycityxml="http://example.com/same/url" />
    
  • Attributes can be qualified but are generally not. They also do not inherit their namespace from the element they are on, as opposed to elements (see below).

Also, element namespaces are inherited from the parent element. In other words I could equally have written the above XML as

<person xmlns="http://www.your.example.com/xml/person">
    <name>Rob</name>
    <age>37</age>
    <homecity xmlns="http://www.my.example.com/xml/cities">
        <name>London</name>
        <lat>123.000</lat>
        <long>0.00</long>
    </homecity>
</person>

Paste MS Excel data to SQL Server

Excel

  1. In Excel, highlight and copy the data you want to paste into SQL.

SQL

  1. Create the table with the desired column names and give you table a name. *Make sure Identity Specification is Yes, so it will auto increment your Identity column.
  2. Find your table, and right click on it and choose Edit Top 200 Rows from the dialog-box.
  3. Right click on the empty row with the * sign and select paste from the dialog-box

enter image description here

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

To simplify to operation, we can use the below command to reinstall version 2:

brew install python@2

Then on my mac, it looks as below:

? python -V
Python 2.7.10

? python2 -V
Python 2.7.14

? python3 -V
Python 3.6.5

? pip2 -V
pip 9.0.3 from /usr/local/lib/python2.7/site-packages (python 2.7)

? pip3 -V
pip 9.0.3 from /usr/local/lib/python3.6/site-packages (python 3.6)

? pip --version
pip 9.0.3 from /usr/local/lib/python2.7/site-packages (python 2.7)

Are arrays passed by value or passed by reference in Java?

Everything in Java is passed by value .

In the case of the array the reference is copied into a new reference, but remember that everything in Java is passed by value .

Take a look at this interesting article for further information ...

Checking Value of Radio Button Group via JavaScript?

Without loop:

document.getElementsByName('gender').reduce(function(value, checkable) {
    if(checkable.checked == true) 
        value = checkable.value; 
    return value;
}, '');

reduce is just a function that will feed sequentially array elements to second argument of callback, and previously returned function to value, while for the first run, it will use value of second argument.

The only minus of this approach is that reduce will traverse every element returned by getElementsByName even after it have found selected radio button.

Android Split string

You might also want to consider the Android specific TextUtils.split() method.

The difference between TextUtils.split() and String.split() is documented with TextUtils.split():

String.split() returns [''] when the string to be split is empty. This returns []. This does not remove any empty strings from the result.

I find this a more natural behavior. In essence TextUtils.split() is just a thin wrapper for String.split(), dealing specifically with the empty-string case. The code for the method is actually quite simple.

Use a content script to access the page context variables and functions

If you wish to inject pure function, instead of text, you can use this method:

_x000D_
_x000D_
function inject(){_x000D_
    document.body.style.backgroundColor = 'blue';_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var actualCode = "("+inject+")()"; _x000D_
_x000D_
document.documentElement.setAttribute('onreset', actualCode);_x000D_
document.documentElement.dispatchEvent(new CustomEvent('reset'));_x000D_
document.documentElement.removeAttribute('onreset');
_x000D_
_x000D_
_x000D_

And you can pass parameters (unfortunatelly no objects and arrays can be stringifyed) to the functions. Add it into the baretheses, like so:

_x000D_
_x000D_
function inject(color){_x000D_
    document.body.style.backgroundColor = color;_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var color = 'yellow';_x000D_
var actualCode = "("+inject+")("+color+")"; 
_x000D_
_x000D_
_x000D_

How do I make text bold in HTML?

Another option is to do it via CSS ...

E.g. 1

<span style="font-weight: bold;">Hello stackoverflow!</span>

E.g. 2

<style type="text/css">
    #text
    {
        font-weight: bold;
    }
</style>

<div id="text">
    Hello again!
</div>

'npm' is not recognized as internal or external command, operable program or batch file

Don't forget to reboot your computer after installing node! That one got me.

PHP CURL Enable Linux

if you have used curl above the page and below your html is present and unfortunately your html page is not able to view then just enable your curl. But in order to check CURL is enable or not in php you need to write following code:

echo 'Curl: ', function_exists('curl_version') ? 'Enabled' : 'Disabled';

Recyclerview and handling different type of row inflation

The trick is to create subclasses of ViewHolder and then cast them.

public class GroupViewHolder extends RecyclerView.ViewHolder {
    TextView mTitle;
    TextView mContent;
    public GroupViewHolder(View itemView) {
        super (itemView);
        // init views...
    }
}

public class ImageViewHolder extends RecyclerView.ViewHolder {
    ImageView mImage;
    public ImageViewHolder(View itemView) {
        super (itemView);
        // init views...
    }
}

private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;  

And then, at runtime do something like this:

@Override
public int getItemViewType(int position) {
    // here your custom logic to choose the view type
    return position == 0 ? TYPE_IMAGE : TYPE_GROUP;
}

@Override
public void onBindViewHolder (ViewHolder viewHolder, int i) {

    switch (viewHolder.getItemViewType()) {

        case TYPE_IMAGE:
            ImageViewHolder imageViewHolder = (ImageViewHolder) viewHolder;
            imageViewHolder.mImage.setImageResource(...);
            break;

        case TYPE_GROUP:
            GroupViewHolder groupViewHolder = (GroupViewHolder) viewHolder;
            groupViewHolder.mContent.setText(...)
            groupViewHolder.mTitle.setText(...);
            break;
    }
}

Hope it helps.

calling javascript function on OnClientClick event of a Submit button

OnClientClick="SomeMethod()" event of that BUTTON, it return by default "true" so after that function it do postback

for solution use

//use this code in BUTTON  ==>   OnClientClick="return SomeMethod();"

//and your function like this
<script type="text/javascript">
  function SomeMethod(){
    // put your code here 
    return false;
  }
</script>

2D arrays in Python

x=list()
def enter(n):
    y=list()
    for i in  range(0,n):
        y.append(int(input("Enter ")))
    return y
for i in range(0,2):
    x.insert(i,enter(2))
print (x)

here i made function to create 1-D array and inserted into another array as a array member. multiple 1-d array inside a an array, as the value of n and i changes u create multi dimensional arrays

Resize image with javascript canvas (smoothly)

While some of those code-snippets are short and working, they aren't trivial to follow and understand.

As i am not a fan of "copy-paste" from stack-overflow, i would like developers to understand the code they are push into they software, hope you'll find the below useful.

DEMO: Resizing images with JS and HTML Canvas Demo fiddler.

You may find 3 different methods to do this resize, that will help you understand how the code is working and why.

https://jsfiddle.net/1b68eLdr/93089/

Full code of both demo, and TypeScript method that you may want to use in your code, can be found in the GitHub project.

https://github.com/eyalc4/ts-image-resizer

This is the final code:

export class ImageTools {
base64ResizedImage: string = null;

constructor() {
}

ResizeImage(base64image: string, width: number = 1080, height: number = 1080) {
    let img = new Image();
    img.src = base64image;

    img.onload = () => {

        // Check if the image require resize at all
        if(img.height <= height && img.width <= width) {
            this.base64ResizedImage = base64image;

            // TODO: Call method to do something with the resize image
        }
        else {
            // Make sure the width and height preserve the original aspect ratio and adjust if needed
            if(img.height > img.width) {
                width = Math.floor(height * (img.width / img.height));
            }
            else {
                height = Math.floor(width * (img.height / img.width));
            }

            let resizingCanvas: HTMLCanvasElement = document.createElement('canvas');
            let resizingCanvasContext = resizingCanvas.getContext("2d");

            // Start with original image size
            resizingCanvas.width = img.width;
            resizingCanvas.height = img.height;


            // Draw the original image on the (temp) resizing canvas
            resizingCanvasContext.drawImage(img, 0, 0, resizingCanvas.width, resizingCanvas.height);

            let curImageDimensions = {
                width: Math.floor(img.width),
                height: Math.floor(img.height)
            };

            let halfImageDimensions = {
                width: null,
                height: null
            };

            // Quickly reduce the dize by 50% each time in few iterations until the size is less then
            // 2x time the target size - the motivation for it, is to reduce the aliasing that would have been
            // created with direct reduction of very big image to small image
            while (curImageDimensions.width * 0.5 > width) {
                // Reduce the resizing canvas by half and refresh the image
                halfImageDimensions.width = Math.floor(curImageDimensions.width * 0.5);
                halfImageDimensions.height = Math.floor(curImageDimensions.height * 0.5);

                resizingCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                    0, 0, halfImageDimensions.width, halfImageDimensions.height);

                curImageDimensions.width = halfImageDimensions.width;
                curImageDimensions.height = halfImageDimensions.height;
            }

            // Now do final resize for the resizingCanvas to meet the dimension requirments
            // directly to the output canvas, that will output the final image
            let outputCanvas: HTMLCanvasElement = document.createElement('canvas');
            let outputCanvasContext = outputCanvas.getContext("2d");

            outputCanvas.width = width;
            outputCanvas.height = height;

            outputCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                0, 0, width, height);

            // output the canvas pixels as an image. params: format, quality
            this.base64ResizedImage = outputCanvas.toDataURL('image/jpeg', 0.85);

            // TODO: Call method to do something with the resize image
        }
    };
}}

How to use ternary operator in razor (specifically on HTML attributes)?

You should be able to use the @() expression syntax:

<a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a>

setBackground vs setBackgroundDrawable (Android)

i know this is an old question but i have a similar situation ,and my solution was

button.setBackgroundResource( R.drawable.ic_button );
Drawable d = button.getBackground();

and then you can play with the "Drawable", applying color filters, etc

Log record changes in SQL server in an audit table

Hey It's very simple see this

@OLD_GUEST_NAME = d.GUEST_NAME from deleted d;

this variable will store your old deleted value and then you can insert it where you want.

for example-

Create trigger testupdate on test for update, delete
  as
declare @tableid varchar(50);
declare @testid varchar(50);
declare @newdata varchar(50);
declare @olddata varchar(50);


select @tableid = count(*)+1 from audit_test
select @testid=d.tableid from inserted d;
select @olddata = d.data from deleted d;
select @newdata = i.data from inserted i;

insert into audit_test (tableid, testid, olddata, newdata) values (@tableid, @testid, @olddata, @newdata)

go

Callback functions in Java

A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.

Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.

How do I space out the child elements of a StackPanel?

My approach inherits StackPanel.

Usage:

<Controls:ItemSpacer Grid.Row="2" Orientation="Horizontal" Height="30" CellPadding="15,0">
    <Label>Test 1</Label>
    <Label>Test 2</Label>
    <Label>Test 3</Label>
</Controls:ItemSpacer>

All that's needed is the following short class:

using System.Windows;
using System.Windows.Controls;
using System;

namespace Controls
{
    public class ItemSpacer : StackPanel
    {
        public static DependencyProperty CellPaddingProperty = DependencyProperty.Register("CellPadding", typeof(Thickness), typeof(ItemSpacer), new FrameworkPropertyMetadata(default(Thickness), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnCellPaddingChanged));
        public Thickness CellPadding
        {
            get
            {
                return (Thickness)GetValue(CellPaddingProperty);
            }
            set
            {
                SetValue(CellPaddingProperty, value);
            }
        }
        private static void OnCellPaddingChanged(DependencyObject Object, DependencyPropertyChangedEventArgs e)
        {
            ((ItemSpacer)Object).SetPadding();
        }

        private void SetPadding()
        {
            foreach (UIElement Element in Children)
            {
                (Element as FrameworkElement).Margin = this.CellPadding;
            }
        }

        public ItemSpacer()
        {
            this.LayoutUpdated += PART_Host_LayoutUpdated;
        }

        private void PART_Host_LayoutUpdated(object sender, System.EventArgs e)
        {
            this.SetPadding();
        }
    }
}

How to apply a CSS filter to a background image

All you actually need is "filter":

blur(«WhatEverYouWantInPixels»);"

_x000D_
_x000D_
body {_x000D_
    color: #fff;_x000D_
    font-family: Helvetica, Arial, sans-serif;_x000D_
}_x000D_
_x000D_
#background {_x000D_
    background-image: url('https://cdn2.geckoandfly.com/wp-content/uploads/2018/03/ios-11-3840x2160-4k-5k-beach-ocean-13655.jpg');_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: cover;_x000D_
    width: 100vw;_x000D_
    height: 100vh;_x000D_
    overflow: hidden;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    z-index: -1;_x000D_
_x000D_
    /* START */_x000D_
    /* START */_x000D_
    /* START */_x000D_
    /* START */_x000D_
_x000D_
    /* You can adjust the blur-radius as you'd like */_x000D_
    filter: blur(3px);_x000D_
}
_x000D_
<div id="background"></div>_x000D_
_x000D_
<p id="randomContent">Lorem Ipsum</p>
_x000D_
_x000D_
_x000D_

Difference between Select Unique and Select Distinct

SELECT UNIQUE is old syntax supported by Oracle's flavor of SQL. It is synonymous with SELECT DISTINCT.

Use SELECT DISTINCT because this is standard SQL, and SELECT UNIQUE is non-standard, and in database brands other than Oracle, SELECT UNIQUE may not be recognized at all.

Getting full-size profile picture

As noted above, it appears that the cover photo of the profile album is a hi-res profile picture. I would check for the album type of "profile" rather than the name though, as the name may not be consistent across different languages, but the type should be.

To reduce the number of requests / parsing, you can use this fql: "select cover_object_id from album where type='profile' and owner = user_id"

And then you can construct the image url with: "https://graph.facebook.com/" + cover_object_id + "/picture&type=normal&access_token=" + access_token

Looks like there is no "large" type for this image, but the "normal" one is still quite large.

As noted above, this photo may be less accessible than the public profile picture. You need the user_photos or friend_photos permission to access it.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

I faced the same issue while submitting the app using Xcode 4.6. It does not recognise the icons with dimension 120x120, 58x58, 29x29, etc. So when I tried to add these icons into the info.plist and submit the app for review, Xcode 4.6 did not allow me to do so. On submitting the app without the above icons, I got a mail saying -

"Your delivery was successful, but you may wish to correct the following issues in your next delivery: Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format."

Since, it was recommended and not necessary, I submitted the app anyhow. I added the above recommended icons to the bundle but did not specify them in the Info.plist. I got the same mail again. This time I ignored it and to my surprise the app was accepted.

I wanted my app to run on iOS 5 and above and therefore, I had to use Xcode 4.6 and not the latest Xcode 5 which properly allows only apps for iOS7 and above only.

UPDATE:

NOTE: "Starting February 1st 2014 new apps and app updates submitted to the App Store must be built with Xcode 5 and iOS 7 SDK". https://developer.apple.com/news/?id=12172013a#top

Thus, this scenario will be invalid in future.

Maven: repository element was not specified in the POM inside distributionManagement?

For me, this was something as simple as a missing version for my artifact - "1.1-SNAPSHOT"

ImportError: No module named psycopg2

For python3 on ubuntu, this worked for me:

$sudo apt-get update
$sudo apt-get install libpq-dev
$sudo pip3 install psycopg2-binary

How do I get git to default to ssh and not https for new repositories

  • GitHub

    git config --global url.ssh://[email protected]/.insteadOf https://github.com/
    
  • BitBucket

    git config --global url.ssh://[email protected]/.insteadOf https://bitbucket.org/
    

That tells git to always use SSH instead of HTTPS when connecting to GitHub/BitBucket, so you'll authenticate by certificate by default, instead of being prompted for a password.

A hex viewer / editor plugin for Notepad++?

The hex editor plugin mentioned by ellak still works, but it seems that you need the TextFX Characters plugin as well.

I initially installed only the hex plugin and Notepad++ would no longer pop up; instead it started eating memory (killed it at 1.2 GB). I removed it again and for other reasons installed the TextFX plugin (based on Find multiple lines in Notepad++)

Out of curiosity I installed the hex plugin again and now it works.

Note that this is on a fresh install of Windows 7 64 bit.

pip install gives error: Unable to find vcvarsall.bat

I appreciate this might not be the answer to resolving on 3.4 but I tried a huge variety of things to fix this on 3.4 and thought this might be useful if someone is time pressed or doesn't have the know-how to correct it (in my case, work demands).

With exactly the same setup, I found that my installation problems only happened with Python 3.4. When I changed to 2.7, all my issues seemed to be resolved.

We have a rather overzealous security setup though so I'm going to try the same on my home version (still 3.4) and see if I have any more joy. My inclination is that my VS version has somehow been restricted and the answers above should help. If I find anything more tonight I'll add further detail.

This is my first reply, not the most technical I'm afraid!

How do I create an array of strings in C?

I was missing somehow more dynamic array of strings, where amount of strings could be varied depending on run-time selection, but otherwise strings should be fixed.

I've ended up of coding code snippet like this:

#define INIT_STRING_ARRAY(...)          \
    {                                   \
        char* args[] = __VA_ARGS__;     \
        ev = args;                      \
        count = _countof(args);         \
    }

void InitEnumIfAny(String& key, CMFCPropertyGridProperty* item)
{
    USES_CONVERSION;
    char** ev = nullptr;
    int count = 0;

    if( key.Compare("horizontal_alignment") )
        INIT_STRING_ARRAY( { "top", "bottom" } )

    if (key.Compare("boolean"))
        INIT_STRING_ARRAY( { "yes", "no" } )

    if( ev == nullptr )
        return;

    for( int i = 0; i < count; i++)
        item->AddOption(A2T(ev[i]));

    item->AllowEdit(FALSE);
}

char** ev picks up pointer to array strings, and count picks up amount of strings using _countof function. (Similar to sizeof(arr) / sizeof(arr[0])).

And there is extra Ansi to unicode conversion using A2T macro, but that might be optional for your case.

Calling a Function defined inside another function in Javascript

You are not calling the function inner, just defining it.

function outer() { 
    function inner() {
        alert("hi");
    }

    inner(); //Call the inner function

}

MetadataException when using Entity Framework Entity Connection

I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.

Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.

To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

How to represent empty char in Java Character class

String before = EMPTY_SPACE+TAB+"word"+TAB+EMPTY_SPACE

Where EMPTY_SPACE = " " (this is String) TAB = '\t' (this is Character)

String after = before.replaceAll(" ", "").replace('\t', '\0') means after = "word"

java.net.BindException: Address already in use: JVM_Bind <null>:80

Make sure /webapps/ROOT file is there and it has all the icons, WEB-INF, and index.jsp is in the folder.

When you startup Tomcat, it will run this code in <Tomcat-Directory>/conf/web.xml directory:

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

The location of index.jsp is in <Tomcat-Directory>/webapps/ROOT/index.jsp

Also, try running tomcat from the /bin directory using ./catalina.sh start instead of ./startup.sh. For some reason, ./startup.sh isn't as reliable.

Angular 2 Cannot find control with unspecified name attribute on formArrays

For me, I was trying to add [formGroupName]="i" and/or formControlName and forgetting to specify the parent formArrayName. Pay attention to your form group tree.

Can't access Eclipse marketplace

Here's the solution,

If you are a constant proxy changer like me for various reasons (university, home , workplace and so on..) you are mostly likely to get this error due to improper configuration of connection settings in the eclipse IDE. all you have to do it play around with the current settings and get it to working state. Here's how,,

1. GO TO

Window-> Preferences -> General -> Network Connection.

2. Change the Settings

Active Provider-> Manual-> and check---> HTTP, HTTPS and SOCKS

If your active provider is already set to Manual, try restoring the default (native)


That's all, restart Eclipse and you are good to go!


CodeIgniter Active Record - Get number of returned rows

$this->db->select('count(id) as rows');
$this->db->from('table_name');
$this->db->where('active',1);
$query = $this->db->get();
foreach($query->result() as $r)
{
   return $r->rows;
}

Connection refused on docker container

In Docker Quickstart Terminal run following command: $ docker-machine ip 192.168.99.100

Is there a JavaScript function that can pad a string to get to a determined length?

I think its better to avoid recursion because its costly.

_x000D_
_x000D_
function padLeft(str,size,padwith) {_x000D_
 if(size <= str.length) {_x000D_
        // not padding is required._x000D_
  return str;_x000D_
 } else {_x000D_
        // 1- take array of size equal to number of padding char + 1. suppose if string is 55 and we want 00055 it means we have 3 padding char so array size should be 3 + 1 (+1 will explain below)_x000D_
        // 2- now join this array with provided padding char (padwith) or default one ('0'). so it will produce '000'_x000D_
        // 3- now append '000' with orginal string (str = 55), will produce 00055_x000D_
_x000D_
        // why +1 in size of array? _x000D_
        // it is a trick, that we are joining an array of empty element with '0' (in our case)_x000D_
        // if we want to join items with '0' then we should have at least 2 items in the array to get joined (array with single item doesn't need to get joined)._x000D_
        // <item>0<item>0<item>0<item> to get 3 zero we need 4 (3+1) items in array   _x000D_
  return Array(size-str.length+1).join(padwith||'0')+str_x000D_
 }_x000D_
}_x000D_
_x000D_
alert(padLeft("59",5) + "\n" +_x000D_
     padLeft("659",5) + "\n" +_x000D_
     padLeft("5919",5) + "\n" +_x000D_
     padLeft("59879",5) + "\n" +_x000D_
     padLeft("5437899",5));
_x000D_
_x000D_
_x000D_

Setting Oracle 11g Session Timeout

Check applications connection Pool settings, rather than altering any session timout settings on the oracle db. It's normal that they time out.

Have a look here: http://grails.org/doc/1.0.x/guide/3.%20Configuration.html#3.3%20The%20DataSource

Are you sure that you have set the "pooled" parameter correctly?

Greetings, Lars


EDIT:
Your config seems ok on first glimpse. I came across this issue today. Maybe it is related to your pain:
"Infinite loop of exceptions if the application is started when the database is down for maintenance"

How do I expire a PHP session after 30 minutes?

Just Store the current time and If it exceeds 30 minutes by comparing then destroy the current session.

File Upload to HTTP server in iphone programming

I have made a lightweight backup method for the Mobile-AppSales app available at github

I wrote about it here http://memention.com/blog/2009/11/22/Lightweight-backup.html

Look for the - (void)startUpload method in ReportManager.m

Difference between 'cls' and 'self' in Python classes?

cls implies that method belongs to the class while self implies that the method is related to instance of the class,therefore member with cls is accessed by class name where as the one with self is accessed by instance of the class...it is the same concept as static member and non-static members in java if you are from java background.

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

how to open a page in new tab on button click in asp.net?

Per Open a URL in a new tab (and not a new window) using JavaScript

Nothing an author can do can choose to open in a new tab instead of a new window.

The browser decides between opening a new tab or opening a new window. You cannot control this as a developer.

Mime type for WOFF fonts?

As of February 2017, RFC8081 is the proposed standard. It defines a top-level media type for fonts, therefore the standard media type for WOFF and WOFF2 are as follows:

font/woff
font/woff2

"Unable to launch the IIS Express Web server" error

open command prompt as administrator then execute this command :

netsh http show urlacl

you will see the url you have added before now you should execute this command :

netsh http delete urlacl url=http://+:36899/ user=Everyone

please check the url from list when using :

(netsh http show urlacl)

public static const in TypeScript

Just simply 'export' variable and 'import' in your class

export var GOOGLE_API_URL = 'https://www.googleapis.com/admin/directory/v1';

// default err string message
export var errStringMsg = 'Something went wrong';

Now use it as,

import appConstants = require('../core/AppSettings');
console.log(appConstants.errStringMsg);
console.log(appConstants.GOOGLE_API_URL);

Linking a qtDesigner .ui file to python/pyqt?

You can convert your .ui files to an executable python file using the below command..

pyuic4 -x form1.ui > form1.py

Now you can straightaway execute the python file as

python3(whatever version) form1.py

You can import this file and you can use it.

How do you reverse a string in place in JavaScript?

I guess, this will work for you

function reverse(str){
    str = str.split("").reverse().join("").split(" ").reverse().join(" ");
    console.log(str)
}

SQL Server: converting UniqueIdentifier to string in a case statement

It is possible to use the convert function here, but 36 characters are enough to hold the unique identifier value:

convert(nvarchar(36), requestID) as requestID

Access files stored on Amazon S3 through web browser

Filestash is the perfect tool for that:

  1. login to your bucket from https://www.filestash.app/s3-browser.html:

enter image description here

  1. create a shared link:

enter image description here

  1. Share it with the world

Also Filestash is open source. (Disclaimer: I am the author)

Mongoose's find method with $or condition does not work properly

I implore everyone to use Mongoose's query builder language and promises instead of callbacks:

User.find().or([{ name: param }, { nickname: param }])
    .then(users => { /*logic here*/ })
    .catch(error => { /*error logic here*/ })

Read more about Mongoose Queries.

What exactly is RESTful programming?

REST is an architectural pattern and style of writing distributed applications. It is not a programming style in the narrow sense.

Saying you use the REST style is similar to saying that you built a house in a particular style: for example Tudor or Victorian. Both REST as an software style and Tudor or Victorian as a home style can be defined by the qualities and constraints that make them up. For example REST must have Client Server separation where messages are self-describing. Tudor style homes have Overlapping gables and Roofs that are steeply pitched with front facing gables. You can read Roy's dissertation to learn more about the constraints and qualities that make up REST.

REST unlike home styles has had a tough time being consistently and practically applied. This may have been intentional. Leaving its actual implementation up to the designer. So you are free to do what you want so as long as you meet the constraints set out in the dissertation you are creating REST Systems.

Bonus:

The entire web is based on REST (or REST was based on the web). Therefore as a web developer you might want aware of that although it's not necessary to write good web apps.

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

Updated Answer

Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)

Instead, the best approach would be to:

  1. Allow each panel to toggle individually
  2. Then, enforce the accordion behavior manually where appropriate.

To allow each panel to toggle individually, on the data-toggle="collapse" element, set the data-target attribute to the .collapse panel ID selector (instead of setting the data-parent attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.

Roughly, each panel should look like this:

<div class="panel panel-default">
   <div class="panel-heading">
         <h4 class="panel-title"
             data-toggle="collapse" 
             data-target="#collapseOne">
             Collapsible Group Item #1
         </h4>
    </div>
    <div id="collapseOne" 
         class="panel-collapse collapse">
        <div class="panel-body"></div>
    </div>
</div>

To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:

$('#accordion').on('show.bs.collapse', function () {
    if (active) $('#accordion .in').collapse('hide');
});

Then use show and hide to toggle the visibility of each of the panels and data-toggle to enable and disable the controls.

$('#collapse-init').click(function () {
    if (active) {
        active = false;
        $('.panel-collapse').collapse('show');
        $('.panel-title').attr('data-toggle', '');
        $(this).text('Enable accordion behavior');
    } else {
        active = true;
        $('.panel-collapse').collapse('hide');
        $('.panel-title').attr('data-toggle', 'collapse');
        $(this).text('Disable accordion behavior');
    }
});

Working demo in jsFiddle

What Vim command(s) can be used to quote/unquote words?

To wrap in single quotes (for example) ciw'<C-r>"'<esc> works, but repeat won't work. Try:

ciw'<C-r><C-o>"'<esc>

This puts the contents of the default register "literally". Now you can press . on any word to wrap it in quotes. To learn more see :h[elp] i_ctrl-r and more about text objects at :h text-objects

Source: http://vimcasts.org/episodes/pasting-from-insert-mode/

Show div on scrollDown after 800px

SCROLLBARS & $(window).scrollTop()

What I have discovered is that calling such functionality as in the solution thankfully provided above, (there are many more examples of this throughout this forum - which all work well) is only successful when scrollbars are actually visible and operating.

If (as I have maybe foolishly tried), you wish to implement such functionality, and you also wish to, shall we say, implement a minimalist "clean screen" free of scrollbars, such as at this discussion, then $(window).scrollTop() will not work.

It may be a programming fundamental, but thought I'd offer the heads up to any fellow newbies, as I spent a long time figuring this out.

If anyone could offer some advice as to how to overcome this or a little more insight, feel free to reply, as I had to resort to show/hide onmouseover/mouseleave instead here

Live long and program, CollyG.

Adding elements to a collection during iteration

There are two issues here:

The first issue is, adding to an Collection after an Iterator is returned. As mentioned, there is no defined behavior when the underlying Collection is modified, as noted in the documentation for Iterator.remove:

... The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

The second issue is, even if an Iterator could be obtained, and then return to the same element the Iterator was at, there is no guarantee about the order of the iteratation, as noted in the Collection.iterator method documentation:

... There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee).

For example, let's say we have the list [1, 2, 3, 4].

Let's say 5 was added when the Iterator was at 3, and somehow, we get an Iterator that can resume the iteration from 4. However, there is no guarentee that 5 will come after 4. The iteration order may be [5, 1, 2, 3, 4] -- then the iterator will still miss the element 5.

As there is no guarantee to the behavior, one cannot assume that things will happen in a certain way.

One alternative could be to have a separate Collection to which the newly created elements can be added to, and then iterating over those elements:

Collection<String> list = Arrays.asList(new String[]{"Hello", "World!"});
Collection<String> additionalList = new ArrayList<String>();

for (String s : list) {
    // Found a need to add a new element to iterate over,
    // so add it to another list that will be iterated later:
    additionalList.add(s);
}

for (String s : additionalList) {
    // Iterate over the elements that needs to be iterated over:
    System.out.println(s);
}

Edit

Elaborating on Avi's answer, it is possible to queue up the elements that we want to iterate over into a queue, and remove the elements while the queue has elements. This will allow the "iteration" over the new elements in addition to the original elements.

Let's look at how it would work.

Conceptually, if we have the following elements in the queue:

[1, 2, 3, 4]

And, when we remove 1, we decide to add 42, the queue will be as the following:

[2, 3, 4, 42]

As the queue is a FIFO (first-in, first-out) data structure, this ordering is typical. (As noted in the documentation for the Queue interface, this is not a necessity of a Queue. Take the case of PriorityQueue which orders the elements by their natural ordering, so that's not FIFO.)

The following is an example using a LinkedList (which is a Queue) in order to go through all the elements along with additional elements added during the dequeing. Similar to the example above, the element 42 is added when the element 2 is removed:

Queue<Integer> queue = new LinkedList<Integer>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);

while (!queue.isEmpty()) {
    Integer i = queue.remove();
    if (i == 2)
        queue.add(42);

    System.out.println(i);
}

The result is the following:

1
2
3
4
42

As hoped, the element 42 which was added when we hit 2 appeared.

What does .class mean in Java?

I think the key here is understanding the difference between a Class and an Object. An Object is an instance of a Class. But in a fully object-oriented language, a Class is also an Object. So calling .class gets the reference to the Class object of that Class, which can then be manipulated.

How to declare a variable in MySQL?

There are mainly three types of variables in MySQL:

  1. User-defined variables (prefixed with @):

    You can access any user-defined variable without declaring it or initializing it. If you refer to a variable that has not been initialized, it has a value of NULL and a type of string.

    SELECT @var_any_var_name
    

    You can initialize a variable using SET or SELECT statement:

    SET @start = 1, @finish = 10;    
    

    or

    SELECT @start := 1, @finish := 10;
    
    SELECT * FROM places WHERE place BETWEEN @start AND @finish;
    

    User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL value.

    User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients.

    They can be used in SELECT queries using Advanced MySQL user variable techniques.

  2. Local Variables (no prefix) :

    Local variables needs to be declared using DECLARE before accessing it.

    They can be used as local variables and the input parameters inside a stored procedure:

    DELIMITER //
    
    CREATE PROCEDURE sp_test(var1 INT) 
    BEGIN   
        DECLARE start  INT unsigned DEFAULT 1;  
        DECLARE finish INT unsigned DEFAULT 10;
    
        SELECT  var1, start, finish;
    
        SELECT * FROM places WHERE place BETWEEN start AND finish; 
    END; //
    
    DELIMITER ;
    
    CALL sp_test(5);
    

    If the DEFAULT clause is missing, the initial value is NULL.

    The scope of a local variable is the BEGIN ... END block within which it is declared.

  3. Server System Variables (prefixed with @@):

    The MySQL server maintains many system variables configured to a default value. They can be of type GLOBAL, SESSION or BOTH.

    Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.

    To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT @@var_name.

    SHOW VARIABLES LIKE '%wait_timeout%';
    
    SELECT @@sort_buffer_size;
    

    They can be set at server startup using options on the command line or in an option file. Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION:

    -- Syntax to Set value to a Global variable:
    SET GLOBAL sort_buffer_size=1000000;
    SET @@global.sort_buffer_size=1000000;
    
    -- Syntax to Set value to a Session variable:
    SET sort_buffer_size=1000000;
    SET SESSION sort_buffer_size=1000000;
    SET @@sort_buffer_size=1000000;
    SET @@local.sort_buffer_size=10000;
    

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

I had similar problem when I tried to build a signed apk for my app.

Strange, it happened only when I wanted to build a release apk, while on debug apk everything worked OK.

Finally, looking on this thread, I checked for support library duplications in build.gradle and removed any duplications but this wasn't enough..

I had to do clean project and only then finally I've got it to work.

How to use EditText onTextChanged event when I press the number?

put the logic in

afterTextChanged(Editable s) {
    string str = s.toString()
    // use the string str
}

documentation on TextWatcher

How can I make Jenkins CI with Git trigger on pushes to master?

For GitLab, use these steps:

  1. Go to your project's settings ? Web hooks
  2. Enter the "Build Now" URL from your Jenkins project as a Push Event URL:

    http://server.com/jenkins/job/project_name/build?delay=0sec for example

  3. Click Add Web Hook and then test hook

Then any time you commit to the repository, the web hook is triggered and a build is created. Be sure to set your Jenkins workspace to delete workspace before each build so you get a fresh copy of the new code.

Call a Javascript function every 5 seconds continuously

You can use setInterval(), the arguments are the same.

const interval = setInterval(function() {
   // method to be executed;
 }, 5000);

clearInterval(interval); // thanks @Luca D'Amico

How do I parse command line arguments in Java?

Argparse4j is best I have found. It mimics Python's argparse libary which is very convenient and powerful.

how do I change text in a label with swift?

Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:

self.simpleLabel.text = "message"

Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.

jQuery: using a variable as a selector

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

Safest way to convert float to integer in python?

df['Column_Name']=df['Column_Name'].astype(int)

AngularJS accessing DOM elements inside directive template

You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.

Here is the directive:

app.directive("ngScopeElement", function () {
  var directiveDefinitionObject = {

    restrict: "A",

    compile: function compile(tElement, tAttrs, transclude) {
      return {
          pre: function preLink(scope, iElement, iAttrs, controller) {
            scope[iAttrs.ngScopeElement] = iElement;
          }
        };
    }
  };

  return directiveDefinitionObject;
});

Usage:

app.directive("myDirective", function() {
    return {
        template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
        link: function(scope, element, attrs) {
            scope.list[0] // scope.list is the jqlite element, 
                          // scope.list[0] is the native dom element
        }
    }
});

Some remarks:

  • Due to the compile and link order for nested directives you can only access scope.list from myDirectives postLink-Function, which you are very likely using anyway
  • ngScopeElement uses a preLink-function, so that directives nested within the element having ng-scope-element can already access scope.list
  • not sure how this behaves performance-wise

mysql stored-procedure: out parameter

You must have use correct signature for input parameter *IN is missing in the below code.

CREATE PROCEDURE my_sqrt(IN input_number INT, OUT out_number FLOAT)

How to have an auto incrementing version number (Visual Studio)?

  • Star in version (like "2.10.3.*") - it is simple, but the numbers are too large

  • AutoBuildVersion - looks great but its dont work on my VS2010.

  • @DrewChapin's script works, but I can not in my studio set different modes for Debug pre-build event and Release pre-build event.

so I changed the script a bit... commamd:

"%CommonProgramFiles(x86)%\microsoft shared\TextTemplating\10.0\TextTransform.exe" -a !!$(ConfigurationName)!1 "$(ProjectDir)Properties\AssemblyInfo.tt"

and script (this works to the "Debug" and "Release" configurations):

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
    int incRevision = 1;
    int incBuild = 1;

    try { incRevision = Convert.ToInt32(this.Host.ResolveParameterValue("","","Debug"));} catch( Exception ) { incBuild=0; }
    try { incBuild = Convert.ToInt32(this.Host.ResolveParameterValue("","","Release")); } catch( Exception ) { incRevision=0; }
    try {
        string currentDirectory = Path.GetDirectoryName(Host.TemplateFile);
        string assemblyInfo = File.ReadAllText(Path.Combine(currentDirectory,"AssemblyInfo.cs"));
        Regex pattern = new Regex("AssemblyVersion\\(\"\\d+\\.\\d+\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
        MatchCollection matches = pattern.Matches(assemblyInfo);
        revision = Convert.ToInt32(matches[0].Groups["revision"].Value) + incRevision;
        build = Convert.ToInt32(matches[0].Groups["build"].Value) + incBuild;
    }
    catch( Exception ) { }
#>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Game engine. Keys: F2 (Debug trace), F4 (Fullscreen), Shift+Arrows (Move view). ")]
[assembly: AssemblyProduct("Game engine")]
[assembly: AssemblyDescription("My engine for game")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © Name 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]

// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("00000000-0000-0000-0000-000000000000")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("0.1.<#= this.revision #>.<#= this.build #>")]
[assembly: AssemblyFileVersion("0.1.<#= this.revision #>.<#= this.build #>")]

<#+
    int revision = 0;
    int build = 0;
#>

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

Instead of exceptions, just use:

if (Build.VERSION.SDK_INT >= 11)

and use

@SuppressLint("NewApi")

to suppress the warnings.

JSONDecodeError: Expecting value: line 1 column 1

in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input

HTML img onclick Javascript

use this simple cod:

    <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}

#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

/* Caption of Modal Image */
#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation */
.modal-content, #caption {  
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {-webkit-transform:scale(0)} 
  to {-webkit-transform:scale(1)}
}

@keyframes zoom {
  from {transform:scale(0)} 
  to {transform:scale(1)}
}

/* The Close Button */
.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
  .modal-content {
    width: 100%;
  }
}
</style>
</head>
<body>

<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>

<img id="myImg" src="img_snow.jpg" alt="Snow" style="width:100%;max-width:300px">

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>

<script>
// Get the modal
var modal = document.getElementById("myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("modal")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() { 
  modal.style.display = "none";
}
</script>

</body>
</html>

this code open and close your photo.

Get the number of rows in a HTML table

In the DOM, a tr element is (implicitly or explicitly) a child of tbody, thead, or tfoot, not a child of table (hence the 0 you got). So a general answer is:

var count = $('#gvPerformanceResult > * > tr').length;

This includes the rows of the table but excludes rows of any inner table.

Maximum number of rows of CSV data in excel sheet

In my memory, excel (versions >= 2007) limits the power 2 of 20: 1.048.576 lines.

Csv is over to this boundary, like ordinary text file. So you will be care of the transfer between two formats.

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

The problem is in the Eclipse Maven support, the related question is here.

Under Eclipse, the java.home variable is set to the JRE that was used to start Eclipse, not the build JRE. The default system JRE from C:\Program Files doesn't include the JDK so tools.jar is not being found.

To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to eclipse.ini (before -vmargs!):

-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll

Then refresh the Maven dependencies (Alt-F5) (Just refreshing the project isn't sufficient).

How can I make my website's background transparent without making the content (images & text) transparent too?

I think what's happening, is that, since the wrapper id is relatively position, it just appears on the same position with the body tag, what you should do, is that you can add a Z-index to the wrapper id.

#wrapper {
margin: auto;
text-align: left;
width: 832px;
position: relative;
padding-top: 27px;
z-index: 99; /* added this line */
 }

This should make layers above the transparent body tag.

Error Importing SSL certificate : Not an X.509 Certificate

Many CAs will provide a cert in PKCS7 format.

According to Oracle documentation, the keytool commmand can handle PKCS#7 but sometimes it fails

The keytool command can import X.509 v1, v2, and v3 certificates, and PKCS#7 formatted certificate chains consisting of certificates of that type. The data to be imported must be provided either in binary encoding format or in printable encoding format (also known as Base64 encoding) as defined by the Internet RFC 1421 standard. In the latter case, the encoding must be bounded at the beginning by a string that starts with -----BEGIN, and bounded at the end by a string that starts with -----END.

If the PKCS7 file can't be imported try to transform it from PKCS7 to X.509:

openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer

Cannot access a disposed object - How to fix?

Stopping the timer doesn't mean that it won't be called again, depending on when you stop the timer, the timer_tick may still be queued on the message loop for the form. What will happen is that you'll get one more tick that you may not be expecting. What you can do is in your timer_tick, check the Enabled property of your timer before executing the Timer_Tick method.

Android: how to create Switch case from this?

@Override
public void onClick(View v)
{
    switch (v.getId())
    {
        case R.id.:

            break;
        case R.id.:

            break;
        default:
            break;
    }
}

Android studio takes too much memory

I'm currently running Android Studio on Windows 8.1 machine with 6 gigs of RAM.

I found that disabling VCS in android studio and using an external program to handle VCS helped a lot. You can disable VCS by going to File->Settings->Plugins and disable the following:

  • CVS Integration
  • Git Integration
  • GitHub
  • Google Cloud Testing
  • Google Cloud Tools Core
  • Google Cloud Tools for Android Studio
  • hg4idea
  • Subversion Integration
  • Mercurial Integration
  • TestNG-J

Generate JSON string from NSDictionary in iOS

You can pass array or dictionary. Here, I am taking NSMutableDictionary.

NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"a" forKey:@"b"];
[contentDictionary setValue:@"c" forKey:@"d"];

To generate a JSON string from a NSDictionary or NSArray, You don't need to import any third party framework. Just use following code:-

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contentDictionary // Here you can pass array or dictionary
                    options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                    error:&error];
NSString *jsonString;
if (jsonData) {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //This is your JSON String
    //NSUTF8StringEncoding encodes special characters using an escaping scheme
} else {
    NSLog(@"Got an error: %@", error);
    jsonString = @"";
}
NSLog(@"Your JSON String is %@", jsonString);

There is no argument given that corresponds to the required formal parameter - .NET Error

In the constructor of

 public class ErrorEventArg : EventArgs

You have to add "base" as follows:

    public ErrorEventArg(string errorMsg, string lastQuery) : base (string errorMsg, string lastQuery)
    {
        ErrorMsg = errorMsg;
        LastQuery = lastQuery;
    }

That solved it for me

Rails how to run rake task

Sometimes Your rake tasks doesn't get loaded in console, In that case you can try the following commands

require "rake"
YourApp::Application.load_tasks
Rake::Task["Namespace:task"].invoke

Given a starting and ending indices, how can I copy part of a string in C?

Use strncpy

e.g.

strncpy(dest, src + beginIndex, endIndex - beginIndex);

This assumes you've

  1. Validated that dest is large enough.
  2. endIndex is greater than beginIndex
  3. beginIndex is less than strlen(src)
  4. endIndex is less than strlen(src)

urlencode vs rawurlencode?

Proof is in the source code of PHP.

I'll take you through a quick process of how to find out this sort of thing on your own in the future any time you want. Bear with me, there'll be a lot of C source code you can skim over (I explain it). If you want to brush up on some C, a good place to start is our SO wiki.

Download the source (or use http://lxr.php.net/ to browse it online), grep all the files for the function name, you'll find something such as this:

PHP 5.3.6 (most recent at time of writing) describes the two functions in their native C code in the file url.c.

RawUrlEncode()

PHP_FUNCTION(rawurlencode)
{
    char *in_str, *out_str;
    int in_str_len, out_str_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
                              &in_str_len) == FAILURE) {
        return;
    }

    out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len);
    RETURN_STRINGL(out_str, out_str_len, 0);
}

UrlEncode()

PHP_FUNCTION(urlencode)
{
    char *in_str, *out_str;
    int in_str_len, out_str_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
                              &in_str_len) == FAILURE) {
        return;
    }

    out_str = php_url_encode(in_str, in_str_len, &out_str_len);
    RETURN_STRINGL(out_str, out_str_len, 0);
}

Okay, so what's different here?

They both are in essence calling two different internal functions respectively: php_raw_url_encode and php_url_encode

So go look for those functions!

Lets look at php_raw_url_encode

PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length)
{
    register int x, y;
    unsigned char *str;

    str = (unsigned char *) safe_emalloc(3, len, 1);
    for (x = 0, y = 0; len--; x++, y++) {
        str[y] = (unsigned char) s[x];
#ifndef CHARSET_EBCDIC
        if ((str[y] < '0' && str[y] != '-' && str[y] != '.') ||
            (str[y] < 'A' && str[y] > '9') ||
            (str[y] > 'Z' && str[y] < 'a' && str[y] != '_') ||
            (str[y] > 'z' && str[y] != '~')) {
            str[y++] = '%';
            str[y++] = hexchars[(unsigned char) s[x] >> 4];
            str[y] = hexchars[(unsigned char) s[x] & 15];
#else /*CHARSET_EBCDIC*/
        if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) {
            str[y++] = '%';
            str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4];
            str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15];
#endif /*CHARSET_EBCDIC*/
        }
    }
    str[y] = '\0';
    if (new_length) {
        *new_length = y;
    }
    return ((char *) str);
}

And of course, php_url_encode:

PHPAPI char *php_url_encode(char const *s, int len, int *new_length)
{
    register unsigned char c;
    unsigned char *to, *start;
    unsigned char const *from, *end;

    from = (unsigned char *)s;
    end = (unsigned char *)s + len;
    start = to = (unsigned char *) safe_emalloc(3, len, 1);

    while (from < end) {
        c = *from++;

        if (c == ' ') {
            *to++ = '+';
#ifndef CHARSET_EBCDIC
        } else if ((c < '0' && c != '-' && c != '.') ||
                   (c < 'A' && c > '9') ||
                   (c > 'Z' && c < 'a' && c != '_') ||
                   (c > 'z')) {
            to[0] = '%';
            to[1] = hexchars[c >> 4];
            to[2] = hexchars[c & 15];
            to += 3;
#else /*CHARSET_EBCDIC*/
        } else if (!isalnum(c) && strchr("_-.", c) == NULL) {
            /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */
            to[0] = '%';
            to[1] = hexchars[os_toascii[c] >> 4];
            to[2] = hexchars[os_toascii[c] & 15];
            to += 3;
#endif /*CHARSET_EBCDIC*/
        } else {
            *to++ = c;
        }
    }
    *to = 0;
    if (new_length) {
        *new_length = to - start;
    }
    return (char *) start;
}

One quick bit of knowledge before I move forward, EBCDIC is another character set, similar to ASCII, but a total competitor. PHP attempts to deal with both. But basically, this means byte EBCDIC 0x4c byte isn't the L in ASCII, it's actually a <. I'm sure you see the confusion here.

Both of these functions manage EBCDIC if the web server has defined it.

Also, they both use an array of chars (think string type) hexchars look-up to get some values, the array is described as such:

/* rfc1738:

   ...The characters ";",
   "/", "?", ":", "@", "=" and "&" are the characters which may be
   reserved for special meaning within a scheme...

   ...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
   reserved characters used for their reserved purposes may be used
   unencoded within a URL...

   For added safety, we only leave -_. unencoded.
 */

static unsigned char hexchars[] = "0123456789ABCDEF";

Beyond that, the functions are really different, and I'm going to explain them in ASCII and EBCDIC.

Differences in ASCII:

URLENCODE:

  • Calculates a start/end length of the input string, allocates memory
  • Walks through a while-loop, increments until we reach the end of the string
  • Grabs the present character
  • If the character is equal to ASCII Char 0x20 (ie, a "space"), add a + sign to the output string.
  • If it's not a space, and it's also not alphanumeric (isalnum(c)), and also isn't and _, -, or . character, then we , output a % sign to array position 0, do an array look up to the hexchars array for a lookup for os_toascii array (an array from Apache that translates char to hex code) for the key of c (the present character), we then bitwise shift right by 4, assign that value to the character 1, and to position 2 we assign the same lookup, except we preform a logical and to see if the value is 15 (0xF), and return a 1 in that case, or a 0 otherwise. At the end, you'll end up with something encoded.
  • If it ends up it's not a space, it's alphanumeric or one of the _-. chars, it outputs exactly what it is.

RAWURLENCODE:

  • Allocates memory for the string
  • Iterates over it based on length provided in function call (not calculated in function as with URLENCODE).

Note: Many programmers have probably never seen a for loop iterate this way, it's somewhat hackish and not the standard convention used with most for-loops, pay attention, it assigns x and y, checks for exit on len reaching 0, and increments both x and y. I know, it's not what you'd expect, but it's valid code.

  • Assigns the present character to a matching character position in str.
  • It checks if the present character is alphanumeric, or one of the _-. chars, and if it isn't, we do almost the same assignment as with URLENCODE where it preforms lookups, however, we increment differently, using y++ rather than to[1], this is because the strings are being built in different ways, but reach the same goal at the end anyway.
  • When the loop's done and the length's gone, It actually terminates the string, assigning the \0 byte.
  • It returns the encoded string.

Differences:

  • UrlEncode checks for space, assigns a + sign, RawURLEncode does not.
  • UrlEncode does not assign a \0 byte to the string, RawUrlEncode does (this may be a moot point)
  • They iterate differntly, one may be prone to overflow with malformed strings, I'm merely suggesting this and I haven't actually investigated.

They basically iterate differently, one assigns a + sign in the event of ASCII 20.

Differences in EBCDIC:

URLENCODE:

  • Same iteration setup as with ASCII
  • Still translating the "space" character to a + sign. Note-- I think this needs to be compiled in EBCDIC or you'll end up with a bug? Can someone edit and confirm this?
  • It checks if the present char is a char before 0, with the exception of being a . or -, OR less than A but greater than char 9, OR greater than Z and less than a but not a _. OR greater than z (yeah, EBCDIC is kinda messed up to work with). If it matches any of those, do a similar lookup as found in the ASCII version (it just doesn't require a lookup in os_toascii).

RAWURLENCODE:

  • Same iteration setup as with ASCII
  • Same check as described in the EBCDIC version of URL Encode, with the exception that if it's greater than z, it excludes ~ from the URL encode.
  • Same assignment as the ASCII RawUrlEncode
  • Still appending the \0 byte to the string before return.

Grand Summary

  • Both use the same hexchars lookup table
  • URIEncode doesn't terminate a string with \0, raw does.
  • If you're working in EBCDIC I'd suggest using RawUrlEncode, as it manages the ~ that UrlEncode does not (this is a reported issue). It's worth noting that ASCII and EBCDIC 0x20 are both spaces.
  • They iterate differently, one may be faster, one may be prone to memory or string based exploits.
  • URIEncode makes a space into +, RawUrlEncode makes a space into %20 via array lookups.

Disclaimer: I haven't touched C in years, and I haven't looked at EBCDIC in a really really long time. If I'm wrong somewhere, let me know.

Suggested implementations

Based on all of this, rawurlencode is the way to go most of the time. As you see in Jonathan Fingland's answer, stick with it in most cases. It deals with the modern scheme for URI components, where as urlencode does things the old school way, where + meant "space."

If you're trying to convert between the old format and new formats, be sure that your code doesn't goof up and turn something that's a decoded + sign into a space by accidentally double-encoding, or similar "oops" scenarios around this space/20%/+ issue.

If you're working on an older system with older software that doesn't prefer the new format, stick with urlencode, however, I believe %20 will actually be backwards compatible, as under the old standard %20 worked, just wasn't preferred. Give it a shot if you're up for playing around, let us know how it worked out for you.

Basically, you should stick with raw, unless your EBCDIC system really hates you. Most programmers will never run into EBCDIC on any system made after the year 2000, maybe even 1990 (that's pushing, but still likely in my opinion).

Get HTML code from website in C#

Here's an example of using the HttpWebRequest class to fetch a URL

private void buttonl_Click(object sender, EventArgs e) 
{ 
    String url = TextBox_url.Text;
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); 
    HttpWebResponse response = (HttpWebResponse) request.GetResponse(); 
    StreamReader sr = new StreamReader(response.GetResponseStream()); 
    richTextBox1.Text = sr.ReadToEnd(); 
    sr.Close(); 
} 

pdftk compression option

this procedure works pretty well

pdf2ps large.pdf very_large.ps

ps2pdf very_large.ps small.pdf

give it a try.

How can I execute a python script from an html button?

Since you asked for a way to complete this within an HTML page I am answering this. I feel there is no need to mention the severe warnings and implications that would go along with this .. I trust you know the security of your .py script better than I do :-)

I would use the .ajax() function in the jQuery library. This will allow you to call your Python script as long as the script is in the publicly accessible html directory ... That said this is the part where I tell you to heed security precautions ...

<!DOCTYPE html>
<html>
  <head>    
  </head>
  <body>
    <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script>
        function goPython(){
            $.ajax({
              url: "MYSCRIPT.py",
             context: document.body
            }).done(function() {
             alert('finished python script');;
            });
        }
    </script>
  </body>
</html>

In addition .. It's worth noting that your script is going to have to have proper permissions for, say, the www-data user to be able to run it ... A chmod, and/or a chown may be necessary.

C# testing to see if a string is an integer?

For Wil P solution (see above) you can also use LINQ.

var x = "12345";
var isNumeric = !string.IsNullOrEmpty(x) && x.All(Char.IsDigit);

Free tool to Create/Edit PNG Images?

Inkscape is a vector drawing program that exports PNG images. So, you end up editing SVG documents and exporting them to PNGs. Inkscape is good if you're starting from scratch, but wouldn't be ideal if you just want to edit existing PNGs.

Note--Inkscape is open source and available for free on multiple platforms.

How to generate a random number in C++?

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(NULL));
    int random_number = std::rand(); // rand() return a number between ?0? and RAND_MAX
    std::cout << random_number;
    return 0;
}

http://en.cppreference.com/w/cpp/numeric/random/rand

How do I get TimeSpan in minutes given two Dates?

I would do it like this:

int totalMinutes = (int)(end - start).TotalMinutes;

Changing image on hover with CSS/HTML

I had a similar problem.

With my button defined like:

<button  id="myButton" class="myButtonClass"></button>

I had the background styling like this:

#myButton{ background-image:url(img/picture.jpg)}

.myButtonClass{background-image:url(img/picture.jpg)}

.myButtonClass:hover{background-image:url(img/picture_hover.jpg)}

When I switched it to:

#myButton{}

.myButtonClass{background-image:url(img/picture.jpg)}

.myButtonClass:hover{background-image:url(img/picture_hover.jpg)}

The hover over feature worked just fine.

(not addressing other attributes like size and position of image or of container, just the background image changing)

Finding the max/min value in an array of primitives using Java

The Google Guava library has min and max methods in its Chars, Ints, Longs, etc. classes.

So you can simply use:

Chars.min(myarray)

No conversions are required and presumably it's efficiently implemented.

How to use CURL via a proxy?

root@APPLICATIOSERVER:/var/www/html# php connectiontest.php
61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#

Post declaring the proxy settings in the php script file issue has been fixed.

$proxy = '10.172.123.1:80';
curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port

Determine if an element has a CSS class with jQuery

In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:

element.classList.contains('your-class-name')

MySQL Trigger: Delete From Table AFTER DELETE

Why not set ON CASCADE DELETE on Foreign Key patron_info.pid?

BarCode Image Generator in Java

ZXing is a free open source Java library to read and generate barcode images. You need to get the source code and build the jars yourself. Here's a simple tutorial that I wrote for building with ZXing jars and writing your first program with ZXing.

[http://www.vineetmanohar.com/2010/09/java-barcode-api/]

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

If you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let EF know there's a relationship in there:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    public virtual Customer Customer { get; set; }
}

You can always set the FK relation explicitly:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    [ForeignKey("Customer")]
    public string CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
}

The ForeignKeyAttribute constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.

What this means is, if you where to place the ForeignKeyAttribute on the Customer property, the attribute would take CustomerID in the constructor:

public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }

EDIT based on Latest Code You get that error because of this line:

[ForeignKey("Parent")]
public Patient Patient { get; set; }

EF will look for a property called Parent to use it as the Foreign Key enforcer. You can do 2 things:

1) Remove the ForeignKeyAttribute and replace it with the RequiredAttribute to mark the relation as required:

[Required]
public virtual Patient Patient { get; set; }

Decorating a property with the RequiredAttribute also has a nice side effect: The relation in the database is created with ON DELETE CASCADE.

I would also recommend making the property virtual to enable Lazy Loading.

2) Create a property called Parent that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance ParentID (you'll need to change the name in the ForeignKeyAttribute as well):

public int ParentID { get; set; }

In my experience in this case though it works better to have it the other way around:

[ForeignKey("Patient")]
public int ParentID { get; set; }

public virtual Patient Patient { get; set; }

Block Comments in a Shell Script

A variation on the here-doc trick in the accepted answer by sunny256 is to use the Perl keywords for comments. If your comments are actually some sort of documentation, you can then start using the Perl syntax inside the commented block, which allows you to print it out nicely formatted, convert it to a man-page, etc.

As far as the shell is concerned, you only need to replace 'END' with '=cut'.

echo "before comment"
: <<'=cut'
=pod

=head1 NAME
   podtest.sh - Example shell script with embedded POD documentation

etc.

=cut
echo "after comment"

(Found on "Embedding documentation in shell script")

Return multiple values from a SQL Server function

Change it to a table-valued function

Please refer to the following link, for example.

Html.DropDownList - Disabled/Readonly

Put this in style

 select[readonly] option, select[readonly] optgroup {
        display: none;
    }

Are SSL certificates bound to the servers ip address?

The SSL certificates are going to be bound to hostname rather than IP if they are setup in the standard way. Hence why it works at one site rather than the other.

Even if the servers share the same hostname they may well have two different certificates and hence WebSphere will have a certificate trust issue as it won't be able to recognise the certificate on the second server as it is different to the first.

C# Reflection: How to get class reference from string?

You will want to use the Type.GetType method.

Here is a very simple example:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Foo");
        MethodInfo method 
             = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);

        method.Invoke(null, null);
    }
}

class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

I say simple because it is very easy to find a type this way that is internal to the same assembly. Please see Jon's answer for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I got a 503 error because the Application Pools weren't started in IIS for some reason.

Shortcut to comment out a block of code with sublime text

Just in case someone is using the Portuguese ABNT keyboard layout The shortcut is

Ctrl + ;

HTML table with 100% width, with vertical scroll inside tbody

For using "overflow: scroll" you must set "display:block" on thead and tbody. And that messes up column widths between them. But then you can clone the thead row with Javascript and paste it in the tbody as a hidden row to keep the exact col widths.

$('.myTable thead > tr').clone().appendTo('.myTable tbody').addClass('hidden-to-set-col-widths');

http://jsfiddle.net/Julesezaar/mup0c5hk/

<table class="myTable">
    <thead>
        <tr>
            <td>Problem</td>
            <td>Solution</td>
            <td>blah</td>
            <td>derp</td>
        </tr>
    </thead>
    <tbody></tbody>
</table>
<p>
  Some text to here
</p>

The css:

table {
  background-color: #aaa;
  width: 100%;
}

thead,
tbody {
  display: block; // Necessary to use overflow: scroll
}

tbody {
  background-color: #ddd;
  height: 150px;
  overflow-y: scroll;
}

tbody tr.hidden-to-set-col-widths,
tbody tr.hidden-to-set-col-widths td {
  visibility: hidden;
  height: 0;
  line-height: 0;
  padding-top: 0;
  padding-bottom: 0;
}

td {
  padding: 3px 10px;
}

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

PNG supports alphachannel transparency.

TIFF can have extended options I.e. Geo referencing for GIS applications.

I recommend only ever using JPEG for photographs, never for images like clip art, logos, text, diagrams, line art.

Favor PNG.

Online SQL syntax checker conforming to multiple databases

I haven't ever seen such a thing, but there is this dev tool that includes a syntax checker for oracle, mysql, db2, and sql server... http://www.sqlparser.com/index.php

However this seems to be just the library. You'd need to build an app to leverage the parser to do what you want. And the Enterprise edition that includes all of the databases would cost you $450... ouch!

EDIT: And, after saying that - it looks like someone might already have done what you want using that library: http://www.wangz.net/cgi-bin/pp/gsqlparser/sqlpp/sqlformat.tpl

The online tool doesn't automatically check against each DB though, you need to run each manually. Nor can I say how good it is at checking the syntax. That you'd need to investigate yourself.

Ruby Array find_first object?

Do you need the object itself or do you just need to know if there is an object that satisfies. If the former then yes: use find:

found_object = my_array.find { |e| e.satisfies_condition? }

otherwise you can use any?

found_it = my_array.any?  { |e| e.satisfies_condition? }

The latter will bail with "true" when it finds one that satisfies the condition. The former will do the same, but return the object.

clearing a char array c

Try the following:

strcpy(my_custom_data,"");

ValueError: all the input arrays must have same number of dimensions

(n,) and (n,1) are not the same shape. Try casting the vector to an array by using the [:, None] notation:

n_lists = np.append(n_list_converted, n_last[:, None], axis=1)

Alternatively, when extracting n_last you can use

n_last = n_list_converted[:, -1:]

to get a (20, 1) array.

Android: keep Service running when app is killed

You can use android:stopWithTask="false"in manifest as bellow, This means even if user kills app by removing it from tasklist, your service won't stop.

 <service android:name=".service.StickyService"
                  android:stopWithTask="false"/>

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue