Programs & Examples On #Flajaxian

Is there any way to delete local commits in Mercurial?

In addition to Samaursa's excelent answer, you can use the evolve extension's prune as a safe and recoverable version of strip that will allow you to go back in case you do anything wrong.

I have these alias on my .hgrc:

 # Prunes all draft changesets on the current repository
 reset-tree = prune -r "outgoing() and not obsolete()"
 # *STRIPS* all draft changesets on current repository. This deletes history.
 force-reset-tree = strip 'roots(outgoing())'

Note that prune also has --keep, just like strip, to keep the working directory intact allowing you to recommit the files.

Difference between setUp() and setUpBeforeClass()

setUpBeforeClass is run before any method execution right after the constructor (run only once)

setUp is run before each method execution

tearDown is run after each method execution

tearDownAfterClass is run after all other method executions, is the last method to be executed. (run only once deconstructor)

Which characters need to be escaped in HTML?

If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand & and the element delimiter less-than and greater-than signs < >:

& becomes &amp;
< becomes &lt;
> becomes &gt;

Inside of attribute values you must also escape the quote character you're using:

" becomes &quot;
' becomes &#39;

In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.

If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.

In general, you should not escape spaces as &nbsp;. &nbsp; is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert          extra        space       without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.


1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p> or <p title="HERE">...</p>. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>, <script>NOT-HERE</script>, <style>NOT-HERE</style>, or <p NOT-HERE="...">...</p>.

In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.

If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.

A good Sorted List for Java

SortedList decorator from Java Happy Libraries can be used to decorate TreeList from Apache Collections. That would produce a new list which performance is compareable to TreeSet. https://sourceforge.net/p/happy-guys/wiki/Sorted%20List/

Intellij idea cannot resolve anything in maven

It seems to me that solutions to this problem is plenty and all look a bit like magic. For me, invalidation of caches, re-importing or anything else already mentioned was not working. The only thing that helped was (without re-import) go to Maven settings, uncheck automatic importing and re-check it back.

enter image description here

Laravel 5 PDOException Could Not Find Driver

You should install PDO on your server. Edit your php.ini (look at your phpinfo(), "Loaded Configuration File" line, to find the php.ini file path). Find and uncomment the following line (remove the ; character):

;extension=pdo_mysql.so

Then, restart your Apache server. For more information, please read the documentation.

Replacing NULL and empty string within Select statement

For an example data in your table such as combinations of

'', null and as well as actual value than if you want to only actual value and replace to '' and null value by # symbol than execute this query

SELECT Column_Name = (CASE WHEN (Column_Name IS NULL OR Column_Name = '') THEN '#' ELSE Column_Name END) FROM Table_Name

and another way you can use it but this is little bit lengthy and instead of this you can also use IsNull function but here only i am mentioning IIF function

SELECT IIF(Column_Name IS NULL, '#', Column_Name) FROM Table_Name  
SELECT IIF(Column_Name  = '', '#', Column_Name) FROM Table_Name  
-- and syntax of this query
SELECT IIF(Column_Name IS NULL, 'True Value', 'False Value') FROM Table_Name

Up, Down, Left and Right arrow keys do not trigger KeyDown event

In order to capture keystrokes in a Forms control, you must derive a new class that is based on the class of the control that you want, and you override the ProcessCmdKey().

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //handle your keys here
}

Example :

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //capture up arrow key
    if (keyData == Keys.Up )
    {
        MessageBox.Show("You pressed Up arrow key");
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Full source...Arrow keys in C#

Vayne

Is it safe to clean docker/overlay2/

Everything in /var/lib/docker are filesystems of containers. If you stop all your containers and prune them, you should end up with the folder being empty. You probably don't really want that, so don't go randomly deleting stuff in there. Do not delete things in /var/lib/docker directly. You may get away with it sometimes, but it's inadvisable for so many reasons.

Do this instead:

sudo bash
cd /var/lib/docker
find . -type f | xargs du -b  | sort -n

What you will see is the largest files shown at the bottom. If you want, figure out what containers those files are in, enter those containers with docker exec -ti containername -- /bin/sh and delete some files.

You can also put docker system prune -a -f on a daily/weekly cron job as long as you aren't leaving stopped containers and volumes around that you care about. It's better to figure out the reasons why it's growing, and correct them at the container level.

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

Load a Bootstrap popover content with AJAX. Is this possible?

For me works change data-content befora load popover:

$('.popup-ajax').data('content', function () {
    var element = this;
    $.ajax({
        url: url,
        success: function (data) {

            $(element).attr('data-content', data)

            $(element).popover({
                html: true,
                trigger: 'manual',
                placement: 'left'
            });
            $(element).popover('show')
        }})
})

SQL datetime format to date only

if you are using SQL Server use convert

e.g. select convert(varchar(10), DeliveryDate, 103) as ShortDate

more information here: http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx

Make HTML5 video poster be same size as video itself

You can use poster to show image instead of video on mobile device(or devices which doesn't support the video autoplay functionality). Because mobile devices not support video autoplay functionality.

<div id="wrap_video">
<video preload="preload" id="Video" autoplay="autoplay" loop="loop" poster="default.jpg">
<source src="Videos.mp4" type="video/mp4">
Your browser does not support the <code>video</code> tag.
</video>
</div>

Now you can just style the poster attribute which is inside the video tag for mobile device via media-query.

#wrap_video
{
width:480px;
height:360px;
position: relative;
} 
@media (min-width:360px) and (max-width:780px)
{
video[poster]
{
top:0 !important;
left:0 !important;
width:480px !important;
height:360px !important;
position: absolute !important;
}
}

hide/show a image in jquery

What image do you want to hide? Assuming all images, the following should work:

$("img").hide();

Otherwise, using selectors, you could find all images that are child elements of the containing div, and hide those.

However, i strongly recommend you read the Jquery docs, you could have figured it out yourself: http://docs.jquery.com/Main_Page

How to know which is running in Jupyter notebook?

Creating a virtual environment for Jupyter Notebooks

A minimal Python install is

sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip

Then you can create and use the environment

/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate

You can make a kernel for Jupyter with

ipython3 kernel install --user --name=test

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

This is not how SQL works:

INSERT INTO employee(hans,germany) values(?,?)

The values (hans,germany) should use column names (emp_name, emp_address). The values are provided by your program by using the Statement.setString(pos,value) methods. It is complaining because you said there were two parameters (the question marks) but didn't provide values.

You should be creating a PreparedStatement and then setting parameter values as in:

String insert= "INSERT INTO employee(emp_name,emp_address) values(?,?)";
PreparedStatement stmt = con.prepareStatement(insert);
stmt.setString(1,"hans");
stmt.setString(2,"germany");
stmt.execute();

If Browser is Internet Explorer: run an alternative script instead

var browserName=navigator.appName; if (browserName=="Microsoft Internet Explorer") { document.write("Your html for IE") }

How to use both onclick and target="_blank"

Instead use window.open():

The syntax is:

window.open(strUrl, strWindowName[, strWindowFeatures]);

Your code should have:

window.open('Prosjektplan.pdf');

Your code should be:

<p class="downloadBoks"
   onclick="window.open('Prosjektplan.pdf')">Prosjektbeskrivelse</p>

Java: set timeout on a certain block of code?

Instead of having the task in the new thread and the timer in the main thread, have the timer in the new thread and the task in the main thread:

public static class TimeOut implements Runnable{
    public void run() {
        Thread.sleep(10000);
        if(taskComplete ==false) {
            System.out.println("Timed Out");
            return;
        }
        else {
            return;
        }
    }
}
public static boolean taskComplete = false;
public static void main(String[] args) {
    TimeOut timeOut = new TimeOut();
    Thread timeOutThread = new Thread(timeOut);
    timeOutThread.start();
    //task starts here
    //task completed
    taskComplete =true;
    while(true) {//do all other stuff }
}

How to make Bootstrap 4 cards the same height in card-columns?

this may help you

just follow this code

<div class="row">
   <div class="col-md-4 h-100">contents....</div>
   <div class="col-md-4 h-100">contents....</div>
   <div class="col-md-4 h-100">contents....</div>
</div>

use bootstrap class "h-100"

Uninstall all installed gems, in OSX?

If you like doing it using ruby:

ruby -e "`gem list`.split(/$/).each { |line| puts `gem uninstall -Iax #{line.split(' ')[0]}` unless line.strip.empty? }"

Cheers

Convert array to JSON string in swift

Hint: To convert an NSArray containing JSON compatible objects to an NSData object containing a JSON document, use the appropriate method of NSJSONSerialization. JSONObjectWithData is not it.

Hint 2: You rarely want that data as a string; only for debugging purposes.

Node.js Web Application examples/tutorials

DailyJS has a good tutorial (long series of 24 posts) that walks you through all the aspects of building a notepad app (including all the possible extras).

Heres an overview of the tutorial: http://dailyjs.com/2010/11/01/node-tutorial/

And heres a link to all the posts: http://dailyjs.com/tags.html#nodepad

req.body empty on posts

I discovered, that it works when sending with content type

"application/json"

in combination with server-side

app.use(bodyParser.json());

Now I can send via

var data = {name:"John"}
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", theUrl, false); // false for synchronous request
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(data);

and the result is available in request.body.name on the server.

SQL Query to search schema of all tables

You can also try doing this using one of many third party tools that are available for this.

Queries are great for simple searches but if you need to do more manipulation with data, search for references and such this is where you can do a much better job with these.

Also, these come in very handy when some objects are encrypted and you need to search for

I’m using ApexSQL Search which is free but there are also many more (also free) on the market such as Red Gate or SSMS Tool Pack.

Database Diagram Support Objects cannot be Installed ... no valid owner

I had the same problem.
I wanted to view my diagram, which I created the same day at work, at home. But I couldn't because of this message.
I found out that the owner of the database was the user of my computer -as expected. but since the computer is in the company's domain, and I am not connected to the company's network, the database couldn't resolve the owner.

So what I did is change the owner to a local user and it worked!!
Hope this helps someone.

You change the user by right-click on the database, properties, files, owner

Hide Show content-list with only CSS, no javascript used

I wouldn't use checkboxes, i'd use the code you already have

DEMO http://jsfiddle.net/6W7XD/1/

CSS

body {
  display: block;
}
.span3:focus ~ .alert {
  display: none;
}
.span2:focus ~ .alert {
  display: block;
}
.alert{display:none;}

HTML

<span class="span3">Hide Me</span>
<span class="span2">Show Me</span>
<p class="alert" >Some alarming information here</p>

This way the text is only hidden on click of the hide element

Timer for Python game

  1. Asks you when to stop [seconds]
  2. Adds '0' at starting [1-9]
import time
import sys

stop = int(input('> '))
second = 0
print('> Stopwatch Started.')

while stop > second:
    if second < 9:
        second = second + 1
        time.sleep(1)
        sys.stdout.write('\r> ' + '0' + str(second))
    else:
        second += 1
        time.sleep(1)
        sys.stdout.write('\r' + '> ' + str(second))

print('\n> Stopwatch Stopped.')

Return list from async/await method

Works for me:

List<Item> list = Task.Run(() => manager.GetList()).Result;

in this way it is not necessary to mark the method with async in the call.

How to use a SQL SELECT statement with Access VBA

Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

How to remove jar file from local maven repository which was added with install:install-file?

  1. cd ~/.m2
  2. git init
  3. git commit -am "some comments"
  4. cd /path/to/your/project
  5. mvn install
  6. cd ~/.m2
  7. git reset --hard

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

What is the result of % in Python?

It's a modulo operation, except when it's an old-fashioned C-style string formatting operator, not a modulo operation. See here for details. You'll see a lot of this in existing code.

How to get week number in Python?

Generally to get the current week number (starts from Sunday):

from datetime import *
today = datetime.today()
print today.strftime("%U")

How to set up a PostgreSQL database in Django

I was having the same Issue on Mac.

The solution was to use only PIP to install everything, and touch some things.

First install PIP from: https://pip.pypa.io/en/latest/

Then you want to make sure if path to pg_config is in your PATH (echo $PATH), if not you can edit your bash_profile:

vi /Users/<user>/.bash_profile

and add this line:

export PATH=$PATH:/path/to/pg_config/bin

If you don't know where pg_config is you can use the "locate" tool, but be sure your locate.db is up to date (i was using an old locate.db and using paths that does not exists).

sudo /usr/libexec/locate.updatedb
locate pg_config

Then install Django (if needed) and psycopg2.

sudo pip install Django
sudo pip install psycopg2

And then in settings.py (localhost:defaultport)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': '',
        'PORT': '',
    }
}

Greets!

Get value from JToken that may not exist (best practices)

Here is how you can check if the token exists:

if (jobject["Result"].SelectToken("Items") != null) { ... }

It checks if "Items" exists in "Result".

This is a NOT working example that causes exception:

if (jobject["Result"]["Items"] != null) { ... }

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

Solving sslv3 alert handshake failure when trying to use a client certificate

The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.

Once changing this value to DEFAULT, run the following command:

/usr/bin/update-crypto-policies --set DEFAULT

Rerun the curl command and it should work.

How to convert date to timestamp?

function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}

$apply already in progress error

At any point in time, there can be only one $digest or $apply operation in progress. This is to prevent very hard to detect bugs from entering your application. The stack trace of this error allows you to trace the origin of the currently executing $apply or $digest call, which caused the error.

More info: https://docs.angularjs.org/error/$rootScope/inprog?p0=$apply

Alter a SQL server function to accept new optional parameter

From CREATE FUNCTION:

When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.

So you need to do:

SELECT dbo.fCalculateEstimateDate(647,DEFAULT)

Is there any way to set environment variables in Visual Studio Code?

Assuming you mean for a debugging session(?) then you can include a env property in your launch configuration.

If you open the .vscode/launch.json file in your workspace or select Debug > Open Configurations then you should see a set of launch configurations for debugging your code. You can then add to it an env property with a dictionary of string:string.

Here is an example for an ASP.NET Core app from their standard web template setting the ASPNETCORE_ENVIRONMENT to Development :

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": ".NET Core Launch (web)",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      // If you have changed target frameworks, make sure to update the program path.
      "program": "${workspaceFolder}/bin/Debug/netcoreapp2.0/vscode-env.dll",
      "args": [],
      "cwd": "${workspaceFolder}",
      "stopAtEntry": false,
      "internalConsoleOptions": "openOnSessionStart",
      "launchBrowser": {
        "enabled": true,
        "args": "${auto-detect-url}",
        "windows": {
          "command": "cmd.exe",
          "args": "/C start ${auto-detect-url}"
        },
        "osx": {
          "command": "open"
        },
        "linux": {
          "command": "xdg-open"
        }
      },
      "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "sourceFileMap": {
        "/Views": "${workspaceFolder}/Views"
      }
    },
    {
      "name": ".NET Core Attach",
      "type": "coreclr",
      "request": "attach",
      "processId": "${command:pickProcess}"
    }
  ]
}

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

How do I `jsonify` a list in Flask?

You can't but you can do it anyway like this. I needed this for jQuery-File-Upload

import json
# get this object
from flask import Response

#example data:

    js = [ { "name" : filename, "size" : st.st_size , 
        "url" : url_for('show', filename=filename)} ]
#then do this
    return Response(json.dumps(js),  mimetype='application/json')

phpmailer: Reply using only "Reply To" address

At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.

    $mail->ClearReplyTos();
    $mail->addReplyTo([email protected], 'EXAMPLE');

Java count occurrence of each item in an array

I would use a hashtable with in key takes the element of the array (here string) and in value an Integer.

then go through the list doing something like this :

for(String s:array){
if(hash.containsKey(s)){
  Integer i = hash.get(s);
  i++;
}else{
  hash.put(s, new Interger(1));
}

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Its already answered above. I will summarise the steps to check above.

run git remote -v in project dir. If the output shows remote url starting with https://abc then you may need username password everytime.

So to change the remote url run git remote set-url origin {ssh remote url address starts with mostly [email protected]:}.

Now run git remote -v to verify the changed remote url.

Refer : https://help.github.com/articles/changing-a-remote-s-url/

How to specify the bottom border of a <tr>?

Add border-collapse:collapse to the table.

Example:

table.myTable{
  border-collapse:collapse;
}

table.myTable tr{
  border:1px solid red;
}

This worked for me.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Storing Form Data as a Session Variable

To use session variables, it's necessary to start the session by using the session_start function, this will allow you to store your data in the global variable $_SESSION in a productive way.

so your code will finally look like this :

<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

<?php 
 
 // starting the session
 session_start();


 if (isset($_POST['Submit'])) { 
 $_SESSION['picturenum'] = $_POST['picturenum'];
 } 
?> 

<strong><?php echo $_SESSION['picturenum'];?></strong>

to make it easy to use and to avoid forgetting it again, you can create a session_file.php which you will want to be included in all your codes and will start the session for you:

session_start.php

 <?php
   session_start();
 ?> 

and then include it wherever you like :

<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

<?php 
 
 // including the session file
 require_once("session_start.php");


 if (isset($_POST['Submit'])) { 
 $_SESSION['picturenum'] = $_POST['picturenum'];
 } 
?> 

that way it is more portable and easy to maintain in the future.

other remarks

  • if you are using Apache version 2 or newer, be careful. instead of
    <?
    to open php's tags, use <?php, otherwise your code will not be interpreted

  • variables names in php are case-sensitive, instead of write $_session, write $_SESSION in capital letters

good work!

How to allow users to check for the latest app version from inside the app?

If it is an application on the Market, then on app start-up, fire an Intent to open up the Market app hopefully which will cause it to check for updates.

Otherwise implementing and update checker is fairly easy. Here is my code (roughly) for it:

String response = SendNetworkUpdateAppRequest(); // Your code to do the network request
                                                 // should send the current version
                                                 // to server
if(response.equals("YES")) // Start Intent to download the app user has to manually install it by clicking on the notification
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("URL TO LATEST APK")));

Of course you should rewrite this to do the request on a background thread but you get the idea.

If you like something a little but more complex but allows your app to automatically apply the update see here.

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

To fix this issue in Web.config I just had to add debug="true"

  <system.web>
    <compilation targetFramework="4.0" debug="true">

What helped me to find this solution has been looking at the Modules windows while debugging and saw that for my ASP.NET DLLs loaded I had: Binary was not built with debug information.

Auto-loading lib files in Rails 4

I think this may solve your problem:

  1. in config/application.rb:

    config.autoload_paths << Rails.root.join('lib')
    

    and keep the right naming convention in lib.

    in lib/foo.rb:

    class Foo
    end
    

    in lib/foo/bar.rb:

    class Foo::Bar
    end
    
  2. if you really wanna do some monkey patches in file like lib/extensions.rb, you may manually require it:

    in config/initializers/require.rb:

    require "#{Rails.root}/lib/extensions" 
    

P.S.

How to use ES6 Fat Arrow to .filter() an array of objects

You can't implicitly return with an if, you would need the braces:

let adults = family.filter(person => { if (person.age > 18) return person} );

It can be simplified though:

let adults = family.filter(person => person.age > 18);

OpenCV in Android Studio

This worked for me and was as easy as adding a gradle dependancy:

https://bintray.com/seesaa/maven/opencv#

https://github.com/seesaa/opencv-android

The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.

It seems to build and the suggested test:

static {
    OpenCVLoader.initDebug();
}

spits out a bunch of output that looks about right to me.

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Here is my solution:

dependencies: Gmaps.js, jQuery

var Maps = function($) {
   var lost_addresses = [],
       geocode_count  = 0;

   var addMarker = function() { console.log('Marker Added!') };

   return {
     getGecodeFor: function(addresses) {
        var latlng;
        lost_addresses = [];
        for(i=0;i<addresses.length;i++) {
          GMaps.geocode({
            address: addresses[i],
            callback: function(response, status) {
              if(status == google.maps.GeocoderStatus.OK) {
                addMarker();
              } else if(status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                lost_addresses.push(addresses[i]);
              }

               geocode_count++;
               // notify listeners when the geocode is done
               if(geocode_count == addresses.length) {
                 $.event.trigger({ type: 'done:geocoder' });
               }
            }
          });
        }
     },
     processLostAddresses: function() {
       if(lost_addresses.length > 0) {
         this.getGeocodeFor(lost_addresses);
       }
     }
   };
}(jQuery);

Maps.getGeocodeFor(address);

// listen to done:geocode event and process the lost addresses after 1.5s
$(document).on('done:geocode', function() {
  setTimeout(function() {
    Maps.processLostAddresses();
  }, 1500);
});

ImportError: No module named enum

Depending on your rights, you need sudo at beginning.

Parse date without timezone javascript

There are some inherent problems with date parsing that are unfortunately not addressed well by default.

-Human readable dates have implicit timezone in them
-There are many widely used date formats around the web that are ambiguous

To solve these problems easy and clean one would need a function like this:

>parse(whateverDateTimeString,expectedDatePattern,timezone)
"unix time in milliseconds"

I have searched for this, but found nothing like that!

So I created: https://github.com/zsoltszabo/timestamp-grabber

Enjoy!

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

I'll start with your last question:

Why are these new categories needed?

The C++ standard contains many rules that deal with the value category of an expression. Some rules make a distinction between lvalue and rvalue. For example, when it comes to overload resolution. Other rules make a distinction between glvalue and prvalue. For example, you can have a glvalue with an incomplete or abstract type but there is no prvalue with an incomplete or abstract type. Before we had this terminology the rules that actually need to distinguish between glvalue/prvalue referred to lvalue/rvalue and they were either unintentionally wrong or contained lots of explaining and exceptions to the rule a la "...unless the rvalue is due to unnamed rvalue reference...". So, it seems like a good idea to just give the concepts of glvalues and prvalues their own name.

What are these new categories of expressions? How do these new categories relate to the existing rvalue and lvalue categories?

We still have the terms lvalue and rvalue that are compatible with C++98. We just divided the rvalues into two subgroups, xvalues and prvalues, and we refer to lvalues and xvalues as glvalues. Xvalues are a new kind of value category for unnamed rvalue references. Every expression is one of these three: lvalue, xvalue, prvalue. A Venn diagram would look like this:

    ______ ______
   /      X      \
  /      / \      \
 |   l  | x |  pr  |
  \      \ /      /
   \______X______/
       gl    r

Examples with functions:

int   prvalue();
int&  lvalue();
int&& xvalue();

But also don't forget that named rvalue references are lvalues:

void foo(int&& t) {
  // t is initialized with an rvalue expression
  // but is actually an lvalue expression itself
}

Change One Cell's Data in mysql

Try the following:

UPDATE TableName SET ValueName=@parameterName WHERE
IdName=@ParameterIdName

How to indent HTML tags in Notepad++

I have a solution for you.

Just you need to install a plugin named Indent By Fold.

You can install this by going through Plugins -> Plugin Manager -> Show Plugin Manager. OR Plugins -> Plugins Admin -> chekmark Indent By Fold from list than install

Then just select the list item and all you need is to type the first word then you got it.

you can use this plugin from a plugin in the menu bar.


Serving static web resources in Spring Boot & Spring Security application

This may be an answer (for spring boot 2) and a question at the same time. It seems that in spring boot 2 combined with spring security everything (means every route/antmatcher) is protected by default if you use an individual security mechanism extended from

WebSecurityConfigurerAdapter

If you don´t use an individual security mechanism, everything is as it was?

In older spring boot versions (1.5 and below) as Andy Wilkinson states in his above answer places like public/** or static/** are permitted by default.

So to sum this question/answer up - if you are using spring boot 2 with spring security and have an individual security mechanism you have to exclusivley permit access to static contents placed on any route. Like so:

@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

private final ThdAuthenticationProvider thdAuthenticationProvider;

private final ThdAuthenticationDetails thdAuthenticationDetails;

/**
 * Overloaded constructor.
 * Builds up the needed dependencies.
 *
 * @param thdAuthenticationProvider a given authentication provider
 * @param thdAuthenticationDetails  given authentication details
 */
@Autowired
public SpringSecurityConfiguration(@NonNull ThdAuthenticationProvider thdAuthenticationProvider,
                                   @NonNull ThdAuthenticationDetails thdAuthenticationDetails) {
    this.thdAuthenticationProvider = thdAuthenticationProvider;
    this.thdAuthenticationDetails = thdAuthenticationDetails;
}

/**
 * Creates the AuthenticationManager with the given values.
 *
 * @param auth the AuthenticationManagerBuilder
 */
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {

    auth.authenticationProvider(thdAuthenticationProvider);
}

/**
 * Configures the http Security.
 *
 * @param http HttpSecurity
 * @throws Exception a given exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .antMatchers("/management/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())
            .antMatchers("/settings/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())

            .anyRequest()
            .fullyAuthenticated()
            .and()
            .formLogin()
            .authenticationDetailsSource(thdAuthenticationDetails)
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/bundle/index", true)
            .failureUrl("/denied")
            .and()
            .logout()
            .invalidateHttpSession(true)
            .logoutSuccessUrl("/login")
            .logoutUrl("/logout")
            .and()
            .exceptionHandling()
            .accessDeniedHandler(new CustomAccessDeniedHandler());
}

}

Please mind this line of code, which is new:

.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

If you use spring boot 1.5 and below you don´t need to permit these locations (static/public/webjars etc.) explicitly.

Here is the official note, what has changed in the new security framework as to old versions of itself:

Security changes in Spring Boot 2.0 M4

I hope this helps someone. Thank you! Have a nice day!

How can I add items to an empty set in python

When you assign a variable to empty curly braces {} eg: new_set = {}, it becomes a dictionary. To create an empty set, assign the variable to a 'set()' ie: new_set = set()

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

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

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

Hbase quickly count number of rows

If you're using a scanner, in your scanner try to have it return the least number of qualifiers as possible. In fact, the qualifier(s) that you do return should be the smallest (in byte-size) as you have available. This will speed up your scan tremendously.

Unfortuneately this will only scale so far (millions-billions?). To take it further, you can do this in real time but you will first need to run a mapreduce job to count all rows.

Store the Mapreduce output in a cell in HBase. Every time you add a row, increment the counter by 1. Every time you delete a row, decrement the counter.

When you need to access the number of rows in real time, you read that field in HBase.

There is no fast way to count the rows otherwise in a way that scales. You can only count so fast.

How to show data in a table by using psql command line interface?

On windows use the name of the table in quotes: TABLE "user"; or SELECT * FROM "user";

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

Handling polymorphism is either model-bound or requires lots of code with various custom deserializers. I'm a co-author of a JSON Dynamic Deserialization Library that allows for model-independent json deserialization library. The solution to OP's problem can be found below. Note that the rules are declared in a very brief manner.

public class SOAnswer {
    @ToString @Getter @Setter
    @AllArgsConstructor @NoArgsConstructor
    public static abstract class Animal {
        private String name;    
    }

    @ToString(callSuper = true) @Getter @Setter
    @AllArgsConstructor @NoArgsConstructor
    public static class Dog extends Animal {
        private String breed;
    }

    @ToString(callSuper = true) @Getter @Setter
    @AllArgsConstructor @NoArgsConstructor
    public static class Cat extends Animal {
        private String favoriteToy;
    }
    
    
    public static void main(String[] args) {
        String json = "[{"
                + "    \"name\": \"pluto\","
                + "    \"breed\": \"dalmatian\""
                + "},{"
                + "    \"name\": \"whiskers\","
                + "    \"favoriteToy\": \"mouse\""
                + "}]";
        
        // create a deserializer instance
        DynamicObjectDeserializer deserializer = new DynamicObjectDeserializer();
        
        // runtime-configure deserialization rules; 
        // condition is bound to the existence of a field, but it could be any Predicate
        deserializer.addRule(DeserializationRuleFactory.newRule(1, 
                (e) -> e.getJsonNode().has("breed"),
                DeserializationActionFactory.objectToType(Dog.class)));
        
        deserializer.addRule(DeserializationRuleFactory.newRule(1, 
                (e) -> e.getJsonNode().has("favoriteToy"),
                DeserializationActionFactory.objectToType(Cat.class)));
        
        List<Animal> deserializedAnimals = deserializer.deserializeArray(json, Animal.class);
        
        for (Animal animal : deserializedAnimals) {
            System.out.println("Deserialized Animal Class: " + animal.getClass().getSimpleName()+";\t value: "+animal.toString());
        }
    }
}

Maven depenendency for pretius-jddl (check newest version at maven.org/jddl:

<dependency>
  <groupId>com.pretius</groupId>
  <artifactId>jddl</artifactId>
  <version>1.0.0</version>
</dependency>

.htaccess: where is located when not in www base dir

. (dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess files, then they are probably in the root folder for the website.

If you are using a command line (terminal) to access, then they will only show up if you use:

ls -a

If you are using a GUI application, look for a setting to "show hidden files" or something similar.

If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):

cd /
find . -name ".htaccess"

This will list out any files it finds with that name.

How can I read inputs as numbers?

def dbz():
    try:
        r = raw_input("Enter number:")
        if r.isdigit():
            i = int(raw_input("Enter divident:"))
            d = int(r)/i
            print "O/p is -:",d
        else:
            print "Not a number"
    except Exception ,e:
        print "Program halted incorrect data entered",type(e)
dbz()

Or 

num = input("Enter Number:")#"input" will accept only numbers

How to remove unused imports in Intellij IDEA on commit?

If you are using IntelliJ IDEA or Android Studio:

Android optimize imports

Go to Settings > Editor > General >Auto Import and check the Optimize imports on the fly checkbox.

Best way to retrieve variable values from a text file?

The other solutions posted here didn't work for me, because:

  • i just needed parameters from a file for a normal script
  • import * didn't work for me, as i need a way to override them by choosing another file
  • Just a file with a dict wasn't fine, as I needed comments in it.

So I ended up using Configparser and globals().update()

Test file:

#File parametertest.cfg:
[Settings]
#Comments are no Problem
test= True
bla= False    #Here neither

#that neither

And that's my demo script:

import ConfigParser

cfg = ConfigParser.RawConfigParser()
cfg.read('parametertest.cfg')       # Read file

#print cfg.getboolean('Settings','bla') # Manual Way to acess them

par=dict(cfg.items("Settings"))
for p in par:
    par[p]=par[p].split("#",1)[0].strip() # To get rid of inline comments

globals().update(par)  #Make them availible globally

print bla

It's just for a file with one section now, but that will be easy to adopt.

Hope it will be helpful for someone :)

In Python How can I declare a Dynamic Array

In python, A dynamic array is an 'array' from the array module. E.g.

from array import array
x = array('d')          #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop()                 # returns 2.2

This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.

However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.

See https://docs.python.org/2/library/array.html for details.

Declare a variable in DB2 SQL

I imagine this forum posting, which I quote fully below, should answer the question.


Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):

BEGIN ATOMIC
 DECLARE example VARCHAR(15) ;
 SET example = 'welcome' ;
 SELECT *
 FROM   tablename
 WHERE  column1 = example ;
END

or (in any environment):

WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM   tablename, t
WHERE  column1 = example

or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):

CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM   tablename
WHERE  column1 = example ;

What is the error "Every derived table must have its own alias" in MySQL?

Here's a different example that can't be rewritten without aliases ( can't GROUP BY DISTINCT).

Imagine a table called purchases that records purchases made by customers at stores, i.e. it's a many to many table and the software needs to know which customers have made purchases at more than one store:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases)
  GROUP BY customer_id HAVING 1 < SUM(1);

..will break with the error Every derived table must have its own alias. To fix:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases) AS custom
  GROUP BY customer_id HAVING 1 < SUM(1);

( Note the AS custom alias).

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

How do I manage MongoDB connections in a Node.js web application?

The primary committer to node-mongodb-native says:

You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool.

So, to answer your question directly, reuse the db object that results from MongoClient.connect(). This gives you pooling, and will provide a noticeable speed increase as compared with opening/closing connections on each db action.

FULL OUTER JOIN vs. FULL JOIN

It's true that some databases recognize the OUTER keyword. Some do not. Where it is recognized, it is usually an optional keyword. Almost always, FULL JOIN and FULL OUTER JOIN do exactly the same thing. (I can't think of an example where they do not. Can anyone else think of one?)

This may leave you wondering, "Why would it even be a keyword if it has no meaning?" The answer boils down to programming style.

In the old days, programmers strived to make their code as compact as possible. Every character meant longer processing time. We used 1, 2, and 3 letter variables. We used 2 digit years. We eliminated all unnecessary white space. Some people still program that way. It's not about processing time anymore. It's more about fast coding.

Modern programmers are learning to use more descriptive variables and put more remarks and documentation into their code. Using extra words like OUTER make sure that other people who read the code will have an easier time understanding it. There will be less ambiguity. This style is much more readable and kinder to the people in the future who will have to maintain that code.

Prevent flicker on webkit-transition of webkit-transform

For a more detailed explanation, check out this post:

http://www.viget.com/inspire/webkit-transform-kill-the-flash/

I would definitely avoid applying it to the entire body. The key is to make sure whatever specific element you plan on transforming in the future starts out rendered in 3d so the browsers doesn't have to switch in and out of rendering modes. Adding

-webkit-transform: translateZ(0) 

(or either of the options already mentioned) to the animated element will accomplish this.

Convert comma separated string to array in PL/SQL

You can use Replace Function to replace comma easily. To Do this-

The syntax for the REPLACE function in SQL Server (Transact-SQL) is:
REPLACE( string, string_to_replace, replacement_string )

Parameters or Arguments

string : The source string from which a sequence of characters will be replaced by another set of characters.
string_to_replace : The string that will be searched for in string1.
replacement_string : The replacement string. All occurrences of string_to_replace will be replaced with replacement_string in string1.
Note :

The REPLACE function performs a replacement that is not case-sensitive. So all occurrences of string_to_replace will be replaced with replacement_string regardless of the case of string_to_replace or replacement_string

For Example :
SELECT REPLACE('Kapil,raj,chouhan', ',' , ' ') from DUAL;
Result : Kapil raj chouhan

SELECT REPLACE('I Live In India', ' ' , '-') from DUAL;
Result : I-Live-In-India

SELECT REPLACE('facebook.com', 'face' , 'friends') from DUAL;
Result : friendsbook.com

I Hope it will be usefull for you.

How do I iterate over an NSArray?

Here is how you declare an array of strings and iterate over them:

NSArray *langs = @[@"es", @"en", @"pt", @"it", @"fr"];

for (int i = 0; i < [langs count]; i++) {
  NSString *lang = (NSString*) [langs objectAtIndex:i];
  NSLog(@"%@, ",lang);
}

How to deploy a war file in Tomcat 7

If you installed tomcat7 using apt-get in linux then, deploy your app to /var/lib/tomcat7/webapps/

eg.

sudo service tomcat7 stop

mvn clean package
sudo cp target/DestroyTheWorldWithPeace.war /var/lib/tomcat7/webapps/
#you might also want to make sure war file has permission (`777` not just `+x`)
sudo service tomcat7 start

Also, keep tailing the tomcat log so that you can verify that your app is actually making peace with tomcat.

tail -f /var/lib/tomcat7/logs/catalina.out

The deployed application should appear in http://172.16.35.155:8080/manager/html

Move SQL data from one table to another

You should be able to with a subquery in the INSERT statement.

INSERT INTO table1(column1, column2) SELECT column1, column2 FROM table2 WHERE ...;

followed by deleting from table1.

Remember to run it as a single transaction so that if anything goes wrong you can roll the entire operation back.

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

Python function as a function argument?

  1. Yes. By including the function call in your input argument/s, you can call two (or more) functions at once.

For example:

def anotherfunc(inputarg1, inputarg2):
    pass
def myfunc(func = anotherfunc):
    print func

When you call myfunc, you do this:

myfunc(anotherfunc(inputarg1, inputarg2))

This will print the return value of anotherfunc.

Hope this helps!

Remove first 4 characters of a string with PHP

function String2Stars($string='',$first=0,$last=0,$rep='*'){
  $begin  = substr($string,0,$first);
  $middle = str_repeat($rep,strlen(substr($string,$first,$last)));
  $end    = substr($string,$last);
  $stars  = $begin.$middle.$end;
  return $stars;
}

example

$string = 'abcdefghijklmnopqrstuvwxyz';
echo String2Stars($string,5,-5);   // abcde****************vwxyz

Why is Git better than Subversion?

Well, it's distributed. Benchmarks indicate that it's considerably faster (given its distributed nature, operations like diffs and logs are all local so of course it's blazingly faster in this case), and working folders are smaller (which still blows my mind).

When you're working on subversion, or any other client/server revision control system, you essentially create working copies on your machine by checking-out revisions. This represents a snapshot in time of what the repository looks like. You update your working copy via updates, and you update the repository via commits.

With a distributed version control, you don't have a snapshot, but rather the entire codebase. Wanna do a diff with a 3 month old version? No problem, the 3 month old version is still on your computer. This doesn't only mean things are way faster, but if you're disconnected from your central server, you can still do many of the operations you're used to. In other words, you don't just have a snapshot of a given revision, but the entire codebase.

You'd think that Git would take up a bunch of space on your harddrive, but from a couple benchmarks I've seen, it actually takes less. Don't ask me how. I mean, it was built by Linus, he knows a thing or two about filesystems I guess.

How to uninstall Golang?

In MacOS, you can just do it with brew:

brew uninstall go
brew install go
brew upgrade go

Get first and last day of month using threeten, LocalDate

The API was designed to support a solution that matches closely to business requirements

import static java.time.temporal.TemporalAdjusters.*;

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.with(firstDayOfMonth());
LocalDate end = initial.with(lastDayOfMonth());

However, Jon's solutions are also fine.

Calling stored procedure with return value

The version of EnterpriseLibrary on my machine had other parameters. This was working:

        SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
        retval.Direction = System.Data.ParameterDirection.ReturnValue;
        cmd.Parameters.Add(retval);
        db.ExecuteNonQuery(cmd);
        object o = cmd.Parameters["@ReturnValue"].Value;

Check whether number is even or odd

If the remainder when you divide by 2 is 0, it's even. % is the operator to get a remainder.

How to import load a .sql or .csv file into SQLite?

If you are happy to use a (python) script then there is a python script that automates this at: https://github.com/rgrp/csv2sqlite

This will auto-create the table for you as well as do some basic type-guessing and data casting for you (so e.g. it will work out something is a number and set the column type to "real").

Headers and client library minor version mismatch

Your PHP was compiled with MySQL 5.1 but now it is linking a mysql library of 5.5.X family. You have to upgrade PHP to a version compiled with MySQL 5.5 or revert back mysql client libraries to 5.1.x.

PermissionError: [Errno 13] Permission denied

I had a similar problem. I thought it might be with the system. But, using shutil.copytree() from the shutil module solved the problem for me!

How to remove last n characters from every element in the R vector

The same may be achieved with the stringi package:

library('stringi')
char_array <- c("foo_bar","bar_foo","apple","beer")
a <- data.frame("data"=char_array, "data2"=1:4)
(a$data <- stri_sub(a$data, 1, -4)) # from the first to the last but 4th char
## [1] "foo_" "bar_" "ap"   "b" 

Xcode 9 Swift Language Version (SWIFT_VERSION)

In my case, all warn disappeared after I directly changed swift version from 2.x to 4.0 in build settings except two warn.

These warning related to myprojectnameTests and myprojectnameUITests folder. I didn't notice and I thought its relate to direct immigration from Xcode 7 to Xcode 9 and I thought I couldn't solve this problem and I should install missed Xcode 8 version.

In my case, I deleted these folders and all warns disappeared, but you can recreate this folder and contains using this:

file > new > target > (uitest or unittest extensions)

and use this article for create test cases: https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/04-writing_tests.html

Recommended way to insert elements into map

To quote:

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

So insert will not change the value if the key already exists, the [] operator will.

EDIT:

This reminds me of another recent question - why use at() instead of the [] operator to retrieve values from a vector. Apparently at() throws an exception if the index is out of bounds whereas [] operator doesn't. In these situations it's always best to look up the documentation of the functions as they will give you all the details. But in general, there aren't (or at least shouldn't be) two functions/operators that do the exact same thing.

My guess is that, internally, insert() will first check for the entry and afterwards itself use the [] operator.

React Native: How to select the next TextInput after pressing the "next" keyboard button?

<TextInput placeholder="Nombre"
    ref="1"
    editable={true}
    returnKeyType="next"
    underlineColorAndroid={'#4DB6AC'}
    blurOnSubmit={false}
    value={this.state.First_Name}
    onChangeText={First_Name => this.setState({ First_Name })}
    onSubmitEditing={() => this.focusNextField('2')}
    placeholderTextColor="#797a7a" style={{ marginBottom: 10, color: '#808080', fontSize: 15, width: '100%', }} />

<TextInput placeholder="Apellido"
    ref="2"
    editable={true}
    returnKeyType="next"
    underlineColorAndroid={'#4DB6AC'}
    blurOnSubmit={false}
    value={this.state.Last_Name}
    onChangeText={Last_Name => this.setState({ Last_Name })}
    onSubmitEditing={() => this.focusNextField('3')}
    placeholderTextColor="#797a7a" style={{ marginBottom: 10, color: '#808080', fontSize: 15, width: '100%', }} />

and add method

focusNextField(nextField) {
    this.refs[nextField].focus();
}

How to install XNA game studio on Visual Studio 2012?

Yes, it's possible with a bit of tweak. Unfortunately, you still have to have VS 2010 installed.

  1. First, install XNA Game Studio 4.0. The easiest way is to install the Windows Phone SDK 7.1 which contains everything required.

  2. Copy the XNA Game Extension from VS 10 to VS 11 by opening a command prompt 'as administrator' and executing the following (may vary if not x64 computer with defaults paths) :

    xcopy /e "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0" "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"

  3. Run notepad as administrator then open extension.vsixmanifest in the destination directory just created.

  4. Upgrade the Supported product version to match the new version (or duplicate the whole VisualStudio element and change the Version attribute, as @brainslugs83 said in comments):

    <SupportedProducts>
      <VisualStudio Version="11.0">
        <Edition>VSTS</Edition>
        <Edition>VSTD</Edition>
        <Edition>Pro</Edition>
        <Edition>VCSExpress</Edition>
        <Edition>VPDExpress</Edition>
      </VisualStudio>
    </SupportedProducts>
    
  5. Don't forget to clear/delete your cache in %localappdata%\Microsoft\VisualStudio\12.0\Extensions.

  6. You may have to run the command to tells Visual Studio that new extensions are available. If you see an 'access denied' message, try launching the console as an administrator.

    "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /setup
    

This has been tested for Windows Games, but not WP7 or Xbox games.

[Edit] According Jowsty, this works also for XBox 360 Games.

[Edit for Visual Studio 2013 & Windows 8.1] See here for documentation on installing Windows Phone SDK 7.1 on Windows 8.1. Use VS version number 12.0 in place of 11.0 for all of these steps, and they will still work correctly.

How to iterate through a list of objects in C++

-> it works like pointer u don't have to use *

for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'

How to mock location on device?

Use this permission in manifest file

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION">

android studio will recommend that "Mock location should only be requested in a test or debug-specific manifest file (typically src/debug/AndroidManifest.xml)" just disable the inspection

Now make sure you have checked the "Allow mock locations" in developer setting of your phone

Use LocationManager

locationManager.addTestProvider(mocLocationProvider, false, false,
                false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);

Now set the location wherever you want

Location mockLocation = new Location(mocLocationProvider); 
mockLocation.setLatitude(lat); 
mockLocation.setLongitude(lng); 
mockLocation.setAltitude(alt); 
mockLocation.setTime(System.currentTimeMillis()); 
locationManager.setTestProviderLocation( mocLocationProvider, mockLocation); 

What does \d+ mean in regular expression terms?

\d means 'digit'. + means, '1 or more times'. So \d+ means one or more digit. It will match 12 and 1.

ld cannot find -l<library>

I had a similar problem with another library and the reason why it didn't found it, was that I didn't run the make install (after running ./configure and make) for that library. The make install may require root privileges (in this case use: sudo make install). After running the make install you should have the so files in the correct folder, i.e. here /usr/local/lib and not in the folder mentioned by you.

What does the [Flags] Enum Attribute mean in C#?

I asked recently about something similar.

If you use flags you can add an extension method to enums to make checking the contained flags easier (see post for detail)

This allows you to do:

[Flags]
public enum PossibleOptions : byte
{
    None = 0,
    OptionOne = 1,
    OptionTwo = 2,
    OptionThree = 4,
    OptionFour = 8,

    //combinations can be in the enum too
    OptionOneAndTwo = OptionOne | OptionTwo,
    OptionOneTwoAndThree = OptionOne | OptionTwo | OptionThree,
    ...
}

Then you can do:

PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree 

if( opt.IsSet( PossibleOptions.OptionOne ) ) {
    //optionOne is one of those set
}

I find this easier to read than the most ways of checking the included flags.

What operator is <> in VBA

Not Equal To


Before C came along and popularized !=, languages tended to use <> for not equal to.

At least, the various dialects of Basic did, and they predate C.

An even older and more unusual case is Fortran, which uses .NE., as in X .NE. Y.

How do I Search/Find and Replace in a standard string?

In C++11, you can do this as a one-liner with a call to regex_replace:

#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;

output:

Removeallspaces

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

How to capture a list of specific type with mockito

For an earlier version of junit, you can do

Class<Map<String, String>> mapClass = (Class) Map.class;
ArgumentCaptor<Map<String, String>> mapCaptor = ArgumentCaptor.forClass(mapClass);

Using {% url ??? %} in django templates

The url template tag will pass the parameter as a string and not as a function reference to reverse(). The simplest way to get this working is adding a name to the view:

url(r'^/logout/' , logout_view, name='logout_view')

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

As for second question - you can use Fiddler filters to set response X-Frame-Options header manually to something like ALLOW-FROM *. But, of course, this trick will work only for you - other users still won't be able to see iframe content(if they not do the same).

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

  • if you unable to find assembly reference from when (Right click on reference ->add required assembly)

try this Package manager console
Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3 and then add by using add reference .

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

Something I stumbled upon today for a DLL I knew was working fine with my VS2013 project, but not with VS2015:

Go to: Project -> XXXX Properties -> Build -> Uncheck "Prefer 32-bit"

This answer is way overdue and probably won't do any good, but if you. But I hope this will help somebody someday.

How to add message box with 'OK' button?

@Override
protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case 0:
    {               
        return new AlertDialog.Builder(this)
        .setMessage("text here")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {                   
            @Override
            public void onClick(DialogInterface arg0, int arg1) 
            {
                try
                {

                }//end try
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),  "", Toast.LENGTH_LONG).show();
                }//end catch
            }//end onClick()
        }).create();                
    }//end case
  }//end switch
    return null;
}//end onCreateDialog

Generating a PDF file from React Components

You can use ReactPDF

Lets you convert a div into PDF with ease. You will need to match your existing markup to use ReactPDF markup, but it is worth it.

How to set CATALINA_HOME variable in windows 7?

In order to set CATALINA_HOME:

  1. First, unzip and paste the apache-tomcat-7.1.100 folder in your C:// drive folder.

NOTE: Do not place your apache tomcat folder within any other folder or drive, place it directly in C:// drive folder only. (I did this mistake and none of the above-mentioned solutions were working).

  1. Open environment variable dialog box (windows key+ pause-break key --> advanced setting).

  2. Add a new variable name as "CATALINA_HOME" and add the variable path as "C://apache-tomcat-7.1.100"(as in my case), in System Variables.

  3. Edit PATH variable name add "%CATALINA_HOME%\bin" and press OK.

  4. Close the window and it will be saved.

  5. Open Command Prompt window and type command- "%CATALINA_HOME%\bin\startup.bat" to run and start the Tomcat server.

  6. END!

MySQL: update a field only if condition is met

Another solution which, in my opinion, is easier to read would be:

UPDATE test 
    SET something = 1, field = IF(condition is true, 1, field) 
    WHERE id = 123

What this does is set 'field' to 1 (like OP used as example) if the condition is met and use the current value of 'field' if not met. Using the previous value is the same as not changing, so there you go.

Have Excel formulas that return 0, make the result blank

Use conditional formatting (Home tab, styles section) and apply highlight cells rule (putting 0 in the Format cells that are equal to box) but select custom format then the Number tab. Select Category custom and in the type box put:

0;-0;;@

Sounds complicated but is actually simple.

This gives the advantage that the cell looks empty but 0 is still the underlying value, so any formulas you use against that cell/selection will still see it as being numeric and saves on lots of messing around with chained IF statements.

How to disable scrolling in UITableView table when the content fits on the screen

You can edit this in your storyboard (if you are using one). Under the table view there is a checkbox that says "Scrolling Enabled". Uncheck it and you're done.

Downloading MySQL dump from command line

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%.%MM%.%DD%.%HH%.%Min%.%Sec%"
set drive=your backup folder
set databaseName=your databasename
set user="your database user"
set password="your database password"
subst Z: "C:\Program Files\7-Zip" 
subst M: "D:\AppServ\MySQL\bin"
set zipFile="%drive%\%databaseName%-%datestamp%.zip"
set sqlFile="%drive%\%databaseName%-%datestamp%.sql"
M:\mysqldump.exe --user=%user% --password=%password% --result-file="%sqlFile%" --databases %databaseName%
@echo Mysql Backup Created
Z:\7z.exe a -tzip "%zipFile%" "%sqlFile%"
@echo File Compress End
del %sqlFile%
@echo Delete mysql file
pause;

How to print_r $_POST array?

$_POST is already an array, so you don't need to wrap array() around it.

Try this instead:

<?php 

 for ($i=0;$i<count($_POST['id']);$i++) {

  echo "<p>".$_POST['id'][$i]."</p>";
  echo "<p>".$_POST['value'][$i]."</p>";
  echo "<hr />";

} 

 ?>

NOTE: This works because your id and value arrays are symmetrical. If they had different numbers of elements then you'd need to take a different approach.

Get login username in java

System.getProperty("user.name")

When to use StringBuilder in Java

The Microsoft certification material addresses this same question. In the .NET world, the overhead for the StringBuilder object makes a simple concatenation of 2 String objects more efficient. I would assume a similar answer for Java strings.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

In your case here is a implementation using directions service.

function displayRoute() {

    var start = new google.maps.LatLng(28.694004, 77.110291);
    var end = new google.maps.LatLng(28.72082, 77.107241);

    var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get "DirectionsRendererOptions" object
    directionsDisplay.setMap(map); // map should be already initialized.

    var request = {
        origin : start,
        destination : end,
        travelMode : google.maps.TravelMode.DRIVING
    };
    var directionsService = new google.maps.DirectionsService(); 
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

How to access remote server with local phpMyAdmin client?

You can set in the config.inc.php file of your phpMyAdmin installation.

$cfg['Servers'][$i]['host'] = '';

What are the differences between the BLOB and TEXT datatypes in MySQL?

According to High-performance Mysql book:

The only difference between the BLOB and TEXT families is that BLOB types store binary data with no collation or character set, but TEXT types have a character set and collation.

Remove trailing zeros from decimal in SQL Server

I had a similar issue, but was also required to remove the decimal point where no decimal was present, here was my solution which splits the decimal into its components, and bases the number of characters it takes from the decimal point string on the length of the fraction component (without using CASE). To make matters even more interesting, my number was stored as a float without its decimals.

DECLARE @MyNum FLOAT
SET @MyNum = 700000
SELECT CAST(PARSENAME(CONVERT(NUMERIC(15,2),@MyNum/10000),2) AS VARCHAR(10)) 
+ SUBSTRING('.',1,LEN(REPLACE(RTRIM(REPLACE(CAST(PARSENAME(CONVERT(NUMERIC(15,2),@MyNum/10000),1) AS VARCHAR(2)),'0',' ')),' ','0'))) 
+ REPLACE(RTRIM(REPLACE(CAST(PARSENAME(CONVERT(NUMERIC(15,2),@MyNum/10000),1) AS VARCHAR(2)),'0',' ')),' ','0') 

The result is painful, I know, but I got there, with much help from the answers above.

How to iterate (keys, values) in JavaScript?

tl;dr

  1. In ECMAScript 5, it is not possible.
  2. In ECMAScript 2015, it is possible with Maps.
  3. In ECMAScript 2017, it would be readily available.

ECMAScript 5:

No, its not possible with objects.

You should either iterate with for..in, or Object.keys, like this

for (var key in dictionary) {
    // check if the property/key is defined in the object itself, not in parent
    if (dictionary.hasOwnProperty(key)) {           
        console.log(key, dictionary[key]);
    }
}

Note: The if condition above is necessary, only if you want to iterate the properties which are dictionary object's very own. Because for..in will iterate through all the inherited enumerable properties.

Or

Object.keys(dictionary).forEach(function(key) {
    console.log(key, dictionary[key]);
});

ECMAScript 2015

In ECMAScript 2015, you can use Map objects and iterate them with Map.prototype.entries. Quoting example from that page,

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

var mapIter = myMap.entries();

console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]

Or iterate with for..of, like this

'use strict';

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const entry of myMap.entries()) {
  console.log(entry);
}

Output

[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]

Or

for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

Output

0 foo
1 bar
{} baz

ECMAScript 2017

ECMAScript 2017 would introduce a new function Object.entries. You can use this to iterate the object as you wanted.

'use strict';

const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
  console.log(key, value);
}

Output

a 1
b 2
c 3

How to execute python file in linux

I suggest that you add

#!/usr/bin/env python

instead of #!/usr/bin/python at the top of the file. The reason for this is that the python installation may be in different folders in different distros or different computers. By using env you make sure that the system finds python and delegates the script's execution to it.

As said before to make the script executable, something like:

chmod u+x name_of_script.py

should do.

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx


To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

Getters \ setters for dummies

In addition to @millimoose's answer, setters can also be used to update other values.

function Name(first, last) {
    this.first = first;
    this.last = last;
}

Name.prototype = {
    get fullName() {
        return this.first + " " + this.last;
    },

    set fullName(name) {
        var names = name.split(" ");
        this.first = names[0];
        this.last = names[1];
    }
};

Now, you can set fullName, and first and last will be updated and vice versa.

n = new Name('Claude', 'Monet')
n.first # "Claude"
n.last # "Monet"
n.fullName # "Claude Monet"
n.fullName = "Gustav Klimt"
n.first # "Gustav"
n.last # "Klimt"

decimal vs double! - Which one should I use and when?

System.Single / float - 7 digits
System.Double / double - 15-16 digits
System.Decimal / decimal - 28-29 significant digits

The way I've been stung by using the wrong type (a good few years ago) is with large amounts:

  • £520,532.52 - 8 digits
  • £1,323,523.12 - 9 digits

You run out at 1 million for a float.

A 15 digit monetary value:

  • £1,234,567,890,123.45

9 trillion with a double. But with division and comparisons it's more complicated (I'm definitely no expert in floating point and irrational numbers - see Marc's point). Mixing decimals and doubles causes issues:

A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used because the floating-point number might not exactly approximate the decimal number.

When should I use double instead of decimal? has some similar and more in depth answers.

Using double instead of decimal for monetary applications is a micro-optimization - that's the simplest way I look at it.

Temporarily switch working copy to a specific Git commit

If you are at a certain branch mybranch, just go ahead and git checkout commit_hash. Then you can return to your branch by git checkout mybranch. I had the same game bisecting a bug today :) Also, you should know about git bisect.

Setting the selected attribute on a select list using jQuery

Code:

var select = function(dropdown, selectedValue) {
    var options = $(dropdown).find("option");
    var matches = $.grep(options,
        function(n) { return $(n).text() == selectedValue; });
    $(matches).attr("selected", "selected");
};

Example:

select("#dropdown", "B");

Convenient C++ struct initialisation

The way /* B */ is fine in C++ also the C++0x is going to extend the syntax so it is useful for C++ containers too. I do not understand why you call it bad style?

If you want to indicate parameters with names then you can use boost parameter library, but it may confuse someone unfamiliar with it.

Reordering struct members is like reordering function parameters, such refactoring may cause problems if you don't do it very carefully.

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

$('body').on('click', '.anything', function(){})

If you want to capture click on everything then do

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

The real difference between "int" and "unsigned int"

The internal representation of int and unsigned int is the same.

Therefore, when you pass the same format string to printf it will be printed as the same.

However, there are differences when you compare them. Consider:

int x = 0x7FFFFFFF;
int y = 0xFFFFFFFF;
x < y // false
x > y // true
(unsigned int) x < (unsigned int y) // true
(unsigned int) x > (unsigned int y) // false

This can be also a caveat, because when comparing signed and unsigned integer one of them will be implicitly casted to match the types.

Connecting to remote MySQL server using PHP

It is very easy to connect remote MySQL Server Using PHP, what you have to do is:

  1. Create a MySQL User in remote server.

  2. Give Full privilege to the User.

  3. Connect to the Server using PHP Code (Sample Given Below)

$link = mysql_connect('your_my_sql_servername or IP Address', 'new_user_which_u_created', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';

mysql_select_db('sandsbtob',$link) or die ("could not open db".mysql_error());
// we connect to localhost at port 3306

Create line after text with css

This is the most easy way I found to achieve the result: Just use hr tag before the text, and set the margin top for text. Very short and easy to understand! jsfiddle

_x000D_
_x000D_
h2 {_x000D_
  background-color: #ffffff;_x000D_
  margin-top: -22px;_x000D_
  width: 25%;_x000D_
}_x000D_
_x000D_
hr {_x000D_
  border: 1px solid #e9a216;_x000D_
}
_x000D_
<br>_x000D_
_x000D_
<hr>_x000D_
<h2>ABOUT US</h2>
_x000D_
_x000D_
_x000D_

SQL Server: Extract Table Meta-Data (description, fields and their data types)

Depending on how much metadata you want, this is working for me: where could be the whole thing like Northwind.dbo.Products or just Products

SELECT c.name Field, 
    t.name Type,
    c.Precision, 
    c.Scale,
    c.is_nullable,
    c.collation_name 
FROM sys.columns c 
INNER JOIN sys.types t ON t.system_type_id=c.system_type_id
WHERE object_id=object_id('<table to inspect>')
ORDER BY column_id

How to pause a YouTube player when hiding the iframe?

Hey an easy way is to simply set the src of the video to nothing, so that the video will desapear while it's hidden an then set the src back to the video you want when you click on the link that opens the video.. to do that simply set an id to the youtube iframe and call the src function using that id like this:

<script type="text/javascript">
function deleteVideo()
{
document.getElementById('VideoPlayer').src='';
}

function LoadVideo()
{
document.getElementById('VideoPlayer').src='http://www.youtube.com/embed/WHAT,EVER,YOUTUBE,VIDEO,YOU,WHANT';
}
</script>

<body>

<p onclick="LoadVideo()">LOAD VIDEO</P>
<p onclick="deleteVideo()">CLOSE</P>

<iframe id="VideoPlayer" width="853" height="480" src="http://www.youtube.com/WHAT,EVER,YOUTUBE,VIDEO,YOU,HAVE" frameborder="0" allowfullscreen></iframe>

</boby>

SQL command to display history of queries

For MySQL > 5.1.11 or MariaDB

  1. SET GLOBAL log_output = 'TABLE';
  2. SET GLOBAL general_log = 'ON';
  3. Take a look at the table mysql.general_log

If you want to output to a log file:

  1. SET GLOBAL log_output = "FILE";
  2. SET GLOBAL general_log_file = "/path/to/your/logfile.log"
  3. SET GLOBAL general_log = 'ON';

As mentioned by jeffmjack in comments, these settings will be forgetting before next session unless you edit the configuration files (e.g. edit /etc/mysql/my.cnf, then restart to apply changes).

Now, if you'd like you can tail -f /var/log/mysql/mysql.log

More info here: Server System Variables

T-SQL: How to Select Values in Value List that are NOT IN the Table?

You should have a table with the list of emails to check. Then do this query:

SELECT E.Email, CASE WHEN U.Email IS NULL THEN 'Not Exists' ELSE 'Exists' END Status
FROM EmailsToCheck E
LEFT JOIN (SELECT DISTINCT Email FROM Users) U
ON E.Email = U.Email

Changing one character in a string

I would like to add another way of changing a character in a string.

>>> text = '~~~~~~~~~~~'
>>> text = text[:1] + (text[1:].replace(text[0], '+', 1))
'~+~~~~~~~~~'

How faster it is when compared to turning the string into list and replacing the ith value then joining again?.

List approach

>>> timeit.timeit("text = '~~~~~~~~~~~'; s = list(text); s[1] = '+'; ''.join(s)", number=1000000)
0.8268570480013295

My solution

>>> timeit.timeit("text = '~~~~~~~~~~~'; text=text[:1] + (text[1:].replace(text[0], '+', 1))", number=1000000)
0.588400217000526

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

How to check the presence of php and apache on ubuntu server through ssh

Try this.

dpkg -s apache2 | grep Status 

dpkg -s php5 | grep Status

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this one -

"SELECT 
       ID, Salt, password, BannedEndDate
     , (
          SELECT COUNT(1)
          FROM dbo.LoginFails l
          WHERE l.UserName = u.UserName
               AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
      ) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"

Custom Authentication in ASP.Net-Core

@Manish Jain, I suggest to implement the method with boolean return:

public class UserManager
{

    // Additional code here...            

    public async Task<bool> SignIn(HttpContext httpContext, UserDbModel user)
    {
        // Additional code here...            

        // Here the real authentication against a DB or Web Services or whatever 
        if (user.Email != null)
            return false;                    

        ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
        ClaimsPrincipal principal = new ClaimsPrincipal(identity);

        // This is for give the authentication cookie to the user when authentication condition was met
        await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        return true;
    }
}

Best font for coding

I like Consolas a lot. This top-10 list is a good resource for others. It includes examples and descriptions.

Difference between <? super T> and <? extends T> in Java

Based on Bert F's answer I would like to explain my understanding.

Lets say we have 3 classes as

public class Fruit{}

public class Melon extends Fruit{}

public class WaterMelon extends Melon{}

Here We have

List<? extends Fruit> fruitExtendedList = …

//Says that I can be a list of any object as long as this object extends Fruit.

Ok now lets try to get some value from fruitExtendedList

Fruit fruit = fruitExtendedList.get(position)

//This is valid as it can only return Fruit or its subclass.

Again lets try

Melon melon = fruitExtendedList.get(position)

//This is not valid because fruitExtendedList can be a list of Fruit only, it may not be 
//list of Melon or WaterMelon and in java we cannot assign sub class object to 
//super class object reference without explicitly casting it.

Same is the case for

WaterMelon waterMelon = fruitExtendedList.get(position)

Now lets try to set some object in fruitExtendedList

Adding fruit object

fruitExtendedList.add(new Fruit())

//This in not valid because as we know fruitExtendedList can be a list of any 
//object as long as this object extends Fruit. So what if it was the list of  
//WaterMelon or Melon you cannot add Fruit to the list of WaterMelon or Melon.

Adding Melon object

fruitExtendedList.add(new Melon())

//This would be valid if fruitExtendedList was the list of Fruit but it may 
//not be, as it can also be the list of WaterMelon object. So, we see an invalid 
//condition already.

Finally let try to add WaterMelon object

fruitExtendedList.add(new WaterMelon())

//Ok, we got it now we can finally write to fruitExtendedList as WaterMelon 
//can be added to the list of Fruit or Melon as any superclass reference can point 
//to its subclass object.

But wait what if someone decides to make a new type of Lemon lets say for arguments sake SaltyLemon as

public class SaltyLemon extends Lemon{}

Now fruitExtendedList can be list of Fruit, Melon, WaterMelon or SaltyLemon.

So, our statement

fruitExtendedList.add(new WaterMelon())

is not valid either.

Basically we can say that we cannot write anything to a fruitExtendedList.

This sums up List<? extends Fruit>

Now lets see

List<? super Melon> melonSuperList= …

//Says that I can be a list of anything as long as its object has super class of Melon.

Now lets try to get some value from melonSuperList

Fruit fruit = melonSuperList.get(position)

//This is not valid as melonSuperList can be a list of Object as in java all 
//the object extends from Object class. So, Object can be super class of Melon and 
//melonSuperList can be a list of Object type

Similarly Melon, WaterMelon or any other object cannot be read.

But note that we can read Object type instances

Object myObject = melonSuperList.get(position)

//This is valid because Object cannot have any super class and above statement 
//can return only Fruit, Melon, WaterMelon or Object they all can be referenced by
//Object type reference.

Now, lets try to set some value from melonSuperList.

Adding Object type object

melonSuperList.add(new Object())

//This is not valid as melonSuperList can be a list of Fruit or Melon.
//Note that Melon itself can be considered as super class of Melon.

Adding Fruit type object

melonSuperList.add(new Fruit())

//This is also not valid as melonSuperList can be list of Melon

Adding Melon type object

melonSuperList.add(new Melon())

//This is valid because melonSuperList can be list of Object, Fruit or Melon and in 
//this entire list we can add Melon type object.

Adding WaterMelon type object

melonSuperList.add(new WaterMelon())

//This is also valid because of same reason as adding Melon

To sum it up we can add Melon or its subclass in melonSuperList and read only Object type object.

SQL Server 2012 can't start because of a login failure

While ("run as SYSTEM") works, people should be advised this means going from a minimum-permissions type account to an account which has all permissions in the world. Which is very much not a recommended setup best practices or security-wise.

If you know what you are doing and know your SQL Server will always be run in an isolated environment (i.e. not on hotel or airport wifi) it's probably fine, but this creates a very real attack vector which can completely compromise a machine if on open internets.

This seems to be an error on Microsoft's part and people should be aware of the implications of the workaround posted.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

There is a new library called ipyvolume that may do what you want, the documentation shows live demos. The current version doesn't do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I'm the author)

Aborting a shell script if any command returns a non-zero value

Add this to the beginning of the script:

set -e

This will cause the shell to exit immediately if a simple command exits with a nonzero exit value. A simple command is any command not part of an if, while, or until test, or part of an && or || list.

See the bash(1) man page on the "set" internal command for more details.

I personally start almost all shell scripts with "set -e". It's really annoying to have a script stubbornly continue when something fails in the middle and breaks assumptions for the rest of the script.

How can I dismiss the on screen keyboard?

None of the above solutions don't work for me.

Flutter suggests this - Put your widget inside new GestureDetector() on which tap will hide keyboard and onTap use FocusScope.of(context).requestFocus(new FocusNode())

class Home extends StatelessWidget {
@override
  Widget build(BuildContext context) {
    var widget = new MaterialApp(
        home: new Scaffold(
            body: new Container(
                height:500.0,
                child: new GestureDetector(
                    onTap: () {
                        FocusScope.of(context).requestFocus(new FocusNode());
                    },
                    child: new Container(
                        color: Colors.white,
                        child:  new Column(
                            mainAxisAlignment:  MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,

                            children: [
                                new TextField( ),
                                new Text("Test"),                                
                            ],
                        )
                    )
                )
            )
        ),
    );

    return widget;
}}

Convert String To date in PHP

Use the strtotime function:

Example:

 $date = "25 december 2009";
 $my_date = date('m/d/y', strtotime($date));
 echo $my_date;

How to change package name in android studio?

In projects that use the Gradle build system, what you want to change is the applicationId in the build.gradle file. The build system uses this value to override anything specified by hand in the manifest file when it does the manifest merge and build.

For example, your module's build.gradle file looks something like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        // CHANGE THE APPLICATION ID BELOW
        applicationId "com.example.fred.myapplication"
        minSdkVersion 10
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
}

applicationId is the name the build system uses for the property that eventually gets written to the package attribute of the manifest tag in the manifest file. It was renamed to prevent confusion with the Java package name (which you have also tried to modify), which has nothing to do with it.

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

On groupby object, the agg function can take a list to apply several aggregation methods at once. This should give you the result you need:

df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])

How do I import/include MATLAB functions?

You should be able to put them in your ~/matlab on unix.

I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath from the matlab command line.

Clearing an HTML file upload field via JavaScript

I know it is quite old, but testing in the browser:

$0.value=null; // when $0 is the file upload element we talking about

erased the value and allow me to rechoose THE SAME FILE as before (means it worked!)

Tested in Chrome 81, FF 76, Safari (on iPad mini), 360 browser, Baidu browser, QQ browser, android browser.

Explanation:

As per my point of view that files selected can be more than 1, you'd better not set the value to a string - the final value sits in $0.files which may be more than 1. The browser need to parse the selected values from "value", so it is an active property. Set it to null, as per my understanding, will cause the browser to parse it to [] empty list in $0.files (this is what happened...)

How to delete an app from iTunesConnect / App Store Connect

As per 2018 in App Store Connect. We can delete/remove application with following stats.

enter image description here

App Store Connect details for Remove an app

So, from now onwards we can delete our test applications too from app store connect.

enter image description here

How can I implement prepend and append with regular JavaScript?

Here's an example of using prepend to add a paragraph to the document.

var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);

result:

<p>Example text</p>

Multiple inputs with same name through POST in php

Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:

<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin"  />

<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />

The outcome would be

$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'], 
          'city' => [ 'Berlin' , 'New York'] ];

To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:

<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin"  />

<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />

The outcome would be

$POST = [ 'address' => [ 
                 1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
                 2 => ['street' => 'Wallstreet', 'city' => 'New York'],
              ]
        ]

How to send HTTP request in java?

There's a great link about sending a POST request here by Example Depot::

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

If you want to send a GET request you can modify the code slightly to suit your needs. Specifically you have to add the parameters inside the constructor of the URL. Then, also comment out this wr.write(data);

One thing that's not written and you should beware of, is the timeouts. Especially if you want to use it in WebServices you have to set timeouts, otherwise the above code will wait indefinitely or for a very long time at least and it's something presumably you don't want.

Timeouts are set like this conn.setReadTimeout(2000); the input parameter is in milliseconds

Build query string for System.Net.HttpClient get

TL;DR: do not use accepted version as It's completely broken in relation to handling unicode characters, and never use internal API

I've actually found weird double encoding issue with the accepted solution:

So, If you're dealing with characters which need to be encoded, accepted solution leads to double encoding:

  • query parameters are auto encoded by using NameValueCollection indexer (and this uses UrlEncodeUnicode, not regular expected UrlEncode(!))
  • Then, when you call uriBuilder.Uri it creates new Uri using constructor which does encoding one more time (normal url encoding)
  • That cannot be avoided by doing uriBuilder.ToString() (even though this returns correct Uri which IMO is at least inconsistency, maybe a bug, but that's another question) and then using HttpClient method accepting string - client still creates Uri out of your passed string like this: new Uri(uri, UriKind.RelativeOrAbsolute)

Small, but full repro:

var builder = new UriBuilder
{
    Scheme = Uri.UriSchemeHttps,
    Port = -1,
    Host = "127.0.0.1",
    Path = "app"
};

NameValueCollection query = HttpUtility.ParseQueryString(builder.Query);

query["cyrillic"] = "????????";

builder.Query = query.ToString();
Console.WriteLine(builder.Query); //query with cyrillic stuff UrlEncodedUnicode, and that's not what you want

var uri = builder.Uri; // creates new Uri using constructor which does encode and messes cyrillic parameter even more
Console.WriteLine(uri);

// this is still wrong:
var stringUri = builder.ToString(); // returns more 'correct' (still `UrlEncodedUnicode`, but at least once, not twice)
new HttpClient().GetStringAsync(stringUri); // this creates Uri object out of 'stringUri' so we still end up sending double encoded cyrillic text to server. Ouch!

Output:

?cyrillic=%u043a%u0438%u0440%u0438%u043b%u0438%u0446%u044f

https://127.0.0.1/app?cyrillic=%25u043a%25u0438%25u0440%25u0438%25u043b%25u0438%25u0446%25u044f

As you may see, no matter if you do uribuilder.ToString() + httpClient.GetStringAsync(string) or uriBuilder.Uri + httpClient.GetStringAsync(Uri) you end up sending double encoded parameter

Fixed example could be:

var uri = new Uri(builder.ToString(), dontEscape: true);
new HttpClient().GetStringAsync(uri);

But this uses obsolete Uri constructor

P.S on my latest .NET on Windows Server, Uri constructor with bool doc comment says "obsolete, dontEscape is always false", but actually works as expected (skips escaping)

So It looks like another bug...

And even this is plain wrong - it send UrlEncodedUnicode to server, not just UrlEncoded what server expects

Update: one more thing is, NameValueCollection actually does UrlEncodeUnicode, which is not supposed to be used anymore and is incompatible with regular url.encode/decode (see NameValueCollection to URL Query?).

So the bottom line is: never use this hack with NameValueCollection query = HttpUtility.ParseQueryString(builder.Query); as it will mess your unicode query parameters. Just build query manually and assign it to UriBuilder.Query which will do necessary encoding and then get Uri using UriBuilder.Uri.

Prime example of hurting yourself by using code which is not supposed to be used like this

Best Practices for securing a REST API / web service

I would recommend OAuth 2/3. You can find more information at http://oauth.net/2/

Datatable to html Table

public static string toHTML_Table(DataTable dt)
{
    if (dt.Rows.Count == 0) return ""; // enter code here

    StringBuilder builder = new StringBuilder();
    builder.Append("<html>");
    builder.Append("<head>");
    builder.Append("<title>");
    builder.Append("Page-");
    builder.Append(Guid.NewGuid());
    builder.Append("</title>");
    builder.Append("</head>");
    builder.Append("<body>");
    builder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
    builder.Append("style='border: solid 1px Silver; font-size: x-small;'>");
    builder.Append("<tr align='left' valign='top'>");
    foreach (DataColumn c in dt.Columns)
    {
        builder.Append("<td align='left' valign='top'><b>");
        builder.Append(c.ColumnName);
        builder.Append("</b></td>");
    }
    builder.Append("</tr>");
    foreach (DataRow r in dt.Rows)
    {
        builder.Append("<tr align='left' valign='top'>");
        foreach (DataColumn c in dt.Columns)
        {
            builder.Append("<td align='left' valign='top'>");
            builder.Append(r[c.ColumnName]);
            builder.Append("</td>");
        }
        builder.Append("</tr>");
    }
    builder.Append("</table>");
    builder.Append("</body>");
    builder.Append("</html>");

    return builder.ToString();
}

C# - using List<T>.Find() with custom objects

You can use find with a Predicate as follows:

list.Find(x => x.Id == IdToFind);

This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).

Taskkill /f doesn't kill a process

The same problem happened to me in VirtualBox with respect to Java processes.

In my case, it was due to a bug in Windows Update patch KB4338818 (Windows 7 x64).

I solved it by doing the following:

  • Uninstall Windows Update patch KB4338818
  • Install Windows Update patch KB4338821

get basic SQL Server table structure information

Instead of using count(*) you can SELECT * and you will return all of the details that you want including data_type:

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Address'

MSDN Docs on INFORMATION_SCHEMA.COLUMNS

Order by in Inner Join

Add an ORDER BY ONE.ID ASC at the end of your first query.

By default there is no ordering.

How to convert image file data in a byte array to a Bitmap?

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.

How to set viewport meta for iPhone that handles rotation properly?

I have come up with a slighly different approach that should work on cross platforms

http://www.jqui.net/tips-tricks/fixing-the-auto-scale-on-mobile-devices/

So far I have tested in on

Samsun galaxy 2

  • Samsung galaxy s
  • Samsung galaxy s2
  • Samsung galaxy Note (but had to change the css to 800px [see below]*)
  • Motorola
  • iPhone 4

    • @media screen and (max-width:800px) {

This is a massive lip forward with mobile development ...

Overriding !important style

https://jsfiddle.net/xk6Ut/256/

One option to override CSS class in JavaScript is using an ID for the style element so that we can update the CSS class

function writeStyles(styleName, cssText) {
    var styleElement = document.getElementById(styleName);
    if (styleElement) document.getElementsByTagName('head')[0].removeChild(
        styleElement);
    styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.id = styleName;
    styleElement.innerHTML = cssText;
    document.getElementsByTagName('head')[0].appendChild(styleElement);
}

..

   var cssText = '.testDIV{ height:' + height + 'px !important; }';
    writeStyles('styles_js', cssText)

How to add 10 days to current time in Rails

This definitely works and I use this wherever I need to add days to the current date:

Date.today + 5

C#: How would I get the current time into a string?

You can use format strings as well.

string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros

or some shortcuts if the format works for you

string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();

Either should work.

Reload activity in Android

I needed to update a message list in one of my applications in a hurry, so I just performed a refresh of my main UI activity before I closed the dialog I was in. I'm sure there are better ways to accomplish this as well.

// Refresh main activity upon close of dialog box
Intent refresh = new Intent(this, clsMainUIActivity.class);
startActivity(refresh);
this.finish(); //

Compress images on client side before uploading

You might be able to resize the image with canvas and export it using dataURI. Not sure about compression, though.

Take a look at this: Resizing an image in an HTML5 canvas

Append data frames together in a for loop

x <- c(1:10) 

# empty data frame with variables ----

df <- data.frame(x1=character(),
                     y1=character())

for (i in x) {
  a1 <- c(x1 == paste0("The number is ",x[i]),y1 == paste0("This is another number ", x[i]))
  df <- rbind(df,a1)
}

names(df) <- c("st_column","nd_column")
View(df)

that might be a good way to do so....

hibernate - get id after save object

Let's say your primary key is an Integer and the object you save is "ticket", then you can get it like this. When you save the object, a Serializable id is always returned

Integer id = (Integer)session.save(ticket);

How can I save multiple documents concurrently in Mongoose/Node.js?

I know this is an old question, but it worries me that there are no properly correct answers here. Most answers just talk about iterating through all the documents and saving each of them individually, which is a BAD idea if you have more than a few documents, and the process gets repeated for even one in many requests.

MongoDB specifically has a batchInsert() call for inserting multiple documents, and this should be used from the native mongodb driver. Mongoose is built on this driver, and it doesn't have support for batch inserts. It probably makes sense as it is supposed to be a Object document modelling tool for MongoDB.

Solution: Mongoose comes with the native MongoDB driver. You can use that driver by requiring it require('mongoose/node_modules/mongodb') (not too sure about this, but you can always install the mongodb npm again if it doesn't work, but I think it should) and then do a proper batchInsert

How to Automatically Start a Download in PHP?

my code works for txt,doc,docx,pdf,ppt,pptx,jpg,png,zip extensions and I think its better to use the actual MIME types explicitly.

$file_name = "a.txt";

// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);

header('Content-disposition: attachment; filename='.$file_name);

if(strtolower($ext) == "txt")
{
    header('Content-type: text/plain'); // works for txt only
}
else
{
    header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);

shell init issue when click tab, what's wrong with getcwd?

Just change the directory to another one and come back. Probably that one has been deleted or moved.

MySQL parameterized queries

Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. The difference might seem trivial, but in reality it's huge.

Incorrect (with security issues)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))

Correct (with escaping)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses printf style syntax instead of the more commonly accepted '?' marker (used by eg. python-sqlite).

Package structure for a Java project?

You could follow maven's standard project layout. You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since many open source projects are layed out this way,

NuGet Packages are missing

In my case there was missing <RestorePackages>true</RestorePackages> in *.csproj file. It was not necessary to delete snippets of code I see in previous answers.

How to move columns in a MySQL table?

Change column position:

ALTER TABLE Employees 
   CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;

If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:

ALTER TABLE UserOrder 
   CHANGE order_id order_id INT(11) NOT NULL FIRST;

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

This IP, site or mobile application is not authorized to use this API key

Disable both direction api and geocoding api and re-enable.

it works for only 5-10 seconds and than automatically disabled itself.

it means you have only 5-10 sec to test you assignment.

Updating property value in properties file without deleting other values

You can use Apache Commons Configuration library. The best part of this is, it won't even mess up the properties file and keeps it intact (even comments).

Javadoc

PropertiesConfiguration conf = new PropertiesConfiguration("propFile.properties");
conf.setProperty("key", "value");
conf.save();    

Show a number to two decimal places

http://php.net/manual/en/function.round.php

e.g.

echo round(5.045, 2);    // 5.05

echo round(5.055, 2);    // 5.06

How do you connect to multiple MySQL databases on a single webpage?

I just made my life simple:

CREATE VIEW another_table AS SELECT * FROM another_database.another_table;

hope it is helpful... cheers...

How do I REALLY reset the Visual Studio window layout?

Have you tried this? In Visual Studio go to Tools > Import and Export Settings > Reset all settings

Be sure you back up your settings before you do this. I made the mistake of trying this to fix an issue and didn't realize it would undo all my appearance settings and toolbars as well. Took a lot of time to get back to the way I like things.

Absolute positioning ignoring padding of parent

One thing you could try is using the following css:

.child-element {
    padding-left: inherit;
    padding-right: inherit;
    position: absolute;
    left: 0;
    right: 0;
}

It lets the child element inherit the padding from the parent, then the child can be positioned to match the parents widht and padding.

Also, I am using box-sizing: border-box; for the elements involved.

I have not tested this in all browsers, but it seems to be working in Chrome, Firefox and IE10.

PHP How to fix Notice: Undefined variable:

Xampp I guess you're using MySQL.

mysql_fetch_array($result);  

And make sure $result is not empty.

What does git push -u mean?

"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull or git push without arguments. A little bit down, this article explains and demonstrates this concept.

How to share data between different threads In C# using AOP?

When you start a thread you are executing a method of some chosen class. All attributes of that class are visible.

  Worker myWorker = new Worker( /* arguments */ );

  Thread myThread = new Thread(new ThreadStart(myWorker.doWork));

  myThread.Start();

Your thread is now in the doWork() method and can see any atrributes of myWorker, which may themselves be other objects. Now you just need to be careful to deal with the cases of having several threads all hitting those attributes at the same time.

numpy max vs amax vs maximum

You've already stated why np.maximum is different - it returns an array that is the element-wise maximum between two arrays.

As for np.amax and np.max: they both call the same function - np.max is just an alias for np.amax, and they compute the maximum of all elements in an array, or along an axis of an array.

In [1]: import numpy as np

In [2]: np.amax
Out[2]: <function numpy.core.fromnumeric.amax>

In [3]: np.max
Out[3]: <function numpy.core.fromnumeric.amax>

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID