Programs & Examples On #Sdl image

SDL_image is an image file loading library. It loads images as SDL surfaces, and supports the following formats: BMP, GIF, JPEG, LBM, PCX, PNG, PNM, TGA, TIFF, WEBP, XCF, XPM, XV.

Refresh an asp.net page on button click

You can do Response.redirect("YourPage",false) that will refresh your page and also increase counter.

How to convert rdd object to dataframe in spark

On newer versions of spark (2.0+)

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
import org.apache.spark.sql._
import org.apache.spark.sql.types._

val spark = SparkSession
  .builder()
  .getOrCreate()
import spark.implicits._

val dfSchema = Seq("col1", "col2", "col3")
rdd.toDF(dfSchema: _*)

Undefined reference to vtable

I just ran into another cause for this error that you can check for.

The base class defined a pure virtual function as:

virtual int foo(int x = 0);

And the subclass had

int foo(int x) override;

The problem was the typo that the "=0" was supposed to be outside of the parenthesis:

virtual int foo(int x) = 0;

So, in case you're scrolling this far down, you probably didn't find the answer - this is something else to check for.

Expression must be a modifiable lvalue

You test k = M instead of k == M.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))

Easier way to create circle div than using an image?

_x000D_
_x000D_
.circle {_x000D_
 height: 20rem;_x000D_
 width: 20rem;_x000D_
 border-radius: 50%;_x000D_
 background-color: #EF6A6A;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

How do you get the length of a string?

You don't need jquery, just use yourstring.length. See reference here and also here.

Update:

To support unicode strings, length need to be computed as following:

[...""].length

or create an auxiliary function

function uniLen(s) {
    return [...s].length
}

Correct set of dependencies for using Jackson mapper

I spent few hours on this.

Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project

Simplest way to download and unzip files in Node.js cross-platform?

I was looking forward this for a long time, and found no simple working example, but based on these answers I created the downloadAndUnzip() function.

The usage is quite simple:

downloadAndUnzip('http://your-domain.com/archive.zip', 'yourfile.xml')
    .then(function (data) {
        console.log(data); // unzipped content of yourfile.xml in root of archive.zip
    })
    .catch(function (err) {
        console.error(err);
    });

And here is the declaration:

var AdmZip = require('adm-zip');
var request = require('request');

var downloadAndUnzip = function (url, fileName) {

    /**
     * Download a file
     * 
     * @param url
     */
    var download = function (url) {
        return new Promise(function (resolve, reject) {
            request({
                url: url,
                method: 'GET',
                encoding: null
            }, function (err, response, body) {
                if (err) {
                    return reject(err);
                }
                resolve(body);
            });
        });
    };

    /**
     * Unzip a Buffer
     * 
     * @param buffer
     * @returns {Promise}
     */
    var unzip = function (buffer) {
        return new Promise(function (resolve, reject) {

            var resolved = false;

            var zip = new AdmZip(buffer);
            var zipEntries = zip.getEntries(); // an array of ZipEntry records

            zipEntries.forEach(function (zipEntry) {
                if (zipEntry.entryName == fileName) {
                    resolved = true;
                    resolve(zipEntry.getData().toString('utf8'));
                }
            });

            if (!resolved) {
                reject(new Error('No file found in archive: ' + fileName));
            }
        });
    };


    return download(url)
        .then(unzip);
};

Is returning out of a switch statement considered a better practice than using break?

A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.

Split string into strings by length?

My solution

   st =' abs de fdgh  1234 556 shg shshh'
   print st

   def splitStringMax( si, limit):
    ls = si.split()
    lo=[]
    st=''
    ln=len(ls)
    if ln==1:
        return [si]
    i=0
    for l in ls:
        st+=l
        i+=1
        if i <ln:
            lk=len(ls[i])
            if (len(st))+1+lk < limit:
                st+=' '
                continue
        lo.append(st);st=''
    return lo

   ############################

   print  splitStringMax(st,7)
   # ['abs de', 'fdgh', '1234', '556', 'shg', 'shshh']
    print  splitStringMax(st,12)

   # ['abs de fdgh', '1234 556', 'shg shshh']

Displaying the Indian currency symbol on a website

use this new unicode char: &#x20b9;

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.

TypeError: 'list' object is not callable in python

If you are in a interactive session and don't want to restart you can remove the shadowing with

del list

Jquery : Refresh/Reload the page on clicking a button

Use this line simply inside your head with

       window.location.reload(true);

It will load your current page or view.

Find unique rows in numpy.array

The most straightforward solution is to make the rows a single item by making them strings. Each row then can be compared as a whole for its uniqueness using numpy. This solution is generalize-able you just need to reshape and transpose your array for other combinations. Here is the solution for the problem provided.

import numpy as np

original = np.array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0]])

uniques, index = np.unique([str(i) for i in original], return_index=True)
cleaned = original[index]
print(cleaned)    

Will Give:

 array([[0, 1, 1, 1, 0, 0],
        [1, 1, 1, 0, 0, 0],
        [1, 1, 1, 1, 1, 0]])

Send my nobel prize in the mail

AngularJs $http.post() does not send data

In my case I resolve the problem like this :

var deferred = $q.defer();

$http({
    method: 'POST',
    url: 'myUri', 
    data: $.param({ param1: 'blablabla', param2: JSON.stringify(objJSON) }),
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(
    function(res) {
        console.log('succes !', res.data);
        deferred.resolve(res.data);
    },
    function(err) {
        console.log('error...', err);
        deferred.resolve(err);
    }
);
return deferred.promise;

You need to use JSON.stringify for each param containing a JSON object, and then build your data object with "$.param" :-)

NB : My "objJSON" is a JSON object containing array, integer, string and html content. His total size is >3500 characters.

How to rename a file using Python

import os

# Set the path
path = 'a\\b\\c'  
# save current working directory
saved_cwd = os.getcwd()
# change your cwd to the directory which contains files
os.chdir(path)
os.rename('a.txt', 'b.klm')
# moving back to the directory you were in 
os.chdir(saved_cwd)

convert UIImage to NSData

Solution in Swift 4

extension UIImage {
    var data : Data? {
      return cgImage?.dataProvider?.data as Data?
    }
}

tmux status bar configuration

I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.

Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

I don't understand why nobody points to the specific issue and some answers are totally misleading, especially the accepted answer. The issue is that the OP did not pick a rule that could possibly override the margin property that is set by the User Agent (UA) directly on the ul tag. Let's consider all the rules with a margin property used by the OP.

body {

margin:0px;
...
}

The body element is way up in the DOM and the UA rule matches an element below, so the UA wins. It's the way inheritance works. Inheritance is the means by which, in the absence of any specific declarations from any source applied by the CSS cascade, a property value of an element is obtained from its parent element. Specificity on the parent element is useless, because the UA rule matches directly the element.

#mainNav{
    margin:0 auto;
    ...
}

This is a better attempt, a more specific selector #mainNav, which matches the mainNav element lower in the DOM, but the same principle applies, because the ul element is still below this element in the DOM.

#mainNav ul li{
    ...
    margin:0;
    ...
}

This went too far down in the DOM! Now, the selector matches the li element, which is below the ul element.

So, assuming that the UA rule used the selector ul and not !important, which is most likely the case, the solution would have been a simple ul { margin: 0; }, but it would be safer to make it more specific, say #mainNav ul { margin: 0 }.

Differences between JDK and Java SDK

Best example for this Question, SDK - Software Development Kit - Ex: Netbeans JDK - Java Development Kit.(This is Java compiler). Without JDK, we unable to run java programs in SDK.

HTML table headers always visible at top of window when viewing a large table

Craig, I refined your code a bit (among a few other things it's now using position:fixed) and wrapped it as a jQuery plugin.

Try it out here: http://jsfiddle.net/jmosbech/stFcx/

And get the source here: https://github.com/jmosbech/StickyTableHeaders

Image comparison - fast algorithm

The best method I know of is to use a Perceptual Hash. There appears to be a good open source implementation of such a hash available at:

http://phash.org/

The main idea is that each image is reduced down to a small hash code or 'fingerprint' by identifying salient features in the original image file and hashing a compact representation of those features (rather than hashing the image data directly). This means that the false positives rate is much reduced over a simplistic approach such as reducing images down to a tiny thumbprint sized image and comparing thumbprints.

phash offers several types of hash and can be used for images, audio or video.

Node: log in a file instead of the console

I took on the idea of swapping the output stream to a my stream.

const LogLater                = require ('./loglater.js');
var logfile=new LogLater( 'log'+( new Date().toISOString().replace(/[^a-zA-Z0-9]/g,'-') )+'.txt' );


var PassThrough = require('stream').PassThrough;

var myout= new PassThrough();
var wasout=console._stdout;
myout.on('data',(data)=>{logfile.dateline("\r\n"+data);wasout.write(data);});
console._stdout=myout;

var myerr= new PassThrough();
var waserr=console._stderr;
myerr.on('data',(data)=>{logfile.dateline("\r\n"+data);waserr.write(data);});
console._stderr=myerr;

loglater.js:

const fs = require('fs');

function LogLater(filename, noduplicates, interval) {
    this.filename = filename || "loglater.txt";
    this.arr = [];
    this.timeout = false;
    this.interval = interval || 1000;
    this.noduplicates = noduplicates || true;
    this.onsavetimeout_bind = this.onsavetimeout.bind(this);
    this.lasttext = "";
    process.on('exit',()=>{ if(this.timeout)clearTimeout(this.timeout);this.timeout=false; this.save(); })
}

LogLater.prototype = {
    _log: function _log(text) {
        this.arr.push(text);
        if (!this.timeout) this.timeout = setTimeout(this.onsavetimeout_bind, this.interval);
    },
    text: function log(text, loglastline) {
        if (this.noduplicates) {
            if (this.lasttext === text) return;
            this.lastline = text;
        }
        this._log(text);
    },
    line: function log(text, loglastline) {
        if (this.noduplicates) {
            if (this.lasttext === text) return;
            this.lastline = text;
        }
        this._log(text + '\r\n');
    },
    dateline: function dateline(text) {
        if (this.noduplicates) {
            if (this.lasttext === text) return;
            this.lastline = text;
        }
        this._log(((new Date()).toISOString()) + '\t' + text + '\r\n');
    },
    onsavetimeout: function onsavetimeout() {
        this.timeout = false;
        this.save();
    },
    save: function save() { fs.appendFile(this.filename, this.arr.splice(0, this.arr.length).join(''), function(err) { if (err) console.log(err.stack) }); }
}

module.exports = LogLater;

Cell color changing in Excel using C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

Select method of Range class failed via VBA

The correct answer to this particular questions is "don't select". Sometimes you have to select or activate, but 99% of the time you don't. If your code looks like

Select something
Do something to the selection
Select something else
Do something to the selection

You probably need to refactor and consider not selecting.

The error, Method 'Range' of object '_Worksheet' failed, error 1004, that you're getting is because the sheet with the button on it doesn't have a range named "Result". Most (maybe all) properties that return an object have a default Parent object. In this case, you're using the Range property to return a Range object. Because you don't qualify the Range property, Excel uses the default.

The default Parent object can be different based on the circumstances. If your code were in a standard module, then the ActiveSheet would be the default Parent and Excel would try to resolve ActiveSheet.Range("Result"). Your code is in a sheet's class module (the sheet with the button on it). When the unqualified reference is used there, the default Parent is the sheet that's attached to that module. In this case they're the same because the sheet has to be active to click the button, but that isn't always the case.

When Excel gives the error that includes text like '_Object' (yours said '_Worksheet') it's always referring to the default Parent object - the underscore gives that away. Generally the way to fix that is to qualify the reference by being explicit about the parent. But in the case of selecting and activating when you don't need to, it's better to just refactor the code.

Here's one way to write your code without any selecting or activating.

Private Sub cmdRecord_Click()

    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim rNext As Range

    'Me refers to the sheet whose class module you're in
    'Me.Parent refers to the workbook
    Set shSource = Me.Parent.Worksheets("BxWsn Simulation")
    Set shDest = Me.Parent.Worksheets("Reslt Record")

    Set rNext = shDest.Cells(shDest.Rows.Count, 1).End(xlUp).Offset(1, 0)

    shSource.Range("Result").Copy
    rNext.PasteSpecial xlPasteFormulasAndNumberFormats

    Application.CutCopyMode = False

End Sub

When I'm in a class module, like the sheet's class module that you're working in, I always try to do things in terms of that class. So I use Me.Parent instead of ActiveWorkbook. It makes the code more portable and prevents unexpected problems when things change.

I'm sure the code you have now runs in milliseconds, so you may not care, but avoiding selecting will definitely speed up your code and you don't have to set ScreenUpdating. That may become important as your code grows or in a different situation.

How do I get column datatype in Oracle with PL-SQL with low privileges?

Quick and dirty way (e.g. to see how data is stored in oracle)

SQL> select dump(dummy) dump_dummy, dummy
     , dump(10) dump_ten
from dual

DUMP_DUMMY       DUMMY DUMP_TEN            
---------------- ----- --------------------
Typ=1 Len=1: 88  X     Typ=2 Len=2: 193,11 
1 row selected.

will show that dummy column in table sys.dual has typ=1 (varchar2), while 10 is Typ=2 (number).

How to center a checkbox in a table cell?

Define the float property of the check element to none:

float: none;

And center the parent element:

text-align: center;

It was the only that works for me.

How to convert seconds to HH:mm:ss in moment.js

var seconds = 2000 ; // or "2000"
seconds = parseInt(seconds) //because moment js dont know to handle number in string format
var format =  Math.floor(moment.duration(seconds,'seconds').asHours()) + ':' + moment.duration(seconds,'seconds').minutes() + ':' + moment.duration(seconds,'seconds').seconds();

Regex Match all characters between two strings

for a quick search in VIM, you could use at Vim Control prompt: /This is.*\_.*sentence

How to check which locks are held on a table

You can also use the built-in sp_who2 stored procedure to get current blocked and blocking processes on a SQL Server instance. Typically you'd run this alongside a SQL Profiler instance to find a blocking process and look at the most recent command that spid issued in profiler.

How to use icons and symbols from "Font Awesome" on Native Android Application

The FontView library lets you use normal/unicode font characters as icons/graphics in your app. It can load the font via assets or a network location.

The benefit of this library is that:

1 - it takes care of remote resources for you
2 - scales the font size in dynamically sized views
3 - allows the font to easily be styled.

https://github.com/shellum/fontView

Example:

Layout:

<com.finalhack.fontview.FontView
        android:id="@+id/someActionIcon"
        android:layout_width="80dp"
        android:layout_height="80dp" />

Java:

fontView.setupFont("fonts/font.ttf", character, FontView.ImageType.CIRCLE);
fontView.addForegroundColor(Color.RED);
fontView.addBackgroundColor(Color.WHITE);

Use jquery to set value of div tag

To put text, use .text('text')

If you want to use .html(SomeValue), SomeValue should have html tags that can be inside a div it must work too.

Just check your script location, as farzad said.

Reference: .html and text

Converting .NET DateTime to JSON

Thought i'd add my solution that i've been using.

If you're using the System.Web.Script.Serialization.JavaScriptSerializer() then the time returned isn't going to be specific to your timezone. To fix this you'll also want to use dte.getTimezoneOffset() to get it back to your correct time.

String.prototype.toDateFromAspNet = function() {
    var dte = eval("new " + this.replace(/\//g, '') + ";");
    dte.setMinutes(dte.getMinutes() - dte.getTimezoneOffset());
    return dte;
}

now you'll just call

"/Date(1245398693390)/".toDateFromAspNet();

Fri Jun 19 2009 00:04:53 GMT-0400 (Eastern Daylight Time) {}

Where do I get servlet-api.jar from?

You can find a recent servlet-api.jar in Tomcat 6 or 7 lib directory. If you don't have Tomcat on your machine, download the binary distribution of version 6 or 7 from http://tomcat.apache.org/download-70.cgi

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Delete the line "/*# sourceMappingURL=bootstrap.min.css.map */ " in following files.

  • css/bootstrap.min.css
  • css/bootstrap.css

To fetch the file path in Linux use the command find / -name "\*bootstrap\*"

Getting Current time to display in Label. VB.net

Try This.....

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub

Generate insert script for selected records?

CREATE PROCEDURE sp_generate_insertscripts
(
    @TABLENAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)=''   -- where TableId = 5 or some value
)
AS
BEGIN

SET NOCOUNT ON

DECLARE @TABLE_NAME VARCHAR(MAX),
        @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @TEXT VARCHAR(MAX),
        @FILTER VARCHAR(MAX) 

SET @TABLE_NAME=@TABLENAME

SELECT @FILTER=@FILTER_CONDITION

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER

--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT

EXECUTE (@TEXT)

SET NOCOUNT OFF

END

Passing event and argument to v-on in Vue.js

If you want to access event object as well as data passed, you have to pass event and ticket.id both as parameters, like following:

HTML

<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">

Javascript

methods: {
  addToCart: function (event, id) {
    // use event here as well as id
    console.log('In addToCart')
    console.log(id)
  }
}

See working fiddle: https://jsfiddle.net/nee5nszL/

Edited: case with vue-router

In case you are using vue-router, you may have to use $event in your v-on:input method like following:

<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">

Here is working fiddle.

How to execute a stored procedure within C# program

using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) { 
                           CommandType = CommandType.StoredProcedure }) {
   conn.Open();
   command.ExecuteNonQuery();
}

How do I calculate the MD5 checksum of a file in Python?

You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest(). A function to do this would look like the following:

def File_Checksum_Dis(dirname):
    
    if not os.path.exists(dirname):
        print(dirname+" directory is not existing");
    
    for fname in os.listdir(dirname):
        if not fname.endswith('~'):
            fnaav = os.path.join(dirname, fname);
            fd = open(fnaav, 'rb');
            data = fd.read();
            fd.close();
        
            print("-"*70);
            print("File Name is: ",fname);          
            print(hashlib.md5(data).hexdigest())
            print("-"*70);
                

Select Tag Helper in ASP.NET Core MVC

In Get:

public IActionResult Create()
{
    ViewData["Tags"] = new SelectList(_context.Tags, "Id", "Name");
    return View();
}

In Post:

var selectedIds= Request.Form["Tags"];

In View :

<label>Tags</label>
<select  asp-for="Tags"  id="Tags" name="Tags" class="form-control" asp-items="ViewBag.Tags" multiple></select>

How to use bluetooth to connect two iPhone?

Check out the BeamIt open source project. It will connect via bluetooth and WIFI (although it claims it does not do WIFI) and I have verified that it works well in my projects. It will allow peer to peer contact easily.

As for multiple connections, it is possible, but you will have to edit the BeamIt source code to make it possible. I suggest reading the GameKit programming guide

Giving a border to an HTML table row, <tr>

adding border-spacing: 0rem 0.5rem; creates a space for each cell (td, th) items on its bottom while leaving no space between the cells

    table.app-table{
        border-collapse: separate;
        border-spacing: 0rem 0.5rem;
    }
    table.app-table thead tr.border-row the,
    table.app-table tbody tr.border-row td,
    table.app-table tbody tr.border-row th{
        border-top: 1px solid #EAEAEA;
        border-bottom: 1px solid #EAEAEA;
        vertical-align: middle;
        white-space: nowrap;
        font-size: 0.875rem;
    }

    table.app-table thead tr.border-row th:first-child,
    table.app-table tbody tr.border-row td:first-child{
        border-left: 1px solid #EAEAEA;
    }

    table.app-table thead tr.border-row th:last-child,
    table.app-table tbody tr.border-row td:last-child{
        border-right: 1px solid #EAEAEA;
    }

How to initialize a list with constructor?

Are you looking for this?

ContactNumbers = new List<ContactNumber>(){ new ContactNumber("555-5555"),
                                            new ContactNumber("555-1234"),
                                            new ContactNumber("555-5678") };

How to start new line with space for next line in Html.fromHtml for text view in android

use <br/> tag

Example:

<string name="copyright"><b>@</b> 2014 <br/>
Corporation.<br/>
<i>All rights reserved.</i></string>

How to delete large data of table in SQL without log?

I was able to delete 19 million rows from my table of 21 million rows in matter of minutes. Here is my approach.

If you have a auto-incrementing primary key on this table, then you can make use of this primary key.

  1. Get minimum value of primary key of the large table where readTime < dateadd(MONTH,-7,GETDATE()). (Add index on readTime, if not already present, this index will anyway be deleted along with the table in step 3.). Lets store it in a variable 'min_primary'

  2. Insert all the rows having primary key > min_primary into a staging table (memory table if no. of rows is not large).

  3. Drop the large table.

  4. Recreate the table. Copy all the rows from staging table to main table.

  5. Drop the staging table.

Django gives Bad Request (400) when DEBUG = False

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

python manage.py runserver --insecure

Asp.net MVC ModelState.Clear

Well the ModelState basically holds the current State of the model in terms of validation, it holds

ModelErrorCollection: Represent the errors when the model try to bind the values. ex.

TryUpdateModel();
UpdateModel();

or like a parameter in the ActionResult

public ActionResult Create(Person person)

ValueProviderResult: Hold the details about the attempted bind to the model. ex. AttemptedValue, Culture, RawValue.

Clear() method must be use with caution because it can lead to unspected results. And you will lose some nice properties of the ModelState like AttemptedValue, this is used by MVC in the background to repopulate the form values in case of error.

ModelState["a"].Value.AttemptedValue

Adding two numbers concatenates them instead of calculating the sum

You need to use javaScript's parseInt() method to turn the strings back into numbers. Right now they are strings so adding two strings concatenates them, which is why you're getting "12".

How do I get java logging output to appear on a single line?

Similar to Tervor, But I like to change the property on runtime.

Note that this need to be set before the first SimpleFormatter is created - as was written in the comments.

    System.setProperty("java.util.logging.SimpleFormatter.format", 
            "%1$tF %1$tT %4$s %2$s %5$s%6$s%n");

How to compare two strings are equal in value, what is the best method?

Not forgetting

.equalsIgnoreCase(String)

if you're not worried about that sort of thing...

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

This code will work for python 3 and above

file=open("filename.txt")   
f=file.readlines()   #reads all lines from the file
EOF=-1   #represents end of file
temp=0
for k in range(len(f)-1,-1,-1):
    if temp==0:
        if f[k]=="\n":
            EOF=k
        else:
            temp+=1
print("Given file has",EOF,"lines")
file.close()

How do you concatenate Lists in C#?

Take a look at my implementation. It's safe from null lists.

 IList<string> all= new List<string>();

 if (letterForm.SecretaryPhone!=null)// first list may be null
     all=all.Concat(letterForm.SecretaryPhone).ToList();

 if (letterForm.EmployeePhone != null)// second list may be null
     all= all.Concat(letterForm.EmployeePhone).ToList(); 

 if (letterForm.DepartmentManagerName != null) // this is not list (its just string variable) so wrap it inside list then concat it 
     all = all.Concat(new []{letterForm.DepartmentManagerPhone}).ToList();

Convert string with commas to array

use the built-in map function with an anonymous function, like so:

string.split(',').map(function(n) {return Number(n);});

[edit] here's how you would use it

var string = "0,1";
var array = string.split(',').map(function(n) {
    return Number(n);
});
alert( array[0] );

How can I add numbers in a Bash script?

You should declare metab as integer and then use arithmetic evaluation

declare -i metab num
...
num+=metab
...

For more information see https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic

Access HTTP response as string in Go

string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.

How can I select all options of multi-select select box on click?

Working Demo

$('#select_all').click( function() {
    $('select#countries > option').prop('selected', 'selected');
});

If you use jQuery older than 1.6:

$('#select_all').click( function() {
    $('select#countries > option').attr('selected', 'selected');
});

how do I give a div a responsive height

I know this is a little late to the party but you could use viewport units

From caniuse.com:

Viewport units: vw, vh, vmin, vmax - CR Length units representing 1% of the viewport size for viewport width (vw), height (vh), the smaller of the two (vmin), or the larger of the two (vmax).

Support: http://caniuse.com/#feat=viewport-units

_x000D_
_x000D_
div {_x000D_
/* 25% of viewport */_x000D_
  height: 25vh;_x000D_
  width: 15rem;_x000D_
  background-color: #222;_x000D_
  color: #eee;_x000D_
  font-family: monospace;_x000D_
  padding: 2rem;_x000D_
}
_x000D_
<div>responsive height</div>
_x000D_
_x000D_
_x000D_

C++ alignment when printing cout <<

C++20 std::format options <, ^ and >

According to https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification the following should hold:

// left: "42    "
std::cout << std::format("{:<6}", 42);

// right: "    42"
std::cout << std::format("{:>6}", 42);

// center: "  42  "
std::cout << std::format("{:^6}", 42);

More information at: std::string formatting like sprintf

How do I get the Back Button to work with an AngularJS ui-router state machine?

app.run(['$window', '$rootScope', 
function ($window ,  $rootScope) {
  $rootScope.goBack = function(){
    $window.history.back();
  }
}]);

<a href="#" ng-click="goBack()">Back</a>

JavaScript onclick redirect

Change the onclick from

onclick="javascript:SubmitFrm()"

to

onclick="SubmitFrm()"

Color theme for VS Code integrated terminal

Simply. You can go to 'File -> Preferences -> Color Theme' option in visual studio and change the color of you choice.

HTML5 Video autoplay on iPhone

I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.

  1. Using dangerouslySetInnerHtml to embed the <video> code. For example:
<div dangerouslySetInnerHTML={{ __html: `
    <video class="video-js" playsinline autoplay loop muted>
        <source src="../video_path.mp4" type="video/mp4"/>
    </video>`}}
/>
  1. Resizing the video weight. I noticed my iPhone does not autoplay videos over 3 megabytes. So I used an online compressor tool (https://www.mp4compress.com/) to go from 4mb to less than 500kb

Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)

Chrome:The website uses HSTS. Network errors...this page will probably work later

I recently had the same issue while trying to access domains using CloudFlare Origin CA.

The only way I found to workaround/avoid HSTS cert exception on Chrome (Windows build) was following the short instructions in https://support.opendns.com/entries/66657664.

The workaround:
Add to Chrome shortcut the flag --ignore-certificate-errors, then reopen it and surf to your website.

Reminder:
Use it only for development purposes.

enter image description here

How do I make calls to a REST API using C#?

The ASP.NET Web API has replaced the WCF Web API previously mentioned.

I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service C#".

Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.

Here's how your example would look when implemented using the ASP.NET Web API Client Library:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ConsoleProgram
{
    public class DataObject
    {
        public string Name { get; set; }
    }

    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json";
        private string urlParameters = "?api_key=123";

        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync(urlParameters).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body.
                var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll
                foreach (var d in dataObjects)
                {
                    Console.WriteLine("{0}", d.Name);
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            // Make any other calls using HttpClient here.

            // Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
            client.Dispose();
        }
    }
}

If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: Do HttpClient and HttpClientHandler have to be disposed between requests?

For more details, including other examples, see Call a Web API From a .NET Client (C#)

This blog post may also be useful: Using HttpClient to Consume ASP.NET Web API REST Services

Kubernetes how to make Deployment to update image

kubectl rollout restart deployment myapp

This is the current way to trigger a rolling update and leave the old replica sets in place for other operations provided by kubectl rollout like rollbacks.

Differences between action and actionListener

As BalusC indicated, the actionListener by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.

This happens through a call like this:

context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,                                                          
    new ExceptionQueuedEventContext(context, exception, source, phaseId)
);

The default listener for this event is the ExceptionHandler which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.

This ExceptionHandler can be replaced however in faces-config.xml with a custom implementation:

<exception-handlerfactory>
   com.foo.myExceptionHandler
</exception-handlerfactory>

Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:

@ManagedBean
@RequestScoped
public class MyBean {

    public void actionMethod(ActionEvent event) {

        FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {

        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
            ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
            throw new RuntimeException(content.getException());
        }

        @Override
        public boolean isListenerForSource(Object source) {
            return true;
        }
        });

        throw new RuntimeException("test");
    }

}

(note, this is not how one should normally code listeners, this is only for demonstration purposes!)

Calling this from a Facelet like this:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <h:form>
            <h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
        </h:form>
    </h:body>
</html>

Will result in an error page being displayed.

Does adding a duplicate value to a HashSet/HashMap replace the previous value

The first thing you need to know is that HashSet acts like a Set, which means you add your object directly to the HashSet and it cannot contain duplicates. You just add your value directly in HashSet.

However, HashMap is a Map type. That means every time you add an entry, you add a key-value pair.

In HashMap you can have duplicate values, but not duplicate keys. In HashMap the new entry will replace the old one. The most recent entry will be in the HashMap.

Understanding Link between HashMap and HashSet:

Remember, HashMap can not have duplicate keys. Behind the scene HashSet uses a HashMap.

When you attempt to add any object into a HashSet, this entry is actually stored as a key in the HashMap - the same HashMap that is used behind the scene of HashSet. Since this underlying HashMap needs a key-value pair, a dummy value is generated for us.

Now when you try to insert another duplicate object into the same HashSet, it will again attempt to be insert it as a key in the HashMap lying underneath. However, HashMap does not support duplicates. Hence, HashSet will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.

Summary:

HashMap allows duplicate values, but not keys. HashSet cannot contains duplicates.

To play with whether the addition of an object is successfully completed or not, you can check the boolean value returned when you call .add() and see if it returns true or false. If it returned true, it was inserted.

Python Tkinter clearing a frame

https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html

w.winfo_children()
Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top).

for widget in frame.winfo_children():
    widget.destroy()

Will destroy all the widget in your frame. No need for a second frame.

Changing width property of a :before css selector using JQuery

The answer should be Jain. You can not select an element via pseudo-selector, but you can add a new rule to your stylesheet with insertRule.

I made something that should work for you:

var addRule = function(sheet, selector, styles) {
    if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
    if (sheet.addRule) return sheet.addRule(selector, styles);
};

addRule(document.styleSheets[0], "body:before", "content: 'foo'");

http://fiddle.jshell.net/MDyxg/1/

To be super-cool (and to answer the question really) I rolled it out again and wrapped this in a jQuery-plugin (however, jquery is still not required!):

/*!
 * jquery.addrule.js 0.0.1 - https://gist.github.com/yckart/5563717/
 * Add css-rules to an existing stylesheet.
 *
 * @see http://stackoverflow.com/a/16507264/1250044
 *
 * Copyright (c) 2013 Yannick Albert (http://yckart.com)
 * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
 * 2013/05/12
 **/

(function ($) {

    window.addRule = function (selector, styles, sheet) {

        styles = (function (styles) {
            if (typeof styles === "string") return styles;
            var clone = "";
            for (var p in styles) {
                if (styles.hasOwnProperty(p)) {
                    var val = styles[p];
                    p = p.replace(/([A-Z])/g, "-$1").toLowerCase(); // convert to dash-case
                    clone += p + ":" + (p === "content" ? '"' + val + '"' : val) + "; ";
                }
            }
            return clone;
        }(styles));
        sheet = sheet || document.styleSheets[document.styleSheets.length - 1];

        if (sheet.insertRule) sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        else if (sheet.addRule) sheet.addRule(selector, styles);

        return this;

    };

    if ($) $.fn.addRule = function (styles, sheet) {
        addRule(this.selector, styles, sheet);
        return this;
    };

}(window.jQuery));

The usage is quite simple:

$("body:after").addRule({
    content: "foo",
    color: "red",
    fontSize: "32px"
});

// or without jquery
addRule("body:after", {
    content: "foo",
    color: "red",
    fontSize: "32px"
});

https://gist.github.com/yckart/5563717

How can I convert a Timestamp into either Date or DateTime object?

java.time

Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.

For your work we need a time zone and a couple of formatters. We may as well declare them static:

static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");

Now the code could be for example:

    while(resultSet.next()) {
        ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                 .atZoneSameInstant(zone);

        // I would like to then have the date and time
        // converted into the formats mentioned...
        String dateFormatted = dtStart.format(dateFormatter);
        String timeFormatted = dtStart.format(timeFormatter);
        System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
    }

Example output (using the time your question was asked):

Date: 09/20/2011; time: 18:13 -0400

In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.

If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:

        ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                 .atZone(zone);

No matter the details I trust you to do similarly for dtEnd.

I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Saving images in Python at a very high quality

In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:

Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:

import seaborn as sb

image = sb.heatmap(matrix)   # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png")   # This saves it

This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.

Another way I like is this. I set the size of the next image as follows:

plt.subplots(figsize=(15,15))

And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)

Sorting using Comparator- Descending order (User defined classes)

I would create a comparator for the person class that can be parametrized with a certain sorting behaviour. Here I can set the sorting order but it can be modified to allow sorting for other person attributes as well.

public class PersonComparator implements Comparator<Person> {

  public enum SortOrder {ASCENDING, DESCENDING}

  private SortOrder sortOrder;

  public PersonComparator(SortOrder sortOrder) {
    this.sortOrder = sortOrder;
  }

  @Override
  public int compare(Person person1, Person person2) {
    Integer age1 = person1.getAge();
    Integer age2 = person2.getAge();
    int compare = Math.signum(age1.compareTo(age2));

    if (sortOrder == ASCENDING) {
      return compare;
    } else {
      return compare * (-1);
    }
  }
}

(hope it compiles now, I have no IDE or JDK at hand, coded 'blind')

Edit

Thanks to Thomas, edited the code. I wouldn't say that the usage of Math.signum is good, performant, effective, but I'd like to keep it as a reminder, that the compareTo method can return any integer and multiplying by (-1) will fail if the implementation returns Integer.MIN_INTEGER... And I removed the setter because it's cheap enough to construct a new PersonComparator just when it's needed.

But I keep the boxing because it shows that I rely on an existing Comparable implementation. Could have done something like Comparable<Integer> age1 = new Integer(person1.getAge()); but that looked too ugly. The idea was to show a pattern which could easily be adapted to other Person attributes, like name, birthday as Date and so on.

Eloquent ORM laravel 5 Get Array of ids

From a Collection, another way you could do it would be:

$collection->pluck('id')->toArray()

This will return an indexed array, perfectly usable by laravel in a whereIn() query, for instance.

How to check if a character is upper-case in Python?

To test that all words start with an upper case use this:

print all(word[0].isupper() for word in words)

What is a "static" function in C?

A static function is one that can be called on the class itself, as opposed to an instance of the class.

For example a non-static would be:

Person* tom = new Person();
tom->setName("Tom");

This method works on an instance of the class, not the class itself. However you can have a static method that can work without having an instance. This is sometimes used in the Factory pattern:

Person* tom = Person::createNewPerson();

Passing Javascript variable to <a href >

You can also use an express framework

app.get("/:id",function(req,res)
{
  var id = req.params.id;
  res.render("home.ejs",{identity : id});
});

Express file, which receives a JS variable identity from node.js

<a href = "/any_route/<%=identity%> includes identity JS variable into your href without a trouble enter

SQL ORDER BY multiple columns

The results are ordered by the first column, then the second, and so on for as many columns as the ORDER BY clause includes. If you want any results sorted in descending order, your ORDER BY clause must use the DESC keyword directly after the name or the number of the relevant column.

Check out this Example

SELECT first_name, last_name, hire_date, salary 
FROM employee 
ORDER BY hire_date DESC,last_name ASC;

It will order in succession. Order the Hire_Date first, then LAST_NAME it by Hire_Date .

How can I convert integer into float in Java?

Sameer:

float l = new Float(x/y)

will not work, as it will compute integer division of x and y first, then construct a float from it.

float result = (float) x / (float) y;

Is semantically the best candidate.

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

Change a Git remote HEAD to point to something besides master

Since you mention GitHub, to do it on their site simply go into your project, then...

admin > Default Branch > (choose something)

Done.

Return Type for jdbcTemplate.queryForList(sql, object, classType)

queryForList returns a List of LinkedHashMap objects.

You need to cast it first like this:


    List list = jdbcTemplate.queryForList(...);
    for (Object o : list) {
       Map m = (Map) o;
       ...
    }

Loading DLLs at runtime in C#

You need to create an instance of the type that expose the Output method:

static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var class1Type = DLL.GetType("DLL.Class1");

        //Now you can use reflection or dynamic to call the method. I will show you the dynamic way

        dynamic c = Activator.CreateInstance(class1Type);
        c.Output(@"Hello");

        Console.ReadLine();
     }

Uncaught SyntaxError: Unexpected token :

This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.

Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.

Persist javascript variables across pages?

Yes, using Cookies. But be careful, don't put too much in them (I think there is a limit at 4kb). But a few variables are ok.

If you need to store considerably more than that, check out @Annie's great tips in the other answer. For small time data storage, I would say Cookies are the easiest thing.

Note that cookies are stored client side.

How to get all files under a specific directory in MATLAB?

You're looking for dir to return the directory contents.

To loop over the results, you can simply do the following:

dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

This should give you output in the following format, e.g.:

name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []

iPhone: How to get current milliseconds?

Swift 2

let seconds = NSDate().timeIntervalSince1970
let milliseconds = seconds * 1000.0

Swift 3

let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds

When do I use path params vs. query params in a RESTful API?

Generally speaking, I tend to use path parameters when there is an obvious 'hierarchy' in the resource, such as:

/region/state/42

If that single resource has a status, one could:

/region/state/42/status

However, if 'region' is not really part of the resource being exposed, it probably belongs as one of the query parameters - similar to pagination (as you mentioned).

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Just add the following rules to the parent element:

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

Here's a sample demo (Resize window to see the image align)

Browser support for Flexbox nowadays is quite good.

For cross-browser compatibility for display: flex and align-items, you can add the older flexbox syntax as well:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

How do I search a Perl array for a matching string?

If you will be doing many searches of the array, AND matching always is defined as string equivalence, then you can normalize your data and use a hash.

my @strings = qw( aAa Bbb cCC DDD eee );

my %string_lut;

# Init via slice:
@string_lut{ map uc, @strings } = ();

# or use a for loop:
#    for my $string ( @strings ) {
#        $string_lut{ uc($string) } = undef;
#    }


#Look for a string:

my $search = 'AAa';

print "'$string' ", 
    ( exists $string_lut{ uc $string ? "IS" : "is NOT" ),
    " in the array\n";

Let me emphasize that doing a hash lookup is good if you are planning on doing many lookups on the array. Also, it will only work if matching means that $foo eq $bar, or other requirements that can be met through normalization (like case insensitivity).

what is the difference between ajax and jquery and which one is better?

Ajax is a technology / paradigm, whereas jquery is a library (which provides - besides other nice functionality - a convenient wrapper around ajax) - thus you can't compare them.

How does one sum only those rows in excel not filtered out?

If you aren't using an auto-filter (i.e. you have manually hidden rows), you will need to use the AGGREGATE function instead of SUBTOTAL.

How to remove .html from URL?

Resorting to using .htaccess to rewrite the URLs for static HTML is generally not only unnecessary, but also bad for you website's performance. Enabling .htaccess is also an unnecessary security vulnerability - turning it off eliminates a significant number of potential issues. The same rules for each .htaccess file can instead go in a <Directory> section for that directory, and it will be more performant if you then set AllowOverride None because it won't need to check each directory for a .htaccess file, and more secure because an attacker can't change the vhost config without root access.

If you don't need .htaccess in a VPS environment, you can disable it entirely and get better performance from your web server.

All you need to do is move your individual files from a structure like this:

index.html
about.html
products.html
terms.html

To a structure like this:

index.html
about/index.html
products/index.html
terms/index.html

Your web server will then render the appropriate pages - if you load /about/, it will treat that as /about/index.html.

This won't rewrite the URL if anyone visits the old one, though, so it would need redirects to be in place if it was retroactively applied to an existing site.

How to get build time stamp from Jenkins build variables?

NOTE: This changed in Jenkins 1.597, Please see here for more info regarding the migration

You should be able to view all the global environment variables that are available during the build by navigating to https://<your-jenkins>/env-vars.html.

Replace https://<your-jenkins>/ with the URL you use to get to Jenkins webpage (for example, it could be http://localhost:8080/env-vars.html).

One of the environment variables is :

BUILD_ID
    The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss)

If you use jenkins editable email notification, you should be able to use ${ENV, var="BUILD_ID"} in the subject line of your email.

Port 443 in use by "Unable to open process" with PID 4

I had the same problem when I installed xampp on Windows 7. I installed Windows server and Web Deployment Agent Service (MsDepSvc.exe) which uses port 80. So I had an error PID 4 listening to port 80 when I ran apache.

Solution

Open task manager: (Ctrl+Shift+Esc) then find "MsDepSvc.exe" and disable it. Finally restart xampp

ref: http://www.honk.com.au/index.php/2010/10/20/windows-7-pid-4-listening-port-80-apache-cannot-star/

How to loop through a collection that supports IEnumerable?

Maybe you forgot the await before returning your collection

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

How to get a user's client IP address in ASP.NET?

UPDATE: Thanks to Bruno Lopes. If several ip addresses could come then need to use this method:

    private string GetUserIP()
    {
        string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrEmpty(ipList))
        {
            return ipList.Split(',')[0];
        }

        return Request.ServerVariables["REMOTE_ADDR"];
    }

SQL Server Operating system error 5: "5(Access is denied.)"

Yes,It's right.The first you should find out your service account of sqlserver,you can see it in Task Manager when you press ctrl+alt+delete at the same time;Then,you must give the read/write privilege of "C:\Murach\SQL Server 2008\Databases" to the service account.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

The IEnumerable<T> interface does not include an indexer, you're probably confusing it with IList<T>

If the object really is an IList<T> (e.g. List<T> or an array T[]), try making the reference to it of type IList<T> too.

Otherwise, you can use myEnumerable.ElementAt(index) which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>s . Note that unless the (run-time) object implements IList<T>, this will cause all of the first index + 1 items to be enumerated, with all but the last being discarded.

EDIT: As an explanation, IEnumerable<T> is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T> must support all these cases, indexers are excluded from its definition.

How to use std::sort to sort an array in C++

sorting method without std::sort:

// sorting myArray ascending
int iTemp = 0;
for (int i = 0; i < ARRAYSIZE; i++)
{
    for (int j = i + 1; j <= ARRAYSIZE; j++)
    {
        // for descending sort change '<' with '>'
        if (myArray[j] < myArray[i])
        {
            iTemp = myArray[i];
            myArray[i] = myArray[j];
            myArray[j] = iTemp;
        }
    }
}

Run complete example:

#include <iostream> // std::cout, std::endl /* http://en.cppreference.com/w/cpp/header/iostream */
#include <cstdlib>  // srand(), rand()      /* http://en.cppreference.com/w/cpp/header/cstdlib */
#include <ctime>    // time()               /* http://en.cppreference.com/w/cpp/header/ctime */


int main()
{
    const int ARRAYSIZE = 10;
    int myArray[ARRAYSIZE];

    // populate myArray with random numbers from 1 to 1000
    srand(time(0));
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        myArray[i] = rand()% 1000 + 1;
    }

    // print unsorted myArray
    std::cout << "unsorted myArray: " << std::endl;
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
    }
    std::cout << std::endl;

    // sorting myArray ascending
    int iTemp = 0;
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        for (int j = i + 1; j <= ARRAYSIZE; j++)
        {
            // for descending sort change '<' with '>'
            if (myArray[j] < myArray[i])
            {
                iTemp = myArray[i];
                myArray[i] = myArray[j];
                myArray[j] = iTemp;
            }
        }
    }

    // print sorted myArray
    std::cout << "sorted myArray: " << std::endl;
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
    }
    std::cout << std::endl;

    return 0;
}

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

I had the same problem when trying to load Hadoop project in eclipse. I tried the solutions above, and I believe it might have worked in Eclipse Kepler... not even sure anymore (tried too many things).

With all the problems I was having, I decided to move on to Eclipse Luna, and the solutions above did not work for me.

There was another post that recommended changing the ... tag to package. I started doing that, and it would "clear" the errors... However, I start to think that the changes would bite me later - I am not an expert on Maven.

Fortunately, I found out how to remove all the errors. Go to Window->Preferences->Maven-> Error/Warnings and change "Plugin execution not covered by lifecycle..." option to "Ignore". Hope it helps.

How to set a value for a span using jQuery

You can do:

$("#submittername").text("testing");

or

$("#submittername").html("testing <b>1 2 3</b>");

How to force keyboard with numbers in mobile website in Android

inputmode according to WHATWG spec is the the default method.

For iOS devices adding pattern could also help.

For backward compatibility use type as well since Chrome use these as of version 66.

<input
  inputmode="numeric"
  pattern="[0-9]*"
  type="number"
/>

Can I open a dropdownlist using jQuery

It is not possible for javascript to "click" on an element (u can trigger the attached onclick event, but you can't literally click it)

To view all the items in the list, make the list a multiple list and increase its size, like such:

<select id="countries" multiple="multiple" size="10">
<option value="1">Country</option>
</select>

undefined reference to `WinMain@16'

Try saving your .c file before building. I believe your computer is referencing a path to a file with no information inside of it.

--Had similar issue when building C projects

How do I finish the merge after resolving my merge conflicts?

The next steps after resolving the conflicts manually are:-

  1. git add .
  2. git status (this will show you which commands are necessary to continue automatic merge procedure)
  3. [command git suggests, e.g. git merge --continue, git cherry-pick --continue, git rebase --continue]

Print a div using javascript in angularJS single page application

Two conditional functions are needed: one for Google Chrome, and a second for the remaining browsers.

$scope.printDiv = function (divName) {

    var printContents = document.getElementById(divName).innerHTML; 

    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
        var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWin.window.focus();
        popupWin.document.write('<!DOCTYPE html><html><head>' +
            '<link rel="stylesheet" type="text/css" href="style.css" />' +
            '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></body></html>');
        popupWin.onbeforeunload = function (event) {
            popupWin.close();
            return '.\n';
        };
        popupWin.onabort = function (event) {
            popupWin.document.close();
            popupWin.close();
        }
    } else {
        var popupWin = window.open('', '_blank', 'width=800,height=600');
        popupWin.document.open();
        popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
        popupWin.document.close();
    }
    popupWin.document.close();

    return true;
}

How can I get my Twitter Bootstrap buttons to right align?

The problem is that you're using the buttons as part of your lists. And because the vertical margin between list items is too low to place the buttons in between it messes the alignments up. I would place one of the buttons on top of the list and another one beneath them so that it would look like what you expect!

<ul>
<input class="btn pull-right" value="test">
<li>One</li> 
<li>Two</li>
<input class="btn pull-right" value="test2"> 
</ul>

log4j vs logback

Mature project or even project deep into development stages would probably loose more than gain from such upgrade, IMHO. Logback is certainly much more advanced in an array of points, but not to an extent for complete replacement in a working system. I would certainly consider logback for a new development, but existing log4j is good enough and mature for anything already released and met end user. This is very subjective, you should see cost yourself.

How to work on UAC when installing XAMPP

You can press OK and install xampp to C:\xampp and not into program files

Change Bootstrap input focus blue glow

For the input border before the focus. You can specify your favorite color you want to use and other css like padding etc


.input {
    padding: 6px 190px 6px 15px;
    outline: #2a65ea auto 105px ;
}

When we focus on input. You can specify your favorite color outline you wish


.input:focus{
    box-shadow: none;
    border-color: none;
    outline: lightgreen auto 5px ;
}

How to get the max of two values in MySQL?

You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).

select 
    if(
        fieldA is NULL, 
        if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
        if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
    ) as maxValue

You can change NULL to your preferred default value (if both values is NULL).

Should I use "camel case" or underscores in python?

PEP 8 advises the first form for readability. You can find it here.

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Get all photos from Instagram which have a specific hashtag with PHP

There is the instagram public API's tags section that can help you do this.

Accessing elements of Python dictionary by index

As a bonus, I'd like to offer kind of a different solution to your issue. You seem to be dealing with nested dictionaries, which is usually tedious, especially when you have to check for existence of an inner key.

There are some interesting libraries regarding this on pypi, here is a quick search for you.

In your specific case, dict_digger seems suited.

>>> import dict_digger
>>> d = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} 
}

>>> print(dict_digger.dig(d, 'Apple','American'))
16
>>> print(dict_digger.dig(d, 'Grapes','American'))
None

MD5 hashing in Android

The provided solutions for the Scala language (a little shorter):

def getMd5(content: Array[Byte]) =
    try {
        val md = MessageDigest.getInstance("MD5")
        val bytes = md.digest(content)
        bytes.map(b => Integer.toHexString((b + 0x100) % 0x100)).mkString
    } catch {
        case ex: Throwable => null
    }

Log exception with traceback

Uncaught exception messages go to STDERR, so instead of implementing your logging in Python itself you could send STDERR to a file using whatever shell you're using to run your Python script. In a Bash script, you can do this with output redirection, as described in the BASH guide.

Examples

Append errors to file, other output to the terminal:

./test.py 2>> mylog.log

Overwrite file with interleaved STDOUT and STDERR output:

./test.py &> mylog.log

Get selected value of a dropdown's item using jQuery

_x000D_
_x000D_
 function fundrp(){_x000D_
 var text_value = $("#drpboxid option:selected").text();  _x000D_
 console.log(text_value);_x000D_
 var val_text = $("#drpboxid option:selected").val();  _x000D_
 console.log(val_text);_x000D_
 var value_text = $("#drpboxid option:selected").attr("vlaue") ;_x000D_
 console.log(value_text);_x000D_
 var get_att_value = $("#drpboxid option:selected").attr("id") _x000D_
 console.log(get_att_value);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="drpboxid">_x000D_
 <option id="1_one" vlaue="one">one</option>_x000D_
 <option id="2_two" vlaue="two">two</option>_x000D_
 <option id="3_three" vlaue="three">three</option>              _x000D_
</select>_x000D_
<button id="btndrp" onclick="fundrp()">Tracking Report1234</button>
_x000D_
_x000D_
_x000D_

What is the difference between json.dump() and json.dumps() in python?

The functions with an s take string parameters. The others take file streams.

Iterate through <select> options

$("#selectId > option").each(function() {
    alert(this.text + ' ' + this.value);
});

Compiling problems: cannot find crt1.o

It seems that while you were playing with llvm/clang you(or the package manager) removed previously existing standard C library development package(eglibc on Debian) or maybe you didn't have it installed in the first place, thus you need to reinstall it, now that you reverted back to gcc.

You can do so like this on Debian:

aptitude show libc-dev

Ubuntu:

apt-get install libc-dev

On Ubuntu, if you don't have libc-dev, since I cannot find it on packages.ubuntu.com, you can try installing libc6-dev directly.

Or on Redhat like systems:

yum install glibc-devel

NB: Although you were briefly answered in the comments, here is an answer just so there is one on record in case someone encounters this one and might be looking for an answer, but not in the comments or the comment is not explicit enough for them.

"webxml attribute is required" error in Maven

The value of my webXml tag needed to look like this in order to work:

<webXml>${project.basedir}\src\main\webapp\WEB-INF\web.xml</webXml> 

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

Joining Spark dataframes on the key

From https://spark.apache.org/docs/1.5.1/api/java/org/apache/spark/sql/DataFrame.html, use join:

Inner equi-join with another DataFrame using the given column.

PersonDf.join(ProfileDf,$"personId")

OR

PersonDf.join(ProfileDf,PersonDf("personId") === ProfileDf("personId"))

Update:

You can also save the DFs as temp table using df.registerTempTable("tableName") and you can write sql queries using sqlContext.

How to sort a Collection<T>?

Assuming you have a list of object of type Person, using Lambda expression, you can sort the last names of users for instance by doing the following:

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

class Person {
        private String firstName;
        private String lastName;

        public Person(String firstName, String lastName){
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getLastName(){
            return this.lastName;
        }

        public String getFirstName(){
            return this.firstName;
        }

        @Override
        public String toString(){
            return "Person: "+ this.getFirstName() + " " + this.getLastName();
        }
    }

    class TestSort {
        public static void main(String[] args){
            List<Person> people = Arrays.asList(
                                  new Person("John", "Max"), 
                                  new Person("Coolio", "Doe"), 
                                  new Person("Judith", "Dan")
            );

            //Making use of lambda expression to sort the collection
            people.sort((p1, p2)->p1.getLastName().compareTo(p2.getLastName()));

            //Print sorted 
            printPeople(people);
        }

        public static void printPeople(List<Person> people){
            for(Person p : people){
                System.out.println(p);
            }
        }
    }

how to set the query timeout from SQL connection string

Only from code:

_x000D_
_x000D_
namespace xxx.DsXxxTableAdapters {_x000D_
    partial class ZzzTableAdapter_x000D_
    {_x000D_
        public void SetTimeout(int timeout)_x000D_
        {_x000D_
            if (this.Adapter.DeleteCommand != null) { this.Adapter.DeleteCommand.CommandTimeout = timeout; }_x000D_
            if (this.Adapter.InsertCommand != null) { this.Adapter.InsertCommand.CommandTimeout = timeout; }_x000D_
            if (this.Adapter.UpdateCommand != null) { this.Adapter.UpdateCommand.CommandTimeout = timeout; }_x000D_
            if (this._commandCollection == null) { this.InitCommandCollection(); }_x000D_
            if (this._commandCollection != null)_x000D_
            {_x000D_
                foreach (System.Data.SqlClient.SqlCommand item in this._commandCollection)_x000D_
                {_x000D_
                    if (item != null)_x000D_
                    { item.CommandTimeout = timeout; }_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
 _x000D_
    //...._x000D_
 _x000D_
 }
_x000D_
_x000D_
_x000D_

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Firefox 'Cross-Origin Request Blocked' despite headers

In my case CORS error was happening only in POST requests with file attachments other than small files.

After many wasted hours we found out request was blocked for users who were using Kaspersky Total Control.

It's possible that other antivirus or firewall software may cause similar problems. Kaspersky run some security tests for requests, but omits them for websites with SSL EV certificate, so obtaining such certificate should resolve this issue properly.

Disabling protection for your domain is a bit tricky, so here are required steps (as for December 2020): Settings -> Network Settings -> Manage exclusions -> Add -> your domain -> Save

The good thing is you can detect such blocked request. The error is empty – it doesn't have status and response. This way you can assume it was blocked by third party software and show some info.

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

await is only valid in async function

If you are writing a Chrome Extension and you get this error for your code at root, you can fix it using the following "workaround":

async function run() {
    // Your async code here
    const beers = await fetch("https://api.punkapi.com/v2/beers");
}

run();

Basically you have to wrap your async code in an async function and then call the function without awaiting it.

pip install mysql-python fails with EnvironmentError: mysql_config not found

for mariadb install libmariadbclient-dev instead of libmysqlclient-dev

sudo apt-get install libmariadbclient-dev

How to add a ScrollBar to a Stackpanel

For horizontally oriented StackPanel, explicitly putting both the scrollbar visibilities worked for me to get the horizontal scrollbar.

    <ScrollViewer VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Auto" >
        <StackPanel Orientation="Horizontal" />
    </ScrollViewer>

Laravel: Get base url

I found an other way to just get the base url to to display the value of environment variable APP_URL

env('APP_URL')

which will display the base url like http://domains_your//yours_website. beware it assumes that you had set the environment variable in .env file (that is present in the root folder).

HttpServletRequest to complete URL

I use this method:

public static String getURL(HttpServletRequest req) {

    String scheme = req.getScheme();             // http
    String serverName = req.getServerName();     // hostname.com
    int serverPort = req.getServerPort();        // 80
    String contextPath = req.getContextPath();   // /mywebapp
    String servletPath = req.getServletPath();   // /servlet/MyServlet
    String pathInfo = req.getPathInfo();         // /a/b;c=123
    String queryString = req.getQueryString();          // d=789

    // Reconstruct original requesting URL
    StringBuilder url = new StringBuilder();
    url.append(scheme).append("://").append(serverName);

    if (serverPort != 80 && serverPort != 443) {
        url.append(":").append(serverPort);
    }

    url.append(contextPath).append(servletPath);

    if (pathInfo != null) {
        url.append(pathInfo);
    }
    if (queryString != null) {
        url.append("?").append(queryString);
    }
    return url.toString();
}

How to convert string to string[]?

To convert a string with comma separated values to a string array use Split:

string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');

Result will be a string array with four strings:

{"One","Two","Three","Four"}

Difference between filter and filter_by in SQLAlchemy

We actually had these merged together originally, i.e. there was a "filter"-like method that accepted *args and **kwargs, where you could pass a SQL expression or keyword arguments (or both). I actually find that a lot more convenient, but people were always confused by it, since they're usually still getting over the difference between column == expression and keyword = expression. So we split them up.

Best practices to test protected methods with PHPUnit

You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:

class Foo {
  protected function stuff() {
    // secret stuff, you want to test
  }
}

class SubFoo extends Foo {
  public function exposedStuff() {
    return $this->stuff();
  }
}

Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.

Send text to specific contact programmatically (whatsapp)

I've found the right way to do this:

Source code: phone and message are both String.

    PackageManager packageManager = context.getPackageManager();
    Intent i = new Intent(Intent.ACTION_VIEW);

    try {
        String url = "https://api.whatsapp.com/send?phone="+ phone +"&text=" + URLEncoder.encode(message, "UTF-8");
        i.setPackage("com.whatsapp");
        i.setData(Uri.parse(url));
        if (i.resolveActivity(packageManager) != null) {
            context.startActivity(i);
        }
    } catch (Exception e){
        e.printStackTrace();
    }

Enjoy yourself!

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I got this problem today while installing SugarCRM (a free CRM).

The system was not able to connect to the database using the root user. I could definitively log in as root from the console... so what was the problem?

I found out that in my situation, I was getting exactly the same error, but that was because the password was sent to mysql directly from the $_POST data, in other words, the < character from my password was sent to mysql as &lt; which means the password was wrong.

Everything else did not help a bit. The list of users in mysql were correct, including the anonymous user (which appears after the root entries.)

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

I took Earmon Nerbonne's answer and edited it to work with tables that fill the whole width.

http://jsfiddle.net/DYgD6/6/

<!DOCTYPE html>
<html><head><title>testdoc</title>
<style type="text/css">
            body {
        font:16px Calibri;
    }
    table {
        border-collapse:separate;
        border-top: 3px solid grey;
    }
    td {
        margin:0;
        border:3px solid grey;
        border-top-width:0px;
        white-space:nowrap;
    }
    #outerdiv {
        position: absolute;
        top: 0;
        left: 0;
        right: 5em;
    }
    #innerdiv {
        width: 100%;
        overflow-x:scroll;
        margin-left: 5em;
        overflow-y:visible;
        padding-bottom:1px;
    }
    .headcol {
        position:absolute;
        width:5em;
        left:0;
        top:auto;
        border-right: 0px none black;
        border-top-width:3px;
        /*only relevant for first row*/
        margin-top:-3px;
        /*compensate for top border*/
    }
    .headcol:before {
        content:'Row ';
    }
    .long {
        background:yellow;
        letter-spacing:1em;
    }
</style></head><body>
  <div id="outerdiv">
   <div id="innerdiv">
    <table>
        <tr>
            <td class="headcol">1</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">2</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">3</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">4</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">5</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">6</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">7</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">8</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">9</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
    </table>
</div></div>
</body></html>

The width of the fixed column still needs to be a set value though.

How to downgrade php from 5.5 to 5.3

Long answer: it is possible!

  1. Temporarily rename existing xampp folder
  2. Install xampp 1.7.7 into xampp folder name
  3. Folder containing just installed 1.7.7 distribution rename to different name and previously existing xampp folder rename back just to xampp.
  4. In xampp folder rename php and apache folders to different names (I propose php_prev and apache_prev) so you can after switch back to them by renaming them back.
  5. Copy apache and php folders from folder with xampp 1.7.7 into xampp directory
  6. In xampp directory comment line apache/conf/httpd.conf:458

    #Include "conf/extra/httpd-perl.conf"

  7. In xampp directory do next replaces in files:

php/pci.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pci" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\php.exe" -f "%XAMPPPHPDIR%\pci" -- %*

php/pciconf.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pciconf" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\.\php.exe" -f "%XAMPPPHPDIR%\pciconf" -- %*

php/pear.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/peardev.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/pecl.bat:32

from

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php\" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/phar.phar.bat:1

from

%~dp0php.exe %~dp0pharcommand.phar %*

to

"%~dp0php.exe" "%~dp0pharcommand.phar" %*

Enjoy new XAMPP with PHP 5.3

Checked by myself in XAMPP 5.6.31, 7.0.15 & 7.1.1 with XAMPP Control Panel v3.2.2

Extension gd is missing from your system - laravel composer Update

On CentOS 7, try running following command:

sudo yum install php72u-gd.x86_64

gridview data export to excel in asp.net

The Best way is to use closedxml. Below is the link for reference

https://closedxml.codeplex.com/wikipage?title=Adding%20DataTable%20as%20Worksheet&referringTitle=Documentation

and you can simple use

    var wb = new ClosedXML.Excel.XLWorkbook();
DataTable dt = GeDataTable();//refer documentaion

wb.Worksheets.Add(dt);

Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\"");

using (var ms = new System.IO.MemoryStream()) {
    wb.SaveAs(ms);
    ms.WriteTo(Response.OutputStream);
    ms.Close();
}

Response.End();

Getting hold of the outer class object from the inner class object

if you don't have control to modify the inner class, the refection may help you (but not recommend). this$0 is reference in Inner class which tells which instance of Outer class was used to create current instance of Inner class.

403 Forbidden You don't have permission to access /folder-name/ on this server

if permission issue and you have ssh access in root folder

find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;

will resolve your error

CSS z-index not working (position absolute)

JSFiddle

You have to put the second div on top of the first one because the both have an z-index of zero so that the order in the dom will decide which is on top. This also affects the relative positioned div because its z-index relates to elements inside the parent div.

<div class="absolute" style="top: 54px"></div>
<div class="absolute">
    <div id="relative"></div>
</div>

Css stays the same.

Trying to SSH into an Amazon Ec2 instance - permission error

I know this question has been answered already but for those that have tried them all and you are still getting the annoying "Permission denied (publickey)". Try running your command with SUDO. Of course this is a temporary solution and you should set permissions correctly but at least that will let you identify that your current user is not running with the privileges you need (as you assumed)

sudo ssh -i amazonec2.pem ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com

Once you do this you'll get a message like this:

Please login as the user "ec2-user" rather than the user "root"

Which is also sparsely documented. In that case just do this:

sudo ssh -i amazonec2.pem ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com -l ec2-user

And you'll get the glorious:

   __|  __|_  )
   _|  (     /   Amazon Linux AMI
  ___|\___|___|

dictionary update sequence element #0 has length 3; 2 is required

Not really an answer to the specific question, but if there are others, like me, who are getting this error in fastAPI and end up here:

It is probably because your route response has a value that can't be JSON serialised by jsonable_encoder. For me it was WKBElement: https://github.com/tiangolo/fastapi/issues/2366

Like in the issue, I ended up just removing the value from the output.

In PANDAS, how to get the index of a known value?

To get the index by value, simply add .index[0] to the end of a query. This will return the index of the first row of the result...

So, applied to your dataframe:

In [1]: a[a['c2'] == 1].index[0]     In [2]: a[a['c1'] > 7].index[0]   
Out[1]: 0                            Out[2]: 4                         

Where the query returns more than one row, the additional index results can be accessed by specifying the desired index, e.g. .index[n]

In [3]: a[a['c2'] >= 7].index[1]     In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]  
Out[3]: 4                            Out[4]: 3 

How to make Python script run as service?

I use this code to daemonize my applications. It allows you start/stop/restart the script using the following commands.

python myscript.py start
python myscript.py stop
python myscript.py restart

In addition to this I also have an init.d script for controlling my service. This allows you to automatically start the service when your operating system boots-up.

Here is a simple example to get your going. Simply move your code inside a class, and call it from the run function inside MyDeamon.

import sys
import time

from daemon import Daemon


class YourCode(object):
    def run(self):
        while True:
            time.sleep(1)


class MyDaemon(Daemon):
    def run(self):
        # Or simply merge your code with MyDaemon.
        your_code = YourCode()
        your_code.run()


if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)

Upstart

If you are running an operating system that is using Upstart (e.g. CentOS 6) - you can also use Upstart to manage the service. If you use Upstart you can keep your script as is, and simply add something like this under /etc/init/my-service.conf

start on started sshd
stop on runlevel [!2345]

exec /usr/bin/python /opt/my_service.py
respawn

You can then use start/stop/restart to manage your service.

e.g.

start my-service
stop my-service
restart my-service

A more detailed example of working with upstart is available here.

Systemd

If you are running an operating system that uses Systemd (e.g. CentOS 7) you can take a look at the following Stackoverflow answer.

Formatting a field using ToText in a Crystal Reports formula field

I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))

You can use CCur to convert numbers or string to Curency formats. CCur(number) or CCur(string)


I think this may be what you are looking for,

Replace (ToText(CCur({field})),"$" , "") that will give the parentheses for negative numbers

It is a little hacky, but I'm not sure CR is very kind in the ways of formatting

Get changes from master into branch in Git

First check out to master:

git checkout master

Do all changes, hotfix and commits and push your master.

Go back to your branch, 'aq', and merge master in it:

git checkout aq
git merge master

Your branch will be up-to-date with master. A good and basic example of merge is 3.2 Git Branching - Basic Branching and Merging.

Select distinct rows from datatable in Linq

We can get the distinct similar to the example shown below

 //example
           var  distinctValues =  DetailedBreakDown_Table.AsEnumerable().Select(r => new
            {
                InvestmentVehicleID = r.Field<string>("InvestmentVehicleID"),
                Universe = r.Field<string>("Universe"),
                AsOfDate = _imqDate,
                Ticker = "",
                Cusip = "",
                PortfolioDate = r.Field<DateTime>("PortfolioDate")

            } ).Distinct();

How can I parse a YAML file from a Linux shell script?

perl -ne 'chomp; printf qq/%s="%s"\n/, split(/\s*:\s*/,$_,2)' file.yml > file.sh

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

Can we pass an array as parameter in any function in PHP?

function sendemail(Array $id,$userid){  // forces $id must be an array
Some Process....
}


$ids  = array(121,122,123);
sendmail($ids, $userId);

How to Set Variables in a Laravel Blade Template

Hacking comments is not a very readable way to do it. Also editors will color it as a comment and someone may miss it when looking through the code.

Try something like this:

{{ ''; $hello = 'world' }}

It will compile into:

<?php echo ''; $hello = 'world'; ?>

...and do the assignment and not echo anything.

Java: print contents of text file to screen

Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text

Príliš žlutoucký kun
úpel dábelské ódy

and the file uses windows-1250 format. If you use FileReader you will get this result:

P??li? ?lu?ou?k? k??
?p?l ??belsk? ?dy

So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.

Example:

String encoding = "Cp1250";
File file = new File("foo.txt");

if (file.exists()) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
else {
    System.out.println("file doesn't exist");
}

In case you want to read the file character after character do not use BufferedReader.

try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
    int data = isr.read();
    while (data != -1) {
        System.out.print((char) data);
        data = isr.read();
    }
} catch (IOException e) {
    e.printStackTrace();
}

Command to collapse all sections of code?

In Visual Studio 2013:

CTL + M + A collapses all

CTL + M + L expands all

Submit a form in a popup, and then close the popup

Try like this as well

covertPostSub("/xyz/test.jsp","?param1=param1&param2=param2","_self","true");
covertPostSub("/xyz/test.jsp","?param1=param1&param2=param2","_blank","true");

var convPop = null;
function covertPostSub(action,paramsTosend,targetIframe,isWindow){
    var Popup = null;
    var form = document.createElement("form");
    form.setAttribute("method", "POST");
    form.setAttribute("id","TheForm");
    form.setAttribute("action", action);
    form.setAttribute("target", targetIframe);
    var params = paramsTosend;
    params = params.substring(1, params.length);
    params = params.split("&");
    for(var key=0; key<params.length; key++) {
        var sa = params[key];
        sa = sa.split("=");
        var xs = (sa[1]);

        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", sa[0]);
            hiddenField.setAttribute("value",xs);

            form.appendChild(hiddenField);
         }
    }
    document.body.appendChild(form);
    form.style.display = "none";
    if(isWindow){
        window.open('', "formpopup","width=900,height=590,toolbar=no,scrollbars=yes,resizable=no,location=0,directories=0,status=1,menubar=0,left=60,top=60");
        form.target = 'formpopup';
        form.submit();
    }else{
        form.submit();
    }

}

How do you use window.postMessage across domains?

Probably you try to send your data from mydomain.com to www.mydomain.com or reverse, NOTE you missed "www". http://mydomain.com and http://www.mydomain.com are different domains to javascript.

Show spinner GIF during an $http request in AngularJS?

If you're wrapping your api calls within a service/factory, then you can track the loading counter there (per answer and excellent simultaneous suggestion by @JMaylin), and reference the loading counter via a directive. Or any combination thereof.

API WRAPPER

yourModule
    .factory('yourApi', ['$http', function ($http) {
        var api = {}

        //#region ------------ spinner -------------

        // ajax loading counter
        api._loading = 0;

        /**
         * Toggle check
         */
        api.isOn = function () { return api._loading > 0; }

        /**
         * Based on a configuration setting to ignore the loading spinner, update the loading counter
         * (for multiple ajax calls at one time)
         */
        api.spinner = function(delta, config) {
            // if we haven't been told to ignore the spinner, change the loading counter
            // so we can show/hide the spinner

            if (NG.isUndefined(config.spin) || config.spin) api._loading += delta;

            // don't let runaway triggers break stuff...
            if (api._loading < 0) api._loading = 0;

            console.log('spinner:', api._loading, delta);
        }
        /**
         * Track an ajax load begin, if not specifically disallowed by request configuration
         */
        api.loadBegin = function(config) {
            api.spinner(1, config);
        }
        /**
         * Track an ajax load end, if not specifically disallowed by request configuration
         */
        api.loadEnd = function (config) {
            api.spinner(-1, config);
        }

        //#endregion ------------ spinner -------------

        var baseConfig = {
            method: 'post'
            // don't need to declare `spin` here
        }

        /**
         * $http wrapper to standardize all api calls
         * @param args stuff sent to request
         * @param config $http configuration, such as url, methods, etc
         */
        var callWrapper = function(args, config) {
            var p = angular.extend(baseConfig, config); // override defaults

            // fix for 'get' vs 'post' param attachment
            if (!angular.isUndefined(args)) p[p.method == 'get' ? 'params' : 'data'] = args;

            // trigger the spinner
            api.loadBegin(p);

            // make the call, and turn of the spinner on completion
            // note: may want to use `then`/`catch` instead since `finally` has delayed completion if down-chain returns more promises
            return $http(p)['finally'](function(response) {
                api.loadEnd(response.config);
                return response;
            });
        }

        api.DoSomething = function(args) {
            // yes spinner
            return callWrapper(args, { cache: true });
        }
        api.DoSomethingInBackground = function(args) {
            // no spinner
            return callWrapper(args, { cache: true, spin: false });
        }

        // expose
        return api;
    });

SPINNER DIRECTIVE

(function (NG) {
    var loaderTemplate = '<div class="ui active dimmer" data-ng-show="hasSpinner()"><div class="ui large loader"></div></div>';

    /**
     * Show/Hide spinner with ajax
     */
    function spinnerDirective($compile, api) {
        return {
            restrict: 'EA',
            link: function (scope, element) {
                // listen for api trigger
                scope.hasSpinner = api.isOn;

                // attach spinner html
                var spin = NG.element(loaderTemplate);
                $compile(spin)(scope); // bind+parse
                element.append(spin);
            }
        }
    }

    NG.module('yourModule')
        .directive('yourApiSpinner', ['$compile', 'yourApi', spinnerDirective]);
})(angular);

USAGE

<div ng-controller="myCtrl" your-api-spinner> ... </div>

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

How to calculate age (in years) based on Date of Birth and getDate()

you should count years by following way :-

select cast(datediff(DAY, '2000-03-01 10:00:01', '2013-03-01 10:00:00') / (365.23076923074) as int) as 'Age'

it's very easy...

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Check The data you are writing to Server. May be data has delimiter which is not used.

like

045|2272575|0.000|0.000|2013-10-07
045|2272585|0.000|0.000;2013-10-07

your delimiter is '|' but data has a delimiter ';'. So for this you are getting the error.

What is the purpose of "pip install --user ..."?

--user installs in site.USER_SITE.

For my case, it was /Users/.../Library/Python/2.7/bin. So I have added that to my PATH (in ~/.bash_profile file):

export PATH=$PATH:/Users/.../Library/Python/2.7/bin

Accessing the index in 'for' loops?

In your question, you write "how do I access the loop index, from 1 to 5 in this case?"

However, the index for a list runs from zero. So, then we need to know if what you actually want is the index and item for each item in a list, or whether you really want numbers starting from 1. Fortunately, in Python, it is easy to do either or both.

First, to clarify, the enumerate function iteratively returns the index and corresponding item for each item in a list.

alist = [1, 2, 3, 4, 5]

for n, a in enumerate(alist):
    print("%d %d" % (n, a))

The output for the above is then,

0 1
1 2
2 3
3 4
4 5

Notice that the index runs from 0. This kind of indexing is common among modern programming languages including Python and C.

If you want your loop to span a part of the list, you can use the standard Python syntax for a part of the list. For example, to loop from the second item in a list up to but not including the last item, you could use

for n, a in enumerate(alist[1:-1]):
    print("%d %d" % (n, a))

Note that once again, the output index runs from 0,

0 2
1 3
2 4

That brings us to the start=n switch for enumerate(). This simply offsets the index, you can equivalently simply add a number to the index inside the loop.

for n, a in enumerate(alist, start=1):
    print("%d %d" % (n, a))

for which the output is

1 1
2 2
3 3
4 4
5 5

Example of SOAP request authenticated with WS-UsernameToken

The core thing is to define prefixes for namespaces and use them to fortify each and every tag - you are mixing 3 namespaces and that just doesn't fly by trying to hack defaults. It's also good to use exactly the prefixes used in the standard doc - just in case that the other side get a little sloppy.

Last but not least, it's much better to use default types for fields whenever you can - so for password you have to list the type, for the Nonce it's already Base64.

Make sure that you check that the generated token is correct before you send it via XML and don't forget that the content of wsse:Password is Base64( SHA-1 (nonce + created + password) ) and date-time in wsu:Created can easily mess you up. So once you fix prefixes and namespaces and verify that yout SHA-1 work fine without XML (just imagine you are validating the request and do the server side of SHA-1 calculation) you can also do a truial wihtout Created and even without Nonce. Oh and Nonce can have different encodings so if you really want to force another encoding you'll have to look further into wsu namespace.

<S11:Envelope xmlns:S11="..." xmlns:wsse="..." xmlns:wsu= "...">
  <S11:Header>
  ...
    <wsse:Security>
      <wsse:UsernameToken>
        <wsse:Username>NNK</wsse:Username>
        <wsse:Password Type="...#PasswordDigest">weYI3nXd8LjMNVksCKFV8t3rgHh3Rw==</wsse:Password>
        <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce>
        <wsu:Created>2003-07-16T01:24:32</wsu:Created>
      </wsse:UsernameToken>
    </wsse:Security>
  ...
  </S11:Header>
...
</S11:Envelope>

Make a dictionary with duplicate keys in Python

If you want to have lists only when they are necessary, and values in any other cases, then you can do this:

class DictList(dict):
    def __setitem__(self, key, value):
        try:
            # Assumes there is a list on the key
            self[key].append(value)
        except KeyError: # If it fails, because there is no key
            super(DictList, self).__setitem__(key, value)
        except AttributeError: # If it fails because it is not a list
            super(DictList, self).__setitem__(key, [self[key], value])

You can then do the following:

dl = DictList()
dl['a']  = 1
dl['b']  = 2
dl['b'] = 3

Which will store the following {'a': 1, 'b': [2, 3]}.


I tend to use this implementation when I want to have reverse/inverse dictionaries, in which case I simply do:

my_dict = {1: 'a', 2: 'b', 3: 'b'}
rev = DictList()
for k, v in my_dict.items():
    rev_med[v] = k

Which will generate the same output as above: {'a': 1, 'b': [2, 3]}.


CAVEAT: This implementation relies on the non-existence of the append method (in the values you are storing). This might produce unexpected results if the values you are storing are lists. For example,

dl = DictList()
dl['a']  = 1
dl['b']  = [2]
dl['b'] = 3

would produce the same result as before {'a': 1, 'b': [2, 3]}, but one might expected the following: {'a': 1, 'b': [[2], 3]}.

Printing to the console in Google Apps Script?

Just to build on vinnief's hacky solution above, I use MsgBox like this:

Browser.msgBox('BorderoToMatriz', Browser.Buttons.OK_CANCEL);

and it acts kinda like a break point, stops the script and outputs whatever string you need to a pop-up box. I find especially in Sheets, where I have trouble with Logger.log, this provides an adequate workaround most times.

How to read a specific line using the specific line number from a file in Java?

Not that I know of, but what you could do is loop through the first 31 lines doing nothing using the readline() function of BufferedReader

FileInputStream fs= new FileInputStream("someFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
for(int i = 0; i < 31; ++i)
  br.readLine();
String lineIWant = br.readLine();

How Big can a Python List Get?

As the Python documentation says:

sys.maxsize

The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.

In my computer (Linux x86_64):

>>> import sys
>>> print sys.maxsize
9223372036854775807

How to convert / cast long to String?

very simple, just concatenate the long to a string.

long date = curDateFld.getDate(); 
String str = ""+date;

How to access SOAP services from iPhone

My solution was to have a proxy server accept REST, issue the SOAP request, and return result, using PHP.

Time to implement: 15-30 minutes.

Not most elegant, but solid.

Twitter Bootstrap date picker

Create a custom theme with themeroller, then on the download page, choose 'Advanced Theme Settings'. Set the CSS scope to 'body'. Since the CSS rules you download will be prefixed with the body tag selector, they'll have higher specificity and will override bootstrap rules.

Convert hex string (char []) to int?

Have you tried strtol()?

strtol - convert string to a long integer

Example:

const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);

In case the string representation of the number begins with a 0x prefix, one must should use 0 as base:

const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);

(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)

Java: Clear the console

You need to use control characters as backslash (\b) and carriage return (\r). It come disabled by default, but the Console view can interpret these controls.

Windows>Preferences and Run/Debug > Console and select Interpret ASCII control characteres to enabled it

Console preferences in Eclipse

After these configurations, you can manage your console with control characters like:

\t - tab.

\b - backspace (a step backward in the text or deletion of a single character).

\n - new line.

\r - carriage return. ()

\f - form feed.

eclipse console clear animation

More information at: https://www.eclipse.org/eclipse/news/4.14/platform.php

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

Bash mkdir and subfolders

To create multiple sub-folders

mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}

How to set text size in a button in html

Try this, its working in FF

body,
input,
select,
button {
 font-family: Arial,Helvetica,sans-serif;
 font-size: 14px;
}

How to get client IP address using jQuery

A simple AJAX call to your server, and then the serverside logic to get the ip address should do the trick.

$.getJSON('getip.php', function(data){
  alert('Your ip is: ' +  data.ip);
});

Then in php you might do:

<?php
/* getip.php */
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
  $ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
  $ip=$_SERVER['REMOTE_ADDR'];
}
print json_encode(array('ip' => $ip));

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

You need to specify the branch. By default it listens to anything. See the blog post Hudson: Git and Maven plugins.

Git Stash vs Shelve in IntelliJ IDEA

git shelve doesn't exist in Git.

Only git stash:

  • when you want to record the current state of the working directory and the index, but want to go back to a clean working directory.
  • which saves your local modifications away and reverts the working directory to match the HEAD commit.

You had a 2008 old project git shelve to isolate modifications in a branch, but that wouldn't be very useful nowadays.

As documented in Intellij IDEA shelve dialog, the feature "shelving and unshelving" is not linked to a VCS (Version Control System tool) but to the IDE itself, to temporarily storing pending changes you have not committed yet in changelist.

Note that since Git 2.13 (Q2 2017), you now can stash individual files too.

Change the column label? e.g.: change column "A" to column "Name"

If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok

How can I count the number of elements of a given value in a matrix?

One way you can perform this operation for all the values 1 through 7 at once is to use the function ACCUMARRAY:

>> M = randi(7,1500,1);  %# Some random sample data with the values 1 through 7
>> dayCounts = accumarray(M,1)  %# Will return a 7-by-1 vector

dayCounts =

   218       %# Number of Sundays
   200       %# Number of Mondays
   213       %# Number of Tuesdays
   220       %# Number of Wednesdays
   234       %# Number of Thursdays
   219       %# Number of Fridays
   196       %# Number of Saturdays

How to update values using pymongo?

With my pymongo version: 3.2.2 I had do the following

from bson.objectid import ObjectId
import pymongo

client = pymongo.MongoClient("localhost", 27017)
db = client.mydbname

db.ProductData.update_one({
  '_id': ObjectId(p['_id']['$oid'])
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False)

jQuery UI dialog positioning

You ca set top position in style for display on center, saw that the code:

.ui-dialog{top: 100px !important;}

This style should show dialog box 100px bellow from top.

MVC 4 Edit modal form using Bootstrap

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

How to check if all inputs are not empty with jQuery

You can achive this with Regex and Replace or with just trimming.

Regex example:

if ($('input').val().replace(/[\s]/, '') == '') {
    alert('Input is not filled!');
}

With this replace() function you replace white spaces with nothing (removing white spaces).

Trimming Example:

if ($('input').val().trim() == '') {
    alert('Input is not filled!');
}

trim() function removes the leading and trailing white space and line terminator characters from a string.

No more data to read from socket error

We were facing same problem, we resolved it by increasing initialSize and maxActive size of connection pool.

You can check this link

Maybe this helps someone.

Reload chart data via JSON with Highcharts

Actually maybe you should choose the function update is better.
Here's the document of function update http://api.highcharts.com/highcharts#Series.update

You can just type code like below:

chart.series[0].update({data: [1,2,3,4,5]})

These code will merge the origin option, and update the changed data.

How to measure elapsed time in Python?

Here's another context manager for timing code -

Usage:

from benchmark import benchmark

with benchmark("Test 1+1"):
    1+1
=>
Test 1+1 : 1.41e-06 seconds

or, if you need the time value

with benchmark("Test 1+1") as b:
    1+1
print(b.time)
=>
Test 1+1 : 7.05e-07 seconds
7.05233786763e-07

benchmark.py:

from timeit import default_timer as timer

class benchmark(object):

    def __init__(self, msg, fmt="%0.3g"):
        self.msg = msg
        self.fmt = fmt

    def __enter__(self):
        self.start = timer()
        return self

    def __exit__(self, *args):
        t = timer() - self.start
        print(("%s : " + self.fmt + " seconds") % (self.msg, t))
        self.time = t

Adapted from http://dabeaz.blogspot.fr/2010/02/context-manager-for-timing-benchmarks.html

git stash changes apply to new branch?

If you have some changes on your workspace and you want to stash them into a new branch use this command:

git stash branch branchName

It will make:

  1. a new branch
  2. move changes to this branch
  3. and remove latest stash (Like: git stash pop)

How do I iterate over a JSON structure?

Another solution to navigate through JSON documents is JSONiq (implemented in the Zorba engine), where you can write something like:

jsoniq version "1.0";

let $doc := [
  {"id":"10", "class": "child-of-9"},
  {"id":"11", "class": "child-of-10"}
]
for $entry in members($doc)             (: binds $entry to each object in turn :)
return $entry.class                     (: gets the value associated with "class" :)

You can run it on http://try.zorba.io/

Changing image size in Markdown

For IntelliJ IDEA users, please refer to Markdown Navigator plugin.

Preview renders images, badges, HTML, etc.

Android Studio Markdown Preview