Programs & Examples On #Perlmagick

Image::Magick is an objected-oriented Perl interface to ImageMagick. Use it to read, manipulate, or write an image or image sequence from within a Perl

how to display full stored procedure code?

Normally speaking you'd use a DB manager application like pgAdmin, browse to the object you're interested in, and right click your way to "script as create" or similar.

Are you trying to do this... without a management app?

SQL Server: Invalid Column Name

Following procedure helped me solve this issue but i don't know why.

  1. Cut the code in question given by the lines in the message
  2. Save the query (e.g. to file)
  3. Paste the code to where it was before
  4. Again save the query

Even if it seems to be the same query executing it did not throw this error

How do you load custom UITableViewCells from Xib files?

Register

After iOS 7, this process has been simplified down to (swift 3.0):

// For registering nib files
tableView.register(UINib(nibName: "MyCell", bundle: Bundle.main), forCellReuseIdentifier: "cell")

// For registering classes
tableView.register(MyCellClass.self, forCellReuseIdentifier: "cell")

(Note) This is also achievable by creating the cells in the .xib or .stroyboard files, as prototype cells. If you need to attach a class to them, you can select the cell prototype and add the corresponding class (must be a descendant of UITableViewCell, of course).

Dequeue

And later on, dequeued using (swift 3.0):

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = "Hello"

    return cell
}

The difference being that this new method not only dequeues the cell, it also creates if non-existant (that means that you don't have to do if (cell == nil) shenanigans), and the cell is ready to use just as in the example above.

(Warning) tableView.dequeueReusableCell(withIdentifier:for:) has the new behavior, if you call the other one (without indexPath:) you get the old behavior, in which you need to check for nil and instance it yourself, notice the UITableViewCell? return value.

if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MyCellClass
{
    // Cell be casted properly
    cell.myCustomProperty = true
}
else
{
    // Wrong type? Wrong identifier?
}

And of course, the type of the associated class of the cell is the one you defined in the .xib file for the UITableViewCell subclass, or alternatively, using the other register method.

Configuration

Ideally, your cells have been already configured in terms of appearance and content positioning (like labels and image views) by the time you registered them, and on the cellForRowAtIndexPath method you simply fill them in.

All together

class MyCell : UITableViewCell
{
    // Can be either created manually, or loaded from a nib with prototypes
    @IBOutlet weak var labelSomething : UILabel? = nil
}

class MasterViewController: UITableViewController 
{
    var data = ["Hello", "World", "Kinda", "Cliche", "Though"]

    // Register
    override func viewDidLoad()
    {
        super.viewDidLoad()

        tableView.register(MyCell.self, forCellReuseIdentifier: "mycell")
        // or the nib alternative
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return data.count
    }

    // Dequeue
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyCell

        cell.labelSomething?.text = data[indexPath.row]

        return cell
    }
}

And of course, this is all available in ObjC with the same names.

How to make a GUI for bash scripts?

Before actually using GUI dialogues, consider using console prompts. Quite often you can get away with simple "y/n?" prompts, which in bash you achieve via the read command..

read -p "Do something? ";
if [ $REPLY == "y" ]; then
    echo yay;
fi

If console prompt's just won't cut it, Zenity is really easy to use, for example:

      zenity --error --text="Testing..."
      zenity --question --text="Continue?"

This only works on Linux/Gnome (or rather, it'll only be installed by default on such systems). The read method will work on pretty much any platform (including headless machines, or via SSH)

If you need anything more complex than what read or Zenity provides, "change to C++" is really the best method (although I'd recommend Python/Ruby over C++ for such shell-script-replacement tasks)

I want to do simple interface for some strange game, the progress bar for health or something is the example for what I want. Variable "HEALTH" is 34, so make progress bar filled in 34/100

As a command-line script, it'd use Python:

$ export HEALTH=34
$ python -c "import os; print '*' * int(os.environ.get('HEALTH', 0))"
**********************************

Or to normalise the values between 1 and 78 (so you don't get line-wrapping on a standard terminal size):

$ python -c "import os; print '*' * int((int(os.environ.get('HEALTH', 0)) / 100.0) * 78)"

Zenity also has a Progress Dialog,

#!/bin/sh
(
echo "10" ; sleep 1
echo "# Updating mail logs" ; sleep 1
echo "20" ; sleep 1
echo "# Resetting cron jobs" ; sleep 1
echo "50" ; sleep 1
echo "This line will just be ignored" ; sleep 1
echo "75" ; sleep 1
echo "# Rebooting system" ; sleep 1
echo "100" ; sleep 1
) |
zenity --progress \
  --title="Update System Logs" \
  --text="Scanning mail logs..." \
  --percentage=0

if [ "$?" = -1 ] ; then
        zenity --error \
          --text="Update canceled."
fi

As I said before, if Zenity cannot do what you need, look into writing your game-thing as a "proper" script in Python/Ruby/Perl/C++/etc as it sounds like you're pushing the bounds of what a shell-script can do..

Is there a way to add/remove several classes in one single instruction with classList?

The classList property ensures that duplicate classes are not unnecessarily added to the element. In order to keep this functionality, if you dislike the longhand versions or jQuery version, I'd suggest adding an addMany function and removeMany to DOMTokenList (the type of classList):

DOMTokenList.prototype.addMany = function(classes) {
    var array = classes.split(' ');
    for (var i = 0, length = array.length; i < length; i++) {
      this.add(array[i]);
    }
}

DOMTokenList.prototype.removeMany = function(classes) {
    var array = classes.split(' ');
    for (var i = 0, length = array.length; i < length; i++) {
      this.remove(array[i]);
    }
}

These would then be useable like so:

elem.classList.addMany("first second third");
elem.classList.removeMany("first third");

Update

As per your comments, if you wish to only write a custom method for these in the event they are not defined, try the following:

DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function(classes) {...}
DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function(classes) {...}

Javascript string replace with regex to strip off illegal characters

I tend to look at it from the inverse perspective which may be what you intended:

What characters do I want to allow?

This is because there could be lots of characters that make in into a string somehow that blow stuff up that you wouldn't expect.

For example this one only allows for letters and numbers removing groups of invalid characters replacing them with a hypen:

"This¢£«±Ÿ÷could&*()\/<>be!@#$%^bad".replace(/([^a-z0-9]+)/gi, '-');
//Result: "This-could-be-bad"

Determine command line working directory when running node bin script

Current Working Directory

To get the current working directory, you can use:

process.cwd()

However, be aware that some scripts, notably gulp, will change the current working directory with process.chdir().

Node Module Path

You can get the path of the current module with:

  • __filename
  • __dirname

Original Directory (where the command was initiated)

If you are running a script from the command line, and you want the original directory from which the script was run, regardless of what directory the script is currently operating in, you can use:

process.env.INIT_CWD

Original directory, when working with NPM scripts

It's sometimes desirable to run an NPM script in the current directory, rather than the root of the project.

This variable is available inside npm package scripts as:

$INIT_CWD.

You must be running a recent version of NPM. If this variable is not available, make sure NPM is up to date.

This will allow you access the current path in your package.json, e.g.:

scripts: {
  "customScript": "gulp customScript --path $INIT_CWD"
}

extract date only from given timestamp in oracle sql

This is exactly what TO_DATE() is for: to convert timestamp to date.

Just use TO_DATE(sysdate) instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS').

SQLFiddle demo

UPDATE:

Per your update, your cdate column is not real DATE or TIMESTAMP type, but VARCHAR2. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.

You should convert your cdate VARCHAR2 field into real TIMESTAMP. Assuming there are no other users for this field except for your code, you can convert cdate to timestamp as follows:

BEGIN TRANSACTION;
-- add new temp field tdate:
ALTER TABLE mytable ADD tdate TIMESTAMP;
-- save cdate to tdate while converting it:
UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');

-- you may want to check contents of tdate before next step!!!

-- drop old field
ALTER TABLE mytable DROP COLUMN cdate;
-- rename tdate to cdate:
ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
COMMIT;

SQLFiddle Demo

Get string after character

${word:$(expr index "$word" "="):1}

that gets the 7. Assuming you mean the entire rest of the string, just leave off the :1.

Angular 2 Cannot find control with unspecified name attribute on formArrays

So, I had this code:

<div class="dropdown-select-wrapper" *ngIf="contentData">
    <button mat-stroked-button [disableRipple]="true" class="mat-button" (click)="openSelect()" [ngClass]="{'only-icon': !contentData?.buttonText?.length}">
      <i *ngIf="contentData.iconClassInfo" class="dropdown-icon {{contentData.iconClassInfo.name}}"></i>
      <span class="button-text" *ngIf="contentData.buttonText">{{contentData.buttonText}}</span>
    </button>
    <mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();">
      <mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
        {{option[contentData.optionsStructure.keyName]}}
      </mat-option>
    </mat-select>
  </div>

Here I was using standalone formControl, and I was getting the error we are talking about, which made no sense for me, since I wasn't working with formgroups or formarrays... it only disappeared when I added the *ngIf to the select it self, so is not being used before it actually exists. That's what solved the issue in my case.

<mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();" *ngIf="theFormControl">
          <mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
            {{option[contentData.optionsStructure.keyName]}}
          </mat-option>
        </mat-select>

What does if __name__ == "__main__": do?

You can checkup for the special variable __name__ with this simple example:

create file1.py

if __name__ == "__main__":
    print("file1 is being run directly")
else:
    print("file1 is being imported")

create file2.py

import file1 as f1

print("__name__ from file1: {}".format(f1.__name__))
print("__name__ from file2: {}".format(__name__))

if __name__ == "__main__":
    print("file2 is being run directly")
else:
    print("file2 is being imported")

Execute file2.py

output:

file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

Difference between .on('click') vs .click()

Is there any difference between the following code?

No, there is no functional difference between the two code samples in your question. .click(fn) is a "shortcut method" for .on("click", fn). From the documentation for .on():

There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

Note that .on() differs from .click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas .click() does not. When .on() is called without a selector parameter, it behaves exactly the same as .click(). If you want event delegation, use .on().

How to change Apache Tomcat web server port number

1) Locate server.xml in {Tomcat installation folder}\ conf \ 2) Find following similar statement

       <!-- Define a non-SSL HTTP/1.1 Connector on port 8180 -->
      <Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

For example

<Connector port="8181" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Edit and save the server.xml file. Restart Tomcat. Done

Further reference: http://www.mkyong.com/tomcat/how-to-change-tomcat-default-port/

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

Inserting a string into a list without getting split into characters

Another option is using the overloaded + operator:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']

How to see full absolute path of a symlink

realpath isn't available on all linux flavors, but readlink should be.

readlink -f symlinkName

The above should do the trick.

Alternatively, if you don't have either of the above installed, you can do the following if you have python 2.6 (or later) installed

python -c 'import os.path; print(os.path.realpath("symlinkName"))'

How can I create database tables from XSD files?

The best way to create the SQL database schema using an XSD file is a program called Altova XMLSpy, this is very simple:

  1. Create a new project
  2. On the DTDs / Schemas folder right clicking and selecting add files
  3. Selects the XSD file
  4. Open the XSD file added by double-clicking
  5. Go to the toolbar and look Conversion
  6. They select Create structure database from XML schema
  7. Selects the data source
  8. And finally give it to export the route calls immediately leave their scrip schemas with SQL Server to execute the query.

Hope it helps.

How to generate a number of most distinctive colors in R?

You can use colorRampPalette from base or RColorBrewer package:

With colorRampPalette, you can specify colours as follows:

colorRampPalette(c("red", "green"))(5)
# [1] "#FF0000" "#BF3F00" "#7F7F00" "#3FBF00" "#00FF00"

You can alternatively provide hex codes as well:

colorRampPalette(c("#3794bf", "#FFFFFF", "#df8640"))(5)
# [1] "#3794BF" "#9BC9DF" "#FFFFFF" "#EFC29F" "#DF8640"
# Note that the mid color is the mid value...

With RColorBrewer you could use colors from pre-existing palettes:

require(RColorBrewer)
brewer.pal(9, "Set1")
# [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628" "#F781BF"
# [9] "#999999"

Look at RColorBrewer package for other available palettes. Hope this helps.

npm install Error: rollbackFailedOptional

    # first this
    > npm config rm proxy
    > npm config rm https-proxy

    # then this
    > npm config set registry https://registry.npmjs.org/

solved my problem.

Again: Be sure to check whether you have internet connected properly.

PostgreSQL "DESCRIBE TABLE"

The best way to describe a table such as a column, type, modifiers of columns, etc.

\d+ tablename or \d tablename

JSON.NET Error Self referencing loop detected for type

To ignore loop references and not to serialize them globally in MVC 6 use the following in startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().Configure<MvcOptions>(options =>
        {
            options.OutputFormatters.RemoveTypesOf<JsonOutputFormatter>();
            var jsonOutputFormatter = new JsonOutputFormatter();
            jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            options.OutputFormatters.Insert(0, jsonOutputFormatter);
        });
    }

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

How do you beta test an iphone app?

In 2014 along with iOS 8 and XCode 6 apple introduced Beta Testing of iOS App using iTunes Connect.

You can upload your build to iTunes connect and invite testers using their mail id's. You can invite up to 2000 external testers using just their email address. And they can install the beta app through TestFlight

How to display images from a folder using php - PHP

You had a mistake on the statement below. Use . not ,

echo '<img src="', $dir, '/', $file, '" alt="', $file, $

to

echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $

and

echo 'Directory \'', $dir, '\' not found!';

to

echo 'Directory \''. $dir. '\' not found!';

jQuery find() method not working in AngularJS directive

I used

elm.children('.class-name-or-whatever') 

to get children of the current element

Could not find or load main class

First, put your file *.class (e.g Hello.class) into 1 folder (e.g C:\java). Then you try command and type cd /d C:\java. Now you can type "java Hello" !

PHP: HTML: send HTML select option attribute in POST

You can do this with JQuery

Simply:

   <form name='add'>
   Age: <select id="age" name='age'>
   <option value='1' stud_name='sre'>23</option>
   <option value='2' stud_name='sam'>24</option>
   <option value='5' stud_name='john'>25</option>
   </select>
   <input type='hidden' id="name" name="name" value=""/>
   <input type='submit' name='submit'/>
   </form>

Add this code in Header section:

<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>

Now JQuery function

<script type="text/javascript" language="javascript">
$(function() {
      $("#age").change(function(){
      var studentNmae= $('option:selected', this).attr('stud_name');
      $('#name').val(studentNmae);
   });
});
</script>

you can use both values as

$name = $_POST['name'];
$value = $_POST['age'];

C++ - struct vs. class

You could prove to yourself that there is no other difference by trying to define a function in a struct. I remember even my college professor who was teaching about structs and classes in C++ was surprised to learn this (after being corrected by a student). I believe it, though. It was kind of amusing. The professor kept saying what the differences were and the student kept saying "actually you can do that in a struct too". Finally the prof. asked "OK, what is the difference" and the student informed him that the only difference was the default accessibility of members.

A quick Google search suggests that POD stands for "Plain Old Data".

T-SQL substring - separating first and last name

This should work:

Select  
    LTRIM(RTRIM(SUBSTRING(FullName, 0, CHARINDEX(' ', FullName)))) As FirstName
,   LTRIM(RTRIM(SUBSTRING(FullName, CHARINDEX(' ', FullName)+1, 8000)))As LastName
FROM TABLE

Edit: Adopted Aaron's and Jonny's hint with the fixed length of 8000 to avoid unnecessary calculations.

Specify multiple attribute selectors in CSS

Just to add that there should be no space between the selector and the opening bracket.

td[someclass] 

will work. But

td [someclass] 

will not.

How to remove tab indent from several lines in IDLE?

Shift-Tab
Ctrl-Tab
< key

depends on your editor.

How to calculate the time interval between two time strings

import datetime as dt
from dateutil.relativedelta import relativedelta

start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
    timedelta_obj.years,
    timedelta_obj.months,
    timedelta_obj.days,
    timedelta_obj.hours,
    timedelta_obj.minutes,
    timedelta_obj.seconds,
)

result: 0 0 0 0 -47 -37

Fixed GridView Header with horizontal and vertical scrolling in asp.net

It is possible to apply the specific GridView / Table layout via custom CSS rules (as it was discussed in the <table><tbody> scrollable? thread) to fix GridView's Header. However, this approach will not work in all browsers. The 3-rd ASP.NET GridView controls (such as the ASPxGridView from DevExpress component vendor provide this functionality.

Check also the following CodeProject solutions:

Make a Bash alias that takes a parameter?

The question is simply asked wrong. You don't make an alias that takes parameters because alias just adds a second name for something that already exists. The functionality the OP wants is the function command to create a new function. You do not need to alias the function as the function already has a name.

I think you want something like this :

function trash() { mv "$@" ~/.Trash; }

That's it! You can use parameters $1, $2, $3, etc, or just stuff them all with $@

Ways to eliminate switch in code

Switch is not a good way to go as it breaks the Open Close Principal. This is how I do it.

public class Animal
{
       public abstract void Speak();
}


public class Dog : Animal
{
   public virtual void Speak()
   {
       Console.WriteLine("Hao Hao");
   }
}

public class Cat : Animal
{
   public virtual void Speak()
   {
       Console.WriteLine("Meauuuu");
   }
}

And here is how to use it (taking your code):

foreach (var animal in zoo) 
{
    echo animal.speak();
}

Basically what we are doing is delegating the responsibility to the child class instead of having the parent decide what to do with children.

You might also want to read up on "Liskov Substitution Principle".

getting integer values from textfield

As You're getting values from textfield as jTextField3.getText();.

As it is a textField it will return you string format as its format says:

String getText()

      Returns the text contained in this TextComponent.

So, convert your String to Integer as:

int jml = Integer.parseInt(jTextField3.getText());

instead of directly setting

   int jml = jTextField3.getText();

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(p.name, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;

p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",p.name,p.age);

free(p.surname);
free(p.name);

Count number of records returned by group by

Can you execute the following code below. It worked in Oracle.

SELECT COUNT(COUNT(*))
FROM temptable
GROUP BY column_1, column_2, column_3, column_4

How to replace NA values in a table for selected columns

We can solve it in data.table way with tidyr::repalce_na function and lapply

library(data.table)
library(tidyr)
setDT(df)
df[,c("a","b","c"):=lapply(.SD,function(x) replace_na(x,0)),.SDcols=c("a","b","c")]

In this way, we can also solve paste columns with NA string. First, we replace_na(x,""),then we can use stringr::str_c to combine columns!

How to change the order of DataFrame columns?

Here is a function to do this for any number of columns.

def mean_first(df):
    ncols = df.shape[1]        # Get the number of columns
    index = list(range(ncols)) # Create an index to reorder the columns
    index.insert(0,ncols)      # This puts the last column at the front
    return(df.assign(mean=df.mean(1)).iloc[:,index]) # new df with last column (mean) first

how to import csv data into django models

If you want to use a library, a quick google search for csv and django reveals two libraries - django-csvimport and django-adaptors. Let's read what they have to say about themselves...

  • django-adaptors:

Django adaptor is a tool which allow you to transform easily a CSV/XML file into a python object or a django model instance.

  • django-importcsv:

django-csvimport is a generic importer tool to allow the upload of CSV files for populating data.

The first requires you to write a model to match the csv file, while the second is more of a command-line importer, which is a huge difference in the way you work with them, and each is good for a different type of project.

So which one to use? That depends on which of those will be better suited for your project in the long run.

However, you can also avoid a library altogether, by writing your own django script to import your csv file, something along the lines of (warning, pseudo-code ahead):

# open file & create csvreader
import csv, yada yada yada

# import the relevant model
from myproject.models import Foo

#loop:
for line in csv file:
     line = parse line to a list
     # add some custom validation\parsing for some of the fields

     foo = Foo(fieldname1=line[1], fieldname2=line[2] ... etc. )
     try:
         foo.save()
     except:
         # if the're a problem anywhere, you wanna know about it
         print "there was a problem with line", i 

It's super easy. Hell, you can do it interactively through the django shell if it's a one-time import. Just - figure out what you want to do with your project, how many files do you need to handle and then - if you decide to use a library, try figuring out which one better suits your needs.

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config>: Scanning and activating annotations for already registered beans in spring config xml.

<context:component-scan>: Bean registration + <context:annotation-config>


@Autowired and @Required are targets property level so bean should register in spring IOC before use these annotations. To enable these annotations either have to register respective beans or include <context:annotation-config />. i.e. <context:annotation-config /> works with registered beans only.

@Required enables RequiredAnnotationBeanPostProcessor processing tool
@Autowired enables AutowiredAnnotationBeanPostProcessor processing tool

Note: Annotation itself nothing to do, we need a Processing Tool, which is a class underneath, responsible for the core process.


@Repository, @Service and @Controller are @Component, and they targets class level.

<context:component-scan> it scans the package and find and register the beans, and it includes the work done by <context:annotation-config />.

Migrating XML to Annotations

how to deal with google map inside of a hidden div (Updated picture)

I had the same issue, the google.maps.event.trigger(map, 'resize') wasn't working for me.

What I did was to put a timer to update the map after putting visible the div...

//CODE WORKING

var refreshIntervalId;

function showMap() {
    document.getElementById('divMap').style.display = '';
    refreshIntervalId = setInterval(function () { updateMapTimer() }, 300);
}

function updateMapTimer() {
    clearInterval(refreshIntervalId);
    var map = new google.maps.Map(....
    ....
}

I don't know if it's the more convenient way to do it but it works!

Check if file exists and whether it contains a specific string

If you have the test binary installed or ksh has a matching built-in function, you could use it to perform your checks. Usually /bin/[ is a symbolic link to test:

if [ -e "$file_name" ]; then
  echo "File exists"
fi

if [ -z "$used_var" ]; then
  echo "Variable is empty"
fi

Using Python String Formatting with Lists

Since I just learned about this cool thing(indexing into lists from within a format string) I'm adding to this old question.

s = '{x[0]} BLAH {x[1]} FOO {x[2]} BAR'
x = ['1', '2', '3']
print (s.format (x=x))

Output:

1 BLAH 2 FOO 3 BAR

However, I still haven't figured out how to do slicing(inside of the format string '"{x[2:4]}".format...,) and would love to figure it out if anyone has an idea, however I suspect that you simply cannot do that.

Distinct in Linq based on only one field of the table

Try this:

table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());

This will group the table by Text and use the first row from each groups resulting in rows where Text is distinct.

How can I sort one set of data to match another set of data in Excel?

You can use VLOOKUP.

Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:

=VLOOKUP(A2, Sheet2!A:B, 2, 0)

This will return you #N/A if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.

Extract column values of Dataframe as List in Apache Spark

from pyspark.sql.functions import col

df.select(col("column_name")).collect()

here collect is functions which in turn convert it to list. Be ware of using the list on the huge data set. It will decrease performance. It is good to check the data.

CKEditor automatically strips classes from div

Following is the complete example for CKEDITOR 4.x :

HTML

<textarea name="post_content" id="post_content" class="form-control"></textarea>

SCRIPT

CKEDITOR.replace('post_content', {
   allowedContent:true,
});

The above code will allow all tags in the editor.

For more Detail : CK EDITOR Allowed Content Rules

How to use OR condition in a JavaScript IF statement?

More then one condition statement is needed to use OR(||) operator in if conditions and notation is ||.

if(condition || condition){ 
   some stuff
}

How to generate XML from an Excel VBA macro?

Here is the example macro to convert the Excel worksheet to XML file.

#'vba code to convert excel to xml

Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
        xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False

End Sub

This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.

Eclipse/Maven error: "No compiler is provided in this environment"

In my case, I had created a run configuration and whenever I tried to run it, the error would be displayed. After searching on some websites, I edited the run configuration and under JRE tab, selected the runtime JRE as 'workspace default JRE' which I had already configured to point to my local Java JDK installation (ex. C:\Program Files (x86)\Java\jdk1.8.0_51). This solved my issue. Maybe it helps someone out there.

How can I use different certificates on specific connections?

I read through LOTS of places online to solve this thing. This is the code I wrote to make it work:

ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());

app.certificateString is a String that contains the Certificate, for example:

static public String certificateString=
        "-----BEGIN CERTIFICATE-----\n" +
        "MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
        "BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
        ... a bunch of characters...
        "5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
        "-----END CERTIFICATE-----";

I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.

How to install pkg config in windows?

A alternative without glib dependency is pkg-config-lite.

Extract pkg-config.exe from the archive and put it in your path.

Nowdays this package is available using chocolatey, then it could be installed whith

choco install pkgconfiglite

Stored procedure return into DataSet in C# .Net

You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.

SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();

Now you can use the below method to pass values to Stored Procedure and get the DataSet.

public DataSet GetDataSet(string paramValue)
{
    sqlcomm.Connection = sqlConn;
    using (sqlConn)
    {
        try
        {
            using (SqlDataAdapter da = new SqlDataAdapter())
            {  
                // This will be your input parameter and its value
                sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);

                // You can retrieve values of `output` variables
                var returnParam = new SqlParameter
                {
                    ParameterName = "@Error",
                    Direction = ParameterDirection.Output,
                    Size = 1000
                };
                sqlcomm.Parameters.Add(returnParam);
                // Name of stored procedure
                sqlcomm.CommandText = "StoredProcedureName";
                da.SelectCommand = sqlcomm;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                DataSet ds = new DataSet();
                da.Fill(ds);                            
            }
        }
        catch (SQLException ex)
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    return new DataSet();
}

The following is the sample of connection string in config file

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
         providerName="System.Data.SqlClient" />
</connectionStrings>

Make anchor link go some pixels above where it's linked to

Eric's answer is great, but you really don't need that timeout. If you're using jQuery, you can just wait for the page to load. So I'd suggest changing the code to:

// The function actually applying the offset
function offsetAnchor() {
    if (location.hash.length !== 0) {
        window.scrollTo(window.scrollX, window.scrollY - 100);
    }
}

// This will capture hash changes while on the page
$(window).on("hashchange", function () {
    offsetAnchor();
});

// Let the page finish loading.
$(document).ready(function() {
    offsetAnchor();
});

This also gets us rid of that arbitrary factor.

SQLite UPSERT / UPDATE OR INSERT

You can also just add an ON CONFLICT REPLACE clause to your user_name unique constraint and then just INSERT away, leaving it to SQLite to figure out what to do in case of a conflict. See:https://sqlite.org/lang_conflict.html.

Also note the sentence regarding delete triggers: When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

The error means that you're navigating to a view whose model is declared as typeof Foo (by using @model Foo), but you actually passed it a model which is typeof Bar (note the term dictionary is used because a model is passed to the view via a ViewDataDictionary).

The error can be caused by

Passing the wrong model from a controller method to a view (or partial view)

Common examples include using a query that creates an anonymous object (or collection of anonymous objects) and passing it to the view

var model = db.Foos.Select(x => new
{
    ID = x.ID,
    Name = x.Name
};
return View(model); // passes an anonymous object to a view declared with @model Foo

or passing a collection of objects to a view that expect a single object

var model = db.Foos.Where(x => x.ID == id);
return View(model); // passes IEnumerable<Foo> to a view declared with @model Foo

The error can be easily identified at compile time by explicitly declaring the model type in the controller to match the model in the view rather than using var.

Passing the wrong model from a view to a partial view

Given the following model

public class Foo
{
    public Bar MyBar { get; set; }
}

and a main view declared with @model Foo and a partial view declared with @model Bar, then

Foo model = db.Foos.Where(x => x.ID == id).Include(x => x.Bar).FirstOrDefault();
return View(model);

will return the correct model to the main view. However the exception will be thrown if the view includes

@Html.Partial("_Bar") // or @{ Html.RenderPartial("_Bar"); }

By default, the model passed to the partial view is the model declared in the main view and you need to use

@Html.Partial("_Bar", Model.MyBar) // or @{ Html.RenderPartial("_Bar", Model.MyBar); }

to pass the instance of Bar to the partial view. Note also that if the value of MyBar is null (has not been initialized), then by default Foo will be passed to the partial, in which case, it needs to be

@Html.Partial("_Bar", new Bar())

Declaring a model in a layout

If a layout file includes a model declaration, then all views that use that layout must declare the same model, or a model that derives from that model.

If you want to include the html for a separate model in a Layout, then in the Layout, use @Html.Action(...) to call a [ChildActionOnly] method initializes that model and returns a partial view for it.

SQL using sp_HelpText to view a stored procedure on a linked server

It's the correct way to access linked DB:

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText 'storedProcName'

But make sure to mention dbo as it owns the sp_helptext.

How to check if an element of a list is a list (in Python)?

Expression you are looking for may be:

...
return any( isinstance(e, list) for e in my_list )

Testing:

>>> my_list = [1,2]
>>> any( isinstance(e, list) for e in my_list )
False
>>> my_list = [1,2, [3,4,5]]
>>> any( isinstance(e, list) for e in my_list )
True
>>> 

Convert list to array in Java

Try this:

List list = new ArrayList();
list.add("Apple");
list.add("Banana");

Object[] ol = list.toArray();

Hiding axis text in matplotlib plots

When using the object oriented API, the Axes object has two useful methods for removing the axis text, set_xticklabels() and set_xticks().

Say you create a plot using

fig, ax = plt.subplots(1)
ax.plot(x, y)

If you simply want to remove the tick labels, you could use

ax.set_xticklabels([])

or to remove the ticks completely, you could use

ax.set_xticks([])

These methods are useful for specifying exactly where you want the ticks and how you want them labeled. Passing an empty list results in no ticks, or no labels, respectively.

I got error "The DELETE statement conflicted with the REFERENCE constraint"

The error means that you have data in other tables that references the data you are trying to delete.

You would need to either drop and recreate the constraints or delete the data that the Foreign Key references.

Suppose you have the following tables

dbo.Students
(
StudentId
StudentName
StudentTypeId
)


dbo.StudentTypes
(
StudentTypeId
StudentType
)

Suppose a Foreign Key constraint exists between the StudentTypeId column in StudentTypes and the StudentTypeId column in Students

If you try to delete all the data in StudentTypes an error will occur as the StudentTypeId column in Students reference the data in the StudentTypes table.

EDIT:

DELETE and TRUNCATE essentially do the same thing. The only difference is that TRUNCATE does not save the changes in to the Log file. Also you can't use a WHERE clause with TRUNCATE

AS to why you can run this in SSMS but not via your Application. I really can't see this happening. The FK constraint would still throw an error regardless of where the transaction originated from.

std::string to char*

No body ever mentioned sprintf?

std::string s;
char * c;
sprintf(c, "%s", s.c_str());

How to convert 'binary string' to normal string in Python3?

If the answer from falsetru didn't work you could also try:

>>> b'a string'.decode('utf-8')
'a string'

Using Axios GET with Authorization Header in React-Native App

For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request

Big thanks to @swapnil for trying to help me debug this.

   const data = {
      grant_type: USER_GRANT_TYPE,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      scope: SCOPE_INT,
      username: DEMO_EMAIL,
      password: DEMO_PASSWORD
    };



  axios.post(TOKEN_URL, Querystring.stringify(data))   
   .then(response => {
      console.log(response.data);
      USER_TOKEN = response.data.access_token;
      console.log('userresponse ' + response.data.access_token); 
    })   
   .catch((error) => {
      console.log('error ' + error);   
   });



const AuthStr = 'Bearer '.concat(USER_TOKEN); 
axios.get(URL, { headers: { Authorization: AuthStr } })
 .then(response => {
     // If request is good...
     console.log(response.data);
  })
 .catch((error) => {
     console.log('error ' + error);
  });

Oracle client ORA-12541: TNS:no listener

I also faced the same problem but I resolved the issue by starting the TNS listener in control panel -> administrative tools -> services ->oracle TNS listener start.I am using windows Xp and Toad to connect to Oracle.

jQuery changing font family and font size

In my opinion, it would be a cleaner and easier solution to just set a class on the body and set the font-family in css according to that class.
don't know if that's an option in your case though.

How to highlight text using javascript

Why using a selfmade highlighting function is a bad idea

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

Use an existing plugin

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins.

Have a look at mark.js

mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms

DEMO

Alternatively you can see this fiddle.

Usage example:

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

It's free and developed open-source on GitHub (project reference).

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:

tcp:name.cloudapp.net,1433

Document directory path of Xcode Device Simulator

I recommend a nice utility app called SimPholders that makes it easy to find the files and folders while developing your iOS app. It has a new version to work with the new simulators called SimPholders2. It can be found at simpholders.com

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

I had the issue where it wouldn't find the PayPal assembly and it was because I had named my solution PayPal. I'm sure this won't be the answer for anyone but thought I'd share it anyway: C# ASP.NET MVC PayPal not finding assembly

MySQL SELECT DISTINCT multiple columns

This will give DISTINCT values across all the columns:

SELECT DISTINCT value
FROM (
    SELECT DISTINCT a AS value FROM my_table
    UNION SELECT DISTINCT b AS value FROM my_table
    UNION SELECT DISTINCT c AS value FROM my_table
) AS derived

Where is GACUTIL for .net Framework 4.0 in windows 7?

There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.

They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.

Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?

If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.

On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).

cannot call member function without object

You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:

int main()
{
   Name_pairs np;
   cout << "Enter names and ages. Use 0 to cancel.\n";
   while(np.test())
   {
      np.read_names();
      np.read_ages();
   }
   np.print();
   keep_window_open();
}

HTML select form with option to enter custom value

You can't really. You'll have to have both the drop down, and the text box, and have them pick or fill in the form. Without javascript you could create a separate radio button set where they choose dropdown or text input, but this seems messy to me. With some javascript you could toggle disable one or the other depending on which one they choose, for instance, have an 'other' option in the dropdown that triggers the text field.

Encrypting & Decrypting a String in C#

using System.IO;
using System.Text;
using System.Security.Cryptography;

public static class EncryptionHelper
{
    public static string Encrypt(string clearText)
    {
        string EncryptionKey = "abc123";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
    public static string Decrypt(string cipherText)
    {
        string EncryptionKey = "abc123";
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
}

Create an application setup in visual studio 2013

Microsoft recommends to use the "InstallShield Limited Edition for Visual Studio" as replacement for the discontinued "Deployment and Setup Project" - but it is not so nice and nobody else recommends to use it. But for simple setups, and if it is not a problem to relay on commercial third party products, you can use it.

The alternative is to use Windows Installer XML (WiX), but you have to do many things manually that did the Setup-Project by itself.

How to simulate target="_blank" in JavaScript

You can extract the href from the a tag:

window.open(document.getElementById('redirect').href);

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

Load local javascript file in chrome for testing?

Look at where your html file is, the path you provided is relative not absolute. Are you sure it's placed correctly. According to the path you gave in the example above: "src="../js/moment.js" " the JS file is one level higher in hierarchy. So it should be placed as following:

Parent folder sub-folder html file js (this is a folder) moment.js

The double dots means the parent folder from current directory, in your case, the current directory is the location of html file.

But to make your life easier using a server will safe you troubles of doing this manually since the server directory is same all time so it's much easier.

Convert string to int array using LINQ

    public static int[] ConvertArray(string[] arrayToConvert)
    {
        int[] resultingArray = new int[arrayToConvert.Length];

        int itemValue;

        resultingArray = Array.ConvertAll<string, int>
            (
                arrayToConvert, 
                delegate(string intParameter) 
                {
                    int.TryParse(intParameter, out itemValue);
                    return itemValue;
                }
            );

        return resultingArray;
    }

Reference:

http://codepolice.net/convert-string-array-to-int-array-and-vice-versa-in-c/

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

Named colors in matplotlib

To get a full list of colors to use in plots:

import matplotlib.colors as colors
colors_list = list(colors._colors_full_map.values())

So, you can use in that way quickly:

scatter(X,Y, color=colors_list[0])
scatter(X,Y, color=colors_list[1])
scatter(X,Y, color=colors_list[2])
...
scatter(X,Y, color=colors_list[-1])

Test file upload using HTTP PUT method

In my opinion the best tool for such testing is curl. Its --upload-file option uploads a file by PUT, which is exactly what you want (and it can do much more, like modifying HTTP headers, in case you need it):

curl http://myservice --upload-file file.txt

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Groovy - How to compare the string?

In Groovy, null == null gets a true. At runtime, you won't know what happened. In Java, == is comparing two references.

This is a cause of big confusion in basic programming, Whether it is safe to use equals. At runtime, a null.equals will give an exception. You've got a chance to know what went wrong.

Especially, you get two values from keys not exist in map(s), == makes them equal.

Writing your own square root function

To calculate the square root of a number by help of inbuilt function

# include"iostream.h"
# include"conio.h"
# include"math.h"
void main()
{
clrscr();
float x;
cout<<"Enter the Number";
cin>>x;

 float squreroot(float);  
 float z=squareroot(x);
 cout<<z;


float squareroot(int x)
    {


 float s;
 s = pow(x,.5)  
 return(s);
 }    

SQL to find the number of distinct values in a column

After MS SQL Server 2012, you can use window function too.

   SELECT column_name, 
   COUNT(column_name) OVER (Partition by column_name) 
   FROM table_name group by column_name ; 

Pretty-Printing JSON with PHP

If you used only $json_string = json_encode($data, JSON_PRETTY_PRINT);, you will get in the browser something like this (using the Facebook link from the question :) ): enter image description here

but if you used a chrome Extension like JSONView (even without the PHP option above), then you get a more pretty readable debuggable solution where you can even Fold/Collapse each single JSON object easily like this: enter image description here

Alternating Row Colors in Bootstrap 3 - No Table

I find that if I specify .row:nth-of-type(..), my other row's elements (for other formatting, etc) also get alternating colours. So rather, I'd define in my css an entirely new class:

.row-striped:nth-of-type(odd){
  background-color: #efefef;
}

.row-striped:nth-of-type(even){
  background-color: #ffffff;
}

So now, the alternating row colours will only apply to the row container, when I specify its class as .row-striped, and not the elements inside the row.

<!-- this entire row container is #efefef -->
<div class="row row-striped">
    <div class="form-group">
        <div class="col-sm-8"><h5>Field Greens with strawberry vinegrette</h5></div>
        <div class="col-sm-4">
            <input type="number" type="number" step="1" min="0"></input><small>$30/salad</small>
        </div>
    </div>
</div>

<!-- this entire row container is #ffffff -->
<div class="row row-striped">
    <div class="form-group">
        <div class="col-sm-8"><h5>Greek Salad</h5></div>
        <div class="col-sm-4">
            <input type="number" type="number" step="1" min="0"></input><small>$25/salad</small>
        </div>
    </div>
</div>

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:

  1. You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.

  2. Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.


-onedaywhen yesterday

Here is an example where #table constraints can prevent bad data which is not the case in CTE's

DECLARE @BadData TABLE ( 
                       ThisID int
                     , ThatID int );
INSERT INTO @BadData
       ( ThisID
       , ThatID
       ) 
VALUES
       ( 1, 1 ),
       ( 1, 2 ),
       ( 2, 2 ),
       ( 1, 1 );

IF OBJECT_ID('tempdb..#This') IS NOT NULL
    DROP TABLE #This;
CREATE TABLE #This ( 
             ThisID int NOT NULL
           , ThatID int NOT NULL
                        UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
     AS (SELECT *
           FROM @BadData)
     SELECT *
       FROM This_CTE;

How to split an integer into an array of digits?

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

from math import log10

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

res = list(digitize(5243))

[5, 2, 4, 3]

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

Renaming branches remotely in Git

If you really just want to rename branches remotely, without renaming any local branches at the same time, you can do this with a single command:

git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>

I wrote this script (git-rename-remote-branch) which provides a handy shortcut to do the above easily.

As a bash function:

git-rename-remote-branch(){
  if [ $# -ne 3 ]; then
    echo "Rationale : Rename a branch on the server without checking it out."
    echo "Usage     : ${FUNCNAME[0]} <remote> <old name> <new name>"
    echo "Example   : ${FUNCNAME[0]} origin master release"
    return 1 
  fi

  git push $1 $1/$2\:refs/heads/$3 :$2
}

To integrate @ksrb's comment: What this basically does is two pushes in a single command, first git push <remote> <remote>/<old_name>:refs/heads/<new_name> to push a new remote branch based on the old remote tracking branch and then git push <remote> :<old_name> to delete the old remote branch.

How to remove \xa0 from string in Python?

Try this code

import re
re.sub(r'[^\x00-\x7F]+','','paste your string here').decode('utf-8','ignore').strip()

Access key value from Web.config in Razor View-MVC3 ASP.NET

The preferred method is actually:

@System.Web.Configuration.WebConfigurationManager.AppSettings["myKey"]

It also doesn't need a reference to the ConfigurationManager assembly, it's already in System.Web.

Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

thenReturn(T value) Sets a return value to be returned when the method is called.

@Test
public void test_return() throws Exception {
    Dummy dummy = mock(Dummy.class);
    int returnValue = 5;

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenReturn(returnValue);
    doReturn(returnValue).when(dummy).stringLength("dummy");
}

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

Use doAnswer() when you want to stub a void method with generic Answer.

Answer specifies an action that is executed and a return value that is returned when you interact with the mock.

@Test
public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
}

Detect end of ScrollView

Did it!

Aside of the fix Alexandre kindly provide me, I had to create an Interface:

public interface ScrollViewListener {
    void onScrollChanged(ScrollViewExt scrollView, 
                         int x, int y, int oldx, int oldy);
}

Then, i had to override the OnScrollChanged method from ScrollView in my ScrollViewExt:

public class ScrollViewExt extends ScrollView {
    private ScrollViewListener scrollViewListener = null;
    public ScrollViewExt(Context context) {
        super(context);
    }

    public ScrollViewExt(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    public void setScrollViewListener(ScrollViewListener scrollViewListener) {
        this.scrollViewListener = scrollViewListener;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged(this, l, t, oldl, oldt);
        }
    }
}

Now, as Alexandre said, put the package name in the XML tag (my fault), make my Activity class implement the interface created before, and then, put it all together:

scroll = (ScrollViewExt) findViewById(R.id.scrollView1);
scroll.setScrollViewListener(this);

And in the method OnScrollChanged, from the interface...

@Override
public void onScrollChanged(ScrollViewExt scrollView, int x, int y, int oldx, int oldy) {
    // We take the last son in the scrollview
    View view = (View) scrollView.getChildAt(scrollView.getChildCount() - 1);
    int diff = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));

    // if diff is zero, then the bottom has been reached
    if (diff == 0) {
        // do stuff
    }
}

And it worked!

Thank you very much for your help, Alexandre!

How can I slice an ArrayList out of an ArrayList in Java?

Although this post is very old. In case if somebody is looking for this..

Guava facilitates partitioning the List into sublists of a specified size

List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    List<List<Integer>> subSets = Lists.partition(intList, 3);

Disable same origin policy in Chrome

EDIT 3: Seems that the extension no longer exists... Normally to get around CORS these days I set up another version of Chrome with a separate directory or I use Firefox with https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/ instead.

EDIT 2: I can no longer get this to work consistently.

EDIT: I tried using the just the other day for another project and it stopped working. Uninstalling and reinstalling the extension fixed it (to reset the defaults).

Original Answer:

I didn't want to restart Chrome and disable my web security (because I was browsing while developing) and stumbled onto this Chrome extension.

Chrome Web Store Allow-Control-Allow-Origin: *
(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en)

Basically it's a little toggle switch to toggle on and off the Allow-Access-Origin-Control check. Works perfectly for me for what I'm doing.

Math functions in AngularJS bindings

I think the best way to do it is by creating a filter, like this:

myModule.filter('ceil', function() {
    return function(input) {
        return Math.ceil(input);
    };
});

then the markup looks like this:

<p>The percentage is {{ (100*count/total) | ceil }}%</p>

Updated fiddle: http://jsfiddle.net/BB4T4/

Fastest way to add an Item to an Array

For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.

Module ArrayExtension
    <Extension()> _
    Public Sub Add(Of T)(ByRef arr As T(), item As T)
        If arr IsNot Nothing Then
            Array.Resize(arr, arr.Length + 1)
            arr(arr.Length - 1) = item
        Else
            ReDim arr(0)
            arr(0) = item
        End If

    End Sub
End Module

How to verify element present or visible in selenium 2 (Selenium WebDriver)

I used java print statements for easy understanding.

  1. To check Element Present:

    if(driver.findElements(By.xpath("value")).size() != 0){
    System.out.println("Element is Present");
    }else{
    System.out.println("Element is Absent");
    }
    

    Or

    if(driver.findElement(By.xpath("value"))!= null){
    System.out.println("Element is Present");
    }else{
    System.out.println("Element is Absent");
    }
    
  2. To check Visible:

    if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){
    System.out.println("Element is Visible");
    }else{
    System.out.println("Element is InVisible");
    }
    
  3. To check Enable:

    if( driver.findElement(By.cssSelector("a > font")).isEnabled()){
    System.out.println("Element is Enable");
    }else{
    System.out.println("Element is Disabled");
    }
    
  4. To check text present

    if(driver.getPageSource().contains("Text to check")){
    System.out.println("Text is present");
    }else{
    System.out.println("Text is absent");
    }
    

How to convert a PNG image to a SVG?

To my surprise, potrace it turns out, can only process black and white. That may be fine for you use case, but some may consider lack of color tracing to be problematic.

Personally, I've had satisfactory results with Vector Magic

Still it's not perfect.

Android Fragments and animation

If you don't have to use the support library then have a look at Roman's answer.

But if you want to use the support library you have to use the old animation framework as described below.

After consulting Reto's and blindstuff's answers I have gotten the following code working.

The fragments appear sliding in from the right and sliding out to the left when back is pressed.

FragmentManager fragmentManager = getSupportFragmentManager();

FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);

CustomFragment newCustomFragment = CustomFragment.newInstance();
transaction.replace(R.id.fragment_container, newCustomFragment );
transaction.addToBackStack(null);
transaction.commit();

The order is important. This means you must call setCustomAnimations() before replace() or the animation will not take effect!

Next these files have to be placed inside the res/anim folder.

enter.xml:

<?xml version="1.0" encoding="utf-8"?>
<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="100%"
               android:toXDelta="0"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="@android:integer/config_mediumAnimTime"/>
</set>

exit.xml:

<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="0"
               android:toXDelta="-100%"
               android:interpolator="@android:anim/accelerate_interpolator"
               android:duration="@android:integer/config_mediumAnimTime"/>
</set>

pop_enter.xml:

<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="-100%"
               android:toXDelta="0"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="@android:integer/config_mediumAnimTime"/>
</set>

pop_exit.xml:

<?xml version="1.0" encoding="utf-8"?>
<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="0"
               android:toXDelta="100%"
               android:interpolator="@android:anim/accelerate_interpolator"
               android:duration="@android:integer/config_mediumAnimTime"/>
</set>

The duration of the animations can be changed to any of the default values like @android:integer/config_shortAnimTime or any other number.

Note that if in between fragment replacements a configuration change happens (for example rotation) the back action isn't animated. This is a documented bug that still exists in the rev 20 of the support library.

Convert string to Boolean in javascript

Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#. So workaround is

var setActive = 'true'; 
setActive = setActive == "true";

if(setActive)
// statements
else
// statements.

How to change Bootstrap's global default font size?

Bootstrap uses the variable:

$font-size-base: 1rem; // Assumes the browser default, typically 16px

I don't recommend mucking with this, but you can. Best practice is to override the browser default base font size with:

html {
  font-size: 14px;
}

Bootstrap will then take that value and use it via rems to set values for all kinds of things.

Java: How to set Precision for double value?

This worked for me:

public static void main(String[] s) {
        Double d = Math.PI;
        d = Double.parseDouble(String.format("%.3f", d));  // can be required precision
        System.out.println(d);
    }

Android TextView Text not getting wrapped

I put this attribute:

android:inputType="textMultiLine"

into my TextView and it has wrapping line and user can "Enter" for a new line.

============================================================

When you come to this post, you may want to create a Big TextView which can display multiple lines so these attributes may also needed

android:layout_height="Xdp" //where X is a number depends on how big Textview you want
android:gravity="top" //in order to make your text start from the top of your TextView.

javascript create empty array of a given size

As of ES5 (when this answer was given):

If you want an empty array of undefined elements, you could simply do

var whatever = new Array(5);

this would give you

[undefined, undefined, undefined, undefined, undefined]

and then if you wanted it to be filled with empty strings, you could do

whatever.fill('');

which would give you

["", "", "", "", ""]

And if you want to do it in one line:

var whatever = Array(5).fill('');

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

As others were saying, an easy solution is to put your script at the bottom of the page, because all DOM elements are loaded synchronously from top to bottom. Otherwise, I think what you're looking for is document.onload(() => {callback_body}) or window.onload(() => {callback_body}) as Erik said. These allow you to execute you script when the dom:loaded event is fired as Douwe Maan said. Not sure about the properties of window.onload, but document.onload is triggered only after all elements, css, and scripts are loaded. In your case:

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

or, If you are using an old browser:

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

How to change a text with jQuery

Pretty straight forward to do:

$(function() {
  $('#toptitle').html('New word');
});

The html function accepts html as well, but its straight forward for replacing text.

Shell script to delete directories older than n days

I was struggling to get this right using the scripts provided above and some other scripts especially when files and folder names had newline or spaces.

Finally stumbled on tmpreaper and it has been worked pretty well for us so far.

tmpreaper -t 5d ~/Downloads


tmpreaper  --protect '*.c' -t 5h ~/my_prg

Original Source link

Has features like test, which checks the directories recursively and lists them. Ability to delete symlinks, files or directories and also the protection mode for a certain pattern while deleting

How do I read and parse an XML file in C#?

Here's an application I wrote for reading xml sitemaps:

using System;
using System.Collections.Generic;
using System.Windows.Forms; 
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Xml;

namespace SiteMapReader
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter the Location of the file");

            // get the location we want to get the sitemaps from 
            string dirLoc = Console.ReadLine();

            // get all the sitemaps 
            string[] sitemaps = Directory.GetFiles(dirLoc);
            StreamWriter sw = new StreamWriter(Application.StartupPath + @"\locs.txt", true);

            // loop through each file 
            foreach (string sitemap in sitemaps)
            {
                try
                {
                    // new xdoc instance 
                    XmlDocument xDoc = new XmlDocument();

                    //load up the xml from the location 
                    xDoc.Load(sitemap);

                    // cycle through each child noed 
                    foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
                    {
                        // first node is the url ... have to go to nexted loc node 
                        foreach (XmlNode locNode in node)
                        {
                            // thereare a couple child nodes here so only take data from node named loc 
                            if (locNode.Name == "loc")
                            {
                                // get the content of the loc node 
                                string loc = locNode.InnerText;

                                // write it to the console so you can see its working 
                                Console.WriteLine(loc + Environment.NewLine);

                                // write it to the file 
                                sw.Write(loc + Environment.NewLine);
                            }
                        }
                    }
                }
                catch { }
            }
            Console.WriteLine("All Done :-)"); 
            Console.ReadLine(); 
        }

        static void readSitemap()
        {
        }
    }
}

Code on Paste Bin http://pastebin.com/yK7cSNeY

How, in general, does Node.js handle 10,000 concurrent requests?

Adding to slebetman answer: When you say Node.JS can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.

Internally, event loop of Node.JS is handling a thread pool, where each thread handles a non-blocking request and event loop continues to listen to more request after delegating work to one of the thread of the thread pool. When one of the thread completes the work, it send a signal to the event loop that it has finished aka callback. Event loop then process this callback and send the response back.

As you are new to NodeJS, do read more about nextTick to understand how event loop works internally. Read blogs on http://javascriptissexy.com, they were really helpful for me when I started with JavaScript/NodeJS.

Find html label associated with a given input

I am bit surprised no one is suggesting to use the CSS relationship method?

in a style sheet you can reference a label from the element selector:

<style>

//for input element with class 'YYY'
input.YYY + label {}

</style>

if the checkbox has an id of 'XXX' then the label would be found through jQuery by:

$('#XXX + label');

You can also apply .find('+ label') to return the label from a jQuery checkbox element, ie useful when looping:

$('input[type=checkbox]').each( function(){
   $(this).find('+ label');
});

How to call external url in jquery?

Follow the below simple steps you will able to get the result

Step 1- Create one internal function getDetailFromExternal in your back end. step 2- In that function call the external url by using cUrl like below function

 function getDetailFromExternal($p1,$p2) {

        $url = "http://request url with parameters";
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true            
        ));

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        echo $output;
        exit;
    }

Step 3- Call that internal function from your front end by using javascript/jquery Ajax.

Android new Bottom Navigation bar or BottomNavigationView

You can create the layouts according to the above-mentioned answers If anyone wants to use this in kotlin:-

 private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.images -> {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
       R.id.videos ->
         {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

then in oncreate you can set the above listener to your view

   mDataBinding?.navigation?.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

Convert XML to JSON (and back) using Javascript

Disclaimer: I've written fast-xml-parser

Fast XML Parser can help to convert XML to JSON and vice versa. Here is the example;

var options = {
    attributeNamePrefix : "@_",
    attrNodeName: "attr", //default is 'false'
    textNodeName : "#text",
    ignoreAttributes : true,
    ignoreNameSpace : false,
    allowBooleanAttributes : false,
    parseNodeValue : true,
    parseAttributeValue : false,
    trimValues: true,
    decodeHTMLchar: false,
    cdataTagName: "__cdata", //default is 'false'
    cdataPositionChar: "\\c",
};
if(parser.validate(xmlData)=== true){//optional
    var jsonObj = parser.parse(xmlData,options);
}

If you want to parse JSON or JS object into XML then

//default options need not to set
var defaultOptions = {
    attributeNamePrefix : "@_",
    attrNodeName: "@", //default is false
    textNodeName : "#text",
    ignoreAttributes : true,
    encodeHTMLchar: false,
    cdataTagName: "__cdata", //default is false
    cdataPositionChar: "\\c",
    format: false, 
    indentBy: "  ",
    supressEmptyNode: false
};
var parser = new parser.j2xParser(defaultOptions);
var xml = parser.parse(json_or_js_obj);

How to get commit history for just one branch?

I think an option for your purposes is git log --online --decorate. This lets you know the checked commit, and the top commits for each branch that you have in your story line. By doing this, you have a nice view on the structure of your repo and the commits associated to a specific branch. I think reading this might help.

Align text in JLabel to the right

To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:

JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);     

And if you have an image:

JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);

But, I believe you want to make the label such that there are only 2 words on 1 line.

In that case try this:

String urText="<html>You can<br>use basic HTML<br>in Swing<br> components," 
   +"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

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

The specific instructions for what you are looking for are in here: https://support.google.com/docs/answer/3093281

Remember your Google Spreadsheets Formulas might use semicolon (;) instead of comma (,) depending on Regional Settings.

Once made the replacement on some examples would look like this:

=GoogleFinance("CURRENCY:USDEUR")
=INDEX(GoogleFinance("USDEUR","price",today()-30,TODAY()),2,2)
=SPARKLINE(GoogleFinance("USDEUR","price",today()-30,today()))

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

In iOS 10+

Apple enabled the attribute playsinline in all browsers on iOS 10, so this works seamlessly:

<video src="file.mp4" playsinline>

In iOS 8 and iOS 9

Short answer: use iphone-inline-video, it enables inline playback and syncs the audio.

Long answer: You can work around this issue by simulating the playback by skimming the video instead of actually .play()'ing it.

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

byte[] to hex string

You combine LINQ with string methods:

string hex = string.Join("",
  bin.Select(
    bin => bin.ToString("X2")
      ).ToArray());

Test if string begins with a string?

Judging by the declaration and description of the startsWith Java function, the "most straight forward way" to implement it in VBA would either be with Left:

Public Function startsWith(str As String, prefix As String) As Boolean
    startsWith = Left(str, Len(prefix)) = prefix
End Function

Or, if you want to have the offset parameter available, with Mid:

Public Function startsWith(str As String, prefix As String, Optional toffset As Integer = 0) As Boolean
    startsWith = Mid(str, toffset + 1, Len(prefix)) = prefix
End Function

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

querySelectorAll with multiple conditions

According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.

This example returns a list of all div elements within the document with a class of either "note" or "alert":

var matches = document.querySelectorAll("div.note, div.alert");

source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:

https://api.jquery.com/multiple-attribute-selector/

ex. "input[id][name$='man']" specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2" to require object of 2 classes.

All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.

Twitter Bootstrap: div in container with 100% height

you need to add padding-top to "fill" element, plus add box-sizing:border-box - sample here bootply

Shell script "for" loop syntax

Brace expansion, {x..y} is performed before other expansions, so you cannot use that for variable length sequences.

Instead, use the seq 2 $max method as user mob stated.

So, for your example it would be:

max=10
for i in `seq 2 $max`
do
    echo "$i"
done

Django gives Bad Request (400) when DEBUG = False

Try to run your server with the --insecure just like this:

python manage.py runserver --insecure

The mysqli extension is missing. Please check your PHP configuration

I encountered this problem today and eventually I realize it was the comment on the line before the mysql dll's that was causing the problem.

This is what you should have in php.ini by default for PHP 5.5.16:

;extension=php_exif.dll       Must be after mbstring as it depends on it
;extension=php_mysql.dll
;extension=php_mysqli.dll

Besides removing the semi-colons, you also need to delete the line of comment that came after php_exif.dll. This leaves you with

extension=php_exif.dll      
extension=php_mysql.dll
extension=php_mysqli.dll

This solves the problem in my case.

jQuery selector to get form by name

$('form[name="frmSave"]') is correct. You mentioned you thought this would get all children with the name frmsave inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');

$('form[name="frmSave"]') literally means find all forms with the name frmSave, because there is no combinator involved.

How to read a file from jar in Java?

A JAR is basically a ZIP file so treat it as such. Below contains an example on how to extract one file from a WAR file (also treat it as a ZIP file) and outputs the string contents. For binary you'll need to modify the extraction process, but there are plenty of examples out there for that.

public static void main(String args[]) {
    String relativeFilePath = "style/someCSSFile.css";
    String zipFilePath = "/someDirectory/someWarFile.war";
    String contents = readZipFile(zipFilePath,relativeFilePath);
    System.out.println(contents);
}

public static String readZipFile(String zipFilePath, String relativeFilePath) {
    try {
        ZipFile zipFile = new ZipFile(zipFilePath);
        Enumeration<? extends ZipEntry> e = zipFile.entries();

        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            // if the entry is not directory and matches relative file then extract it
            if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
                BufferedInputStream bis = new BufferedInputStream(
                        zipFile.getInputStream(entry));
                // Read the file
                    // With Apache Commons I/O
                 String fileContentsStr = IOUtils.toString(bis, "UTF-8");

                    // With Guava
                //String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
                // close the input stream.
                bis.close();
                return fileContentsStr;
            } else {
                continue;
            }
        }
    } catch (IOException e) {
        logger.error("IOError :" + e);
        e.printStackTrace();
    }
    return null;
}

In this example I'm using Apache Commons I/O and if you are using Maven here is the dependency:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

Convert JS Object to form data

You can simply install qs:

npm i qs

Simply import:

import qs from 'qs'

Pass object to qs.stringify():

var item = {
   description: 'Some Item',
   price : '0.00',
   srate : '0.00',
   color : 'red',
   ...
   ...
}

qs.stringify(item)

How to search for a string in an arraylist

Nowadays, Java 8 allows for a one-line functional solution that is cleaner, faster, and a whole lot simpler than the accepted solution:

List<String> list = new ArrayList<>();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");

List<String> matches = list.stream().filter(it -> it.contains("bea")).collect(Collectors.toList());

System.out.println(matches); // [bear, beat]

And even easier in Kotlin:

val matches = list.filter { it.contains("bea") }

IntelliJ: Error:java: error: release version 5 not supported

You should do one more change by either below approaches:


1 Through IntelliJ GUI

As mentioned by 'tataelm':

Project Structure > Project Settings > Modules > Language level: > then change to your preferred language level


2 Edit IntelliJ config file directly

Open the <ProjectName>.iml file (it is created automatically in your project folder if you're using IntelliJ) directly by editing the following line,

From: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5">

To: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_11">

As your approach is also meaning to edit this file. :)


Approach 1 is actually asking IntelliJ to help edit the .iml file instead of doing by you directly.

AttributeError: 'module' object has no attribute 'urlopen'

import urllib.request as ur

filehandler = ur.urlopen ('http://www.google.com')
for line in filehandler:
    print(line.strip())

Conditional Count on a field

SELECT  Priority, COALESCE(cnt, 0)
FROM    (
        SELECT  1 AS Priority
        UNION ALL
        SELECT  2 AS Priority
        UNION ALL
        SELECT  3 AS Priority
        UNION ALL
        SELECT  4 AS Priority
        UNION ALL
        SELECT  5 AS Priority
        ) p
LEFT JOIN
        (
        SELECT  Priority, COUNT(*) AS cnt
        FROM    jobs
        GROUP BY
                Priority
        ) j
ON      j.Priority = p.Priority

Modify tick label text

The axes class has a set_yticklabels function which allows you to set the tick labels, like so:

#ax is the axes instance
group_labels = ['control', 'cold treatment',
             'hot treatment', 'another treatment',
             'the last one']

ax.set_xticklabels(group_labels)

I'm still working on why your example above didn't work.

How to connect to LocalDB in Visual Studio Server Explorer?

It worked for me.

  1. Open command prompt
  2. Run "SqlLocalDB.exe start"
  3. System response "LocalDB instance "mssqllocaldb" started."
  4. In VS, View/Server Explorer/(Right click) Data Connections/Add Connection
    • Data Source: Microsoft SQL Server (SqlClient)
    • Server name: (localdb)\MSSQLLocalDB
    • Log on to the server: Use Windows Authentication
  5. Press "Test Connection", Then OK.

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

If you don't want to use

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>(...)</version>
</parent>

as a parent POM, you may use the

mvn org.springframework.boot:spring-boot-maven-plugin:run

command instead.

Vim delete blank lines

The following can be used to remove only multi blank lines (reduce them to a single blank line) and leaving single blank lines intact:

:g/^\_$\n\_^$/d

Read Excel sheet in Powershell

This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ... as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.

$lastCell = 11 
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7

$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row

$phoneData = for ($i=1; $i -le $endRow; $i++)
            {
                $pModel = $sh.Cells.Item($startRow,$model).Value2
                $pMAC = $sh.Cells.Item($startRow,$mac).Value2
                $nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
                $extension = $sh.Cells.Item($startRow,$ext).Value2
                New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
                $startRow++
            }

I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.

How to handle notification when app in background in Firebase

According to OAUTH 2.0:

There will be Auth problem for this case beacuse FCM now using OAUTH 2

So I read firebase documentation and according to documentation new way to post data message is;

POST: https://fcm.googleapis.com/v1/projects/YOUR_FIREBASEDB_ID/messages:send

Headers

Key: Content-Type, Value: application/json

Auth

Bearer YOUR_TOKEN 

Example Body

{
   "message":{
    "topic" : "xxx",
    "data" : {
         "body" : "This is a Firebase Cloud Messaging Topic Message!",
         "title" : "FCM Message"
          }
      }
 }

In the url there is Database Id which you can find it on your firebase console. (Go project setttings)

And now lets take our token (It will valid only 1 hr):

First in the Firebase console, open Settings > Service Accounts. Click Generate New Private Key, securely store the JSON file containing the key. I was need this JSON file to authorize server requests manually. I downloaded it.

Then I create a node.js project and used this function to get my token;

var PROJECT_ID = 'YOUR_PROJECT_ID';
var HOST = 'fcm.googleapis.com';
var PATH = '/v1/projects/' + PROJECT_ID + '/messages:send';
var MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
var SCOPES = [MESSAGING_SCOPE];

  router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
      getAccessToken().then(function(accessToken) {
        console.log("TOKEN: "+accessToken)
      })

    });

function getAccessToken() {
return new Promise(function(resolve, reject) {
    var key = require('./YOUR_DOWNLOADED_JSON_FILE.json');
    var jwtClient = new google.auth.JWT(
        key.client_email,
        null,
        key.private_key,
        SCOPES,
        null
    );
    jwtClient.authorize(function(err, tokens) {
        if (err) {
            reject(err);
            return;
        }
        resolve(tokens.access_token);
    });
});
}

Now I can use this token in my post request. Then I post my data message, and it is now handled by my apps onMessageReceived function.

jQuery animated number counter from zero to value

You can do it with animate function in jQuery.

$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
    duration: 8000,
    easing: 'linear',
    step: function () {
        $('.yourelement').html(Math.floor(this.countNum));
    },
    complete: function () {
        $('.code').html(this.countNum);
        //alert('finished');
   }
});

Demo

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

How to scroll HTML page to given anchor?

a vue2 solution ... add simple data property to simply force the update

  const app = new Vue({ 
  ... 

  , updated: function() {
           this.$nextTick(function() {
           var uri = window.location.href
           var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
           if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
              this.updater = "" // only on page-load !
              location.href = "#"+String(anchor)
           }
         })
        }
     });
     app.updater = "page_load"

 /* smooth scrolling in css - works in html5 only */
 html, body {
     scroll-behavior: smooth;
 }

case statement in where clause - SQL Server

simply do the select:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))

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

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

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

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

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

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

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

Get pixel's RGB using PIL

An alternative to converting the image is to create an RGB index from the palette.

from PIL import Image

def chunk(seq, size, groupByList=True):
    """Returns list of lists/tuples broken up by size input"""
    func = tuple
    if groupByList:
        func = list
    return [func(seq[i:i + size]) for i in range(0, len(seq), size)]


def getPaletteInRgb(img):
    """
    Returns list of RGB tuples found in the image palette
    :type img: Image.Image
    :rtype: list[tuple]
    """
    assert img.mode == 'P', "image should be palette mode"
    pal = img.getpalette()
    colors = chunk(pal, 3, False)
    return colors

# Usage
im = Image.open("image.gif")
pal = getPalletteInRgb(im)

How do you tell if a string contains another string in POSIX sh?

Here is a link to various solutions of your issue.

This is my favorite as it makes the most human readable sense:

The Star Wildcard Method

if [[ "$string" == *"$substring"* ]]; then
    return 1
fi
return 0

How to find Oracle Service Name

Check the service name of a database by

sql> show parameter service;

Formatting code in Notepad++

ANSWER AS OF June 2019

Install the XML Tools plugin from the Plugin Admin (in Notepad++ 7.7 at least)

Then click Plugins -> XML Tools -> Pretty Print (XML Only with Line breaks)

That did it for me.

POST Multipart Form Data using Retrofit 2.0 including image

Update Code for image file uploading in Retrofit2.0

public interface ApiInterface {

    @Multipart
    @POST("user/signup")
    Call<UserModelResponse> updateProfilePhotoProcess(@Part("email") RequestBody email,
                                                      @Part("password") RequestBody password,
                                                      @Part("profile_pic\"; filename=\"pp.png")
                                                              RequestBody file);
}

Change MediaType.parse("image/*") to MediaType.parse("image/jpeg")

RequestBody reqFile = RequestBody.create(MediaType.parse("image/jpeg"),
                                         file);
RequestBody email = RequestBody.create(MediaType.parse("text/plain"),
                                       "[email protected]");
RequestBody password = RequestBody.create(MediaType.parse("text/plain"),
                                          "123456789");

Call<UserModelResponse> call = apiService.updateProfilePhotoProcess(email,
                                                                    password,
                                                                    reqFile);
call.enqueue(new Callback<UserModelResponse>() {

    @Override
    public void onResponse(Call<UserModelResponse> call,
                           Response<UserModelResponse> response) {

        String
                TAG =
                response.body()
                        .toString();

        UserModelResponse userModelResponse = response.body();
        UserModel userModel = userModelResponse.getUserModel();

        Log.d("MainActivity",
              "user image = " + userModel.getProfilePic());

    }

    @Override
    public void onFailure(Call<UserModelResponse> call,
                          Throwable t) {

        Toast.makeText(MainActivity.this,
                       "" + TAG,
                       Toast.LENGTH_LONG)
             .show();

    }
});

Deleting multiple elements from a list

This has been mentioned, but somehow nobody managed to actually get it right.

On O(n) solution would be:

indices = {0, 2}
somelist = [i for j, i in enumerate(somelist) if j not in indices]

This is really close to SilentGhost's version, but adds two braces.

SQL DELETE with JOIN another table for WHERE condition

How about:

DELETE guide_category  
  WHERE id_guide_category IN ( 

        SELECT id_guide_category 
          FROM guide_category AS gc
     LEFT JOIN guide AS g 
            ON g.id_guide = gc.id_guide
         WHERE g.title IS NULL

  )

Python JSON serialize a Decimal object

3.9 can not be exactly represented in IEEE floats, it will always come as 3.8999999999999999, e.g. try print repr(3.9), you can read more about it here:

http://en.wikipedia.org/wiki/Floating_point
http://docs.sun.com/source/806-3568/ncg_goldberg.html

So if you don't want float, only option you have to send it as string, and to allow automatic conversion of decimal objects to JSON, do something like this:

import decimal
from django.utils import simplejson

def json_encode_decimal(obj):
    if isinstance(obj, decimal.Decimal):
        return str(obj)
    raise TypeError(repr(obj) + " is not JSON serializable")

d = decimal.Decimal('3.5')
print simplejson.dumps([d], default=json_encode_decimal)

Android: adb pull file on desktop

Use a fully-qualified path to the desktop (e.g., /home/mmurphy/Desktop).

Example: adb pull sdcard/log.txt /home/mmurphy/Desktop

Lazy Method for Reading Big File in Python?

you can use following code.

file_obj = open('big_file') 

open() returns a file object

then use os.stat for getting size

file_size = os.stat('big_file').st_size

for i in range( file_size/1024):
    print file_obj.read(1024)

Connect to Amazon EC2 file directory using Filezilla and SFTP

This is very simple if you used your pem file ( I am using MacOS / windows user can follow the same steps.)

  1. Just download your FileZilla (I'm using MacOS - and downloaded free version, that's good enough)

  2. Open Site Manager in FileZilla (?S) -> New Site

enter image description here

  1. Put your host name in the Host field.

Example: eca-**-**-**-111.ap-southwest-9.compute.amazonaws.com

  • Select Protocol as SFTP - SSH File Transfer Protocol

  • Select Logon type as Key File

  • Put your user name in the User field : for me it's ubuntu (find your ssh user)

Note:

OS vs Username

Amazon - ec2-user

Centos - centos

Debian - admin or root

Fedora - ec2-user

RHEL - ec2-user or root

SUSE - ec2-user or root

Ubuntu - ubuntu or root

  1. For Key file field, browse your pem file: and click Connect

enter image description here

  1. That's all :) have fun!

Note:

(Remember to allow SSH connection to your IP address from EC2) If not you will get connecting error message!

Note: Allowing your IP to connect your aws instance via SFTP

EC2 -> SecurityGroups -> SSH -> Inbound rules -> Edit -> Add Rule ( SSH|TCP|22|My IP(it's get ip automatically | name for rule) -> Save

What's the difference between OpenID and OAuth?

Both protocols were created for different reasons. OAuth was created to authorize third parties to access resources. OpenID was created to perform decentralize identity validation. This website states the following:

OAuth is a protocol designed to verify the identity of an end-user and to grant permissions to a third party. This verification results in a token. The third party can use this token to access resources on the user’s behalf. Tokens have a scope. The scope is used to verify whether a resource is accessible to a user, or not

OpenID is a protocol used for decentralised authentication. Authentication is about identity; Establishing the user is in fact the person who he claims to be. Decentralising that, means this service is unaware of the existence of any resources or applications that need to be protected. That’s the key difference between OAuth and OpenID.

what are the .map files used for in Bootstrap 3.x?

The bootstrap css can be generated by Less. The main purpose of map file is used to link the css source code to less source code in the chrome dev tool. As we used to do .If we inspect the element in the chrome dev tool. you can see the source code of css. But if include the map file in the page with bootstrap css file. you can see the less code which apply to the element style you want to inspect.

Can't get Gulp to run: cannot find module 'gulp-util'

Linux Ubuntu 18:04 user here. I tried all the solutions on this board to date. Even though I read above in the accepted answer that "From later versions, there is no need to manually install gulp-util.", it was the thing that worked for me. (...maybe bc I'm on Ubuntu? I don't know. )

To recap, I kept getting the "cannot find module 'gulp-util'" error when just checking to see if gulp was installed by running:

gulp --version

...again, the 'gulp-util' error kept appearing...

So, I followed the npm install [package name] advice listed above, but ended up getting several other packages that needed to be installed as well. And one had a issue of already existing, and i wasn't sure how to replace it. ...I will put all the packages/install commands that I had to use here, just as reference in case someone else experiences this problem:

sudo npm install -g gulp-util

(then I got an error for 'pretty-hrtime' so I added that, and then the others as Error: Cannot find module ___ kept popping up after each gulp --version check. ...so I just kept installing each one.)

sudo npm install -g pretty-hrtime
sudo npm install -g chalk
sudo npm install -g semver --force

(without --force, on my system I got an error: "EEXIST: file already exists, symlink". --force is not recommended, but idk any other way. )

sudo npm install -g archy
sudo npm install -g liftoff
sudo npm install -g tildify
sudo npm install -g interpret
sudo npm install -g v8flags
sudo npm install -g minimist

And now gulp --version is finally showing: CLI version 3.9.1 Local version 3.9.1

How to try convert a string to a Guid

If all you want is some very basic error checking, you could just check the length of the string.

              string guidStr = "";
              if( guidStr.Length == Guid.Empty.ToString().Length )
                 Guid g = new Guid( guidStr );

Check if space is in a string

== takes precedence over in, so you're actually testing word == True.

>>> w = 'ab c'
>>> ' ' in w == True
1: False
>>> (' ' in w) == True
2: True

But you don't need == True at all. if requires [something that evalutes to True or False] and ' ' in word will evalute to true or false. So, if ' ' in word: ... is just fine:

>>> ' ' in w
3: True

Do you (really) write exception safe code?

Some of us have been using exception for over 20 years. PL/I has them, for example. The premise that they are a new and dangerous technology seems questionable to me.

Input type for HTML form for integer

Even if you want to accept numbers for the input, I would recommend using the text type.

<input type="text" name"some-number" />

Client-side run some jQuery validations to verify it's a number.

Then in your server side code, run some validation to verify it is in fact a numerical value.

How do I force make/GCC to show me the commands?

Build system independent method

make SHELL='sh -x'

is another option. Sample Makefile:

a:
    @echo a

Output:

+ echo a
a

This sets the special SHELL variable for make, and -x tells sh to print the expanded line before executing it.

One advantage over -n is that is actually runs the commands. I have found that for some projects (e.g. Linux kernel) that -n may stop running much earlier than usual probably because of dependency problems.

One downside of this method is that you have to ensure that the shell that will be used is sh, which is the default one used by Make as they are POSIX, but could be changed with the SHELL make variable.

Doing sh -v would be cool as well, but Dash 0.5.7 (Ubuntu 14.04 sh) ignores for -c commands (which seems to be how make uses it) so it doesn't do anything.

make -p will also interest you, which prints the values of set variables.

CMake generated Makefiles always support VERBOSE=1

As in:

mkdir build
cd build
cmake ..
make VERBOSE=1

Dedicated question at: Using CMake with GNU Make: How can I see the exact commands?

Need help rounding to 2 decimal places

The System.Math.Round method uses the Double structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:

Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)

Result: 0.58

Remove a prefix from a string

def remove_prefix(str, prefix):
    if str.startswith(prefix):
        return str[len(prefix):]
    else:
        return str

As an aside note, str is a bad name for a variable because it shadows the str type.

psql: FATAL: Peer authentication failed for user "dev"

While @flaviodesousa's answer would work, it also makes it mandatory for all users (everyone else) to enter a password.

Sometime it makes sense to keep peer authentication for everyone else, but make an exception for a service user. In that case you would want to add a line to the pg_hba.conf that looks like:

local   all             some_batch_user                         md5

I would recommend that you add this line right below the commented header line:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             some_batch_user                         md5

You will need to restart PostgreSQL using

sudo service postgresql restart

If you're using 9.3, your pg_hba.conf would most likely be:

/etc/postgresql/9.3/main/pg_hba.conf

Python progression path - From apprentice to guru

If you're in and using python for science (which it seems you are) part of that will be learning and understanding scientific libraries, for me these would be

  • numpy
  • scipy
  • matplotlib
  • mayavi/mlab
  • chaco
  • Cython

knowing how to use the right libraries and vectorize your code is essential for scientific computing.

I wanted to add that, handling large numeric datasets in common pythonic ways(object oriented approaches, lists, iterators) can be extremely inefficient. In scientific computing, it can be necessary to structure your code in ways that differ drastically from how most conventional python coders approach data.

What do .c and .h file extensions mean to C?

The .c is the source file and .h is the header file.

How to SSH into Docker?

These files will successfully open sshd and run service so you can ssh in locally. (you are using cyberduck aren't you?)

Dockerfile

FROM swiftdocker/swift
MAINTAINER Nobody

RUN apt-get update && apt-get -y install openssh-server supervisor
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

EXPOSE 22
CMD ["/usr/bin/supervisord"]

supervisord.conf

[supervisord]
nodaemon=true

[program:sshd]
command=/usr/sbin/sshd -D

to build / run start daemon / jump into shell.

docker build -t swift3-ssh .  
docker run -p 2222:22 -i -t swift3-ssh
docker ps # find container id
docker exec -i -t <containerid> /bin/bash

enter image description here

Testing two JSON objects for equality ignoring child order in Java

I'd take the library at http://json.org/java/, and modify the equals method of JSONObject and JSONArray to do a deep equality test. To make sure that it works regradless of the order of the children, all you need to do is replace the inner map with a TreeMap, or use something like Collections.sort().

How do I convert a byte array to Base64 in Java?

In case you happen to be using Spring framework along with java, there is an easy way around.

  1. Import the following.

    import org.springframework.util.Base64Utils;
  2. Convert like this.

    byte[] bytearr ={0,1,2,3,4};
    String encodedText = Base64Utils.encodeToString(bytearr);
    

    To decode you can use the decodeToString method of the Base64Utils class.

How can I use ":" as an AWK field separator?

AWK works as a text interpreter that goes linewise for the whole document and that goes fieldwise for each line. Thus $1, $2...$n are references to the fields of each line ($1 is the first field, $2 is the second field, and so on...).

You can define a field separator by using the "-F" switch under the command line or within two brackets with "FS=...".

Now consider the answer of Jürgen:

echo "1: " | awk -F  ":" '/1/ {print $1}'

Above the field, boundaries are set by ":" so we have two fields $1 which is "1" and $2 which is the empty space. After comes the regular expression "/1/" that instructs the filter to output the first field only when the interpreter stumbles upon a line containing such an expression (I mean 1).

The output of the "echo" command is one line that contains "1", so the filter will work...

When dealing with the following example:

echo "1: " | awk '/1/ -F ":" {print $1}'

The syntax is messy and the interpreter chose to ignore the part F ":" and switches to the default field splitter which is the empty space, thus outputting "1:" as the first field and there will be not a second field!

The answer of Jürgen contains the good syntax...

How can I clear the NuGet package cache using the command line?

dotnet nuget locals all --clear

If you're using .NET Core.

How to convert Java String into byte[]?

You can use String.getBytes() which returns the byte[] array.

How can I send a file document to the printer and have it print?

I know the tag says Windows Forms... but, if anyone is interested in a WPF application method, System.Printing works like a charm.

var file = File.ReadAllBytes(pdfFilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();

using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
    stream.Write(file, 0, file.Length);
}

Just remember to include System.Printing reference, if it's not already included. Now, this method does not play well with ASP.NET or Windows Service. It should not be used with Windows Forms, as it has System.Drawing.Printing. I don't have a single issue with my PDF printing using the above code.

I should mention, however, that if your printer does not support Direct Print for PDF file format, you're out of luck with this method.

How to "grep" for a filename instead of the contents of a file?

The easiest way is

find . | grep test

here find will list all the files in the (.) ie current directory, recursively. And then it is just a simple grep. all the files which name has "test" will appeared.

you can play with grep as per your requirement. Note : As the grep is generic string classification, It can result in giving you not only file names. but if a path has a directory ('/xyz_test_123/other.txt') would also comes to the result set. cheers

How to correctly use "section" tag in HTML5?

My understanding is that SECTION holds a section with a heading which is an important part of the "flow" of the page (not an aside). SECTIONs would be chapters, numbered parts of documents and so on.

ARTICLE is for syndicated content -- e.g. posts, news stories etc. ARTICLE and SECTION are completely separate -- you can have one without the other as they are very different use cases.

Another thing about SECTION is that you shouldn't use it if your page has only the one section. Also, each section must have a heading (H1-6, HGROUP, HEADING). Headings are "scoped" withing the SECTION, so e.g. if you use a H1 in the main page (outside a SECTION) and then a H1 inside the section, the latter will be treated as an H2.

The examples in the spec are pretty good at time of writing.

So in your first example would be correct if you had several sections of content which couldn't be described as ARTICLEs. (With a minor point that you wouldn't need the #primary DIV unless you wanted it for a style hook - P tags would be better).

The second example would be correct if you removed all the SECTION tags -- the data in that document would be articles, posts or something like this.

SECTIONs should not be used as containers -- DIV is still the correct use for that, and any other custom box you might come up with.

Java default constructor

A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()

public Module(){
}

How do I get DOUBLE_MAX?

You get the integer limits in <limits.h> or <climits>. Floating point characteristics are defined in <float.h> for C. In C++, the preferred version is usually std::numeric_limits<double>::max() (for which you #include <limits>).

As to your original question, if you want a larger integer type than long, you should probably consider long long. This isn't officially included in C++98 or C++03, but is part of C99 and C++11, so all reasonably current compilers support it.

Get a worksheet name using Excel VBA

This works for me.

worksheetName = ActiveSheet.Name  

"Field has incomplete type" error

The problem is that your ui property uses a forward declaration of class Ui::MainWindowClass, hence the "incomplete type" error.

Including the header file in which this class is declared will fix the problem.

EDIT

Based on your comment, the following code:

namespace Ui
{
    class MainWindowClass;
}

does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.

But the class has to be defined somewhere.

Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.

So either you actually want an incomplete type, and then you should declare your ui member as a pointer:

namespace Ui
{
    // Forward declaration - Class will have to exist at link time
    class MainWindowClass;
}

class MainWindow : public QMainWindow
{
    private:

        // Member needs to be a pointer, as it's an incomplete type
        Ui::MainWindowClass * ui;
};

Or you want a statically allocated instance of Ui::MainWindowClass, and then it needs to be declared. You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:

namespace Ui
{
    // Real class declaration - May/Should be in a specific header file
    class MainWindowClass
    {};
}


class MainWindow : public QMainWindow
{
    private:

        // Member can be statically allocated, as the type is complete
        Ui::MainWindowClass ui;
};

will also work.

Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).

Google map V3 Set Center to specific Marker

Once you have markers on the map, you can retrieve the Lat/Long coordinates through the API and use this to set the map's center. You'll first just need to determine which marker you wish to center on - I'll leave that up to you.

// "marker" refers to the Marker object you wish to center on

var latLng = marker.getPosition(); // returns LatLng object
map.setCenter(latLng); // setCenter takes a LatLng object

Info windows are separate objects which are typically bound to a marker, so to open the info window you might do something like this (however it will depend on your code):

var infoWindow = marker.infoWindow; // retrieve the InfoWindow object
infoWindow.open(map); // Trigger the "open()" method

Hope this helps.

Is it better to use NOT or <> when comparing values?

The latter (<>), because the meaning of the former isn't clear unless you have a perfect understanding of the order of operations as it applies to the Not and = operators: a subtlety which is easy to miss.

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

Set environment variables on Mac OS X Lion

Simplified Explanation

This post/question is kind of old, so I will answer a simplified version for OS X Lion users. By default, OSX Lion does not have any of the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

At most, if you've done anything in the terminal you might see ~/.bash_history

What It Means

You must create the file to set your default bash commands (commonly in ~/.bashrc). To do this, use any sort of editor, though it's more simple to do it within the terminal:

  1. %> emacs .profile
  2. [from w/in emacs type:] source ~/.bashrc
  3. [from w/in emacs type:] Ctrl + x Ctrl + s (to save the file)
  4. [from w/in emacs type:] Ctrl + x Ctrl + c (to close emacs)
  5. %> emacs .bashrc
  6. [from w/in emacs type/paste all your bash commands, save, and exit]

The next time you quit and reload the terminal, it should load all your bash preferences. For good measure, it's usually a good idea to separate your commands into useful file names. For instance, from within ~/.bashrc, you should have a source ~/.bash_aliases and put all your alias commands in ~/.bash_aliases.

Java Date - Insert into database

you can use this code date and time time is 24 h

INSERT INTO TABLE_NAME(
  date_column
)values(
  TO_DATE('2016-10-05 10:53:56', 'SYYYY-MM-DD HH24:MI:SS')
)

How can I split this comma-delimited string in Python?

Question is a little vague.

list_of_lines = multiple_lines.split("\n")
for line in list_of_lines:
    list_of_items_in_line = line.split(",")
    first_int = int(list_of_items_in_line[0])

etc.

'node' is not recognized as an internal or external command

I set the NODEJS variable in the system control panel but the only thing that worked to set the path was to do it from command line as administrator.

SET PATH=%NODEJS%;%PATH%

Another trick is that once you set the path you must close the console and open a new one for the new path to be taken into account.

However for the regular user to be able to use node I had to run set path again not as admin and restart the computer

C#: List All Classes in Assembly

Use Assembly.GetTypes. For example:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}