Programs & Examples On #Google maps styled

Full Page <iframe>

For full-screen frame redirects and similar things I have two methods. Both work fine on mobile and desktop.

Note this are complete cross-browser working, valid HTML files. Just change title and src for your needs.

1. this is my favorite:

<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-1 </title>
<meta name=viewport content="width=device-width">
<style>
 html, body, iframe { height:100%; width:100%; margin:0; border:0; display:block }
</style>
<iframe src=src1></iframe>

<!-- More verbose CSS for better understanding:
  html   { height:100% }
  body   { height:100%; margin:0 }
  iframe { height:100%; width:100%; border:0; display:block }
-->

or 2. something like that, slightly shorter:

<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-2 </title>
<meta name=viewport content="width=device-width">
<iframe src=src2 style="position:absolute; top:0; left:0; width:100%; height:100%; border:0">
</iframe>


Note:
The above examples avoid using height:100vh because old browsers don't know it (maybe moot these days) and height:100vh is not always equal to height:100% on mobile browsers (probably not applicable here). Otherwise, vh simplifies things a little bit, so

3. this is an example using vh (not my favorite, less compatible with little advantage)

<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-3 </title>
<meta name=viewport content="width=device-width">
<style>
 body { margin:0 }
 iframe { display:block; width:100%; height:100vh; border:0 }
</style>
<iframe src=src3></iframe>

Adding a month to a date in T SQL

Use DATEADD:

DATEADD(month, 1, reference_dt)

SELECT * WHERE NOT EXISTS

SELECT * FROM employees WHERE name NOT IN (SELECT name FROM eotm_dyn)

OR

SELECT * FROM employees WHERE NOT EXISTS (SELECT * FROM eotm_dyn WHERE eotm_dyn.name = employees.name)

OR

SELECT * FROM employees LEFT OUTER JOIN eotm_dyn ON eotm_dyn.name = employees.name WHERE eotm_dyn IS NULL

git ahead/behind info between master and branch?

Here's a trick I found to compare two branches and show how many commits each branch is ahead of the other (a more general answer on your question 1):

For local branches: git rev-list --left-right --count master...test-branch

For remote branches: git rev-list --left-right --count origin/master...origin/test-branch

This gives output like the following:

1 7

This output means: "Compared to master, test-branch is 7 commits ahead and 1 commit behind."

You can also compare local branches with remote branches, e.g. origin/master...master to find out how many commits the local master branch is ahead/behind its remote counterpart.

Clear screen in shell

For macOS/OS X, you can use the subprocess module and call 'cls' from the shell:

import subprocess as sp
sp.call('cls', shell=True)

To prevent '0' from showing on top of the window, replace the 2nd line with:

tmp = sp.call('cls', shell=True)

For Linux, you must replace cls command with clear

tmp = sp.call('clear', shell=True)

PreparedStatement setNull(..)

Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways

setNull(..)

and

set<ClassName>(.., null)) 

behave the same way.

Convert an NSURL to an NSString

I just fought with this very thing and this update didn't work.

This eventually did in Swift:

let myUrlStr : String = myUrl!.relativePath!

How to get my project path?

You can use

string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

How do you count the elements of an array in java

Java doesn't have the concept of a "count" of the used elements in an array.

To get this, Java uses an ArrayList. The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big).

To get the count, you use mylist.size() to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20). To get rid of the extra capacity, you use mylist.trimToSize().

Multiple submit buttons in the same form calling different Servlets

You may need to write a javascript for each button submit. Instead of defining action in form definition, set those values in javascript. Something like below.

function callButton1(form, yourServ)
{
form.action = yourServ;
form.submit();
});

How to delete columns in numpy.array

From Numpy Documentation

np.delete(arr, obj, axis=None) Return a new array with sub-arrays along an axis deleted.

>>> arr
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

>>> np.delete(arr, np.s_[::2], 1)
array([[ 2,  4],
       [ 6,  8],
       [10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1,  3,  5,  7,  8,  9, 10, 11, 12])

Delegates in swift?

In swift 4.0

Create a delegate on class that need to send some data or provide some functionality to other classes

Like

protocol GetGameStatus {
    var score: score { get }
    func getPlayerDetails()
}

After that in the class that going to confirm to this delegate

class SnakesAndLadders: GetGameStatus {
    func getPlayerDetails() {

 }
}

Make DateTimePicker work as TimePicker only in WinForms

You want to set its 'Format' property to be time and add a spin button control to it:

yourDateTimeControl.Format = DateTimePickerFormat.Time;
yourDateTimeControl.ShowUpDown = true;

SVN undo delete before commit

What worked for me is

svn revert --depth infinity deletedDir

Adding and reading from a Config file

  1. Right click on the project file -> Add -> New Item -> Application Configuration File. This will add an app.config (or web.config) file to your project.

  2. The ConfigurationManager class would be a good start. You can use it to read different configuration values from the configuration file.

I suggest you start reading the MSDN document about Configuration Files.

Command failed due to signal: Segmentation fault: 11

I got this error when I was overriding a property in a subclass and I didn't repeat the property's declaration exactly.

Base class:

var foo: String! {return nil}

Subclass:

override var foo: String {return "bar"} // missing the implicit unwrap operator

Does C have a string type?

To note it in the languages you mentioned:

Java:

String str = new String("Hello");

Python:

str = "Hello"

Both Java and Python have the concept of a "string", C does not have the concept of a "string". C has character arrays which can come in "read only" or manipulatable.

C:

char * str = "Hello";  // the string "Hello\0" is pointed to by the character pointer
                       // str. This "string" can not be modified (read only)

or

char str[] = "Hello";  // the characters: 'H''e''l''l''o''\0' have been copied to the 
                       // array str. You can change them via: str[x] = 't'

A character array is a sequence of contiguous characters with a unique sentinel character at the end (normally a NULL terminator '\0'). Note that the sentinel character is auto-magically appended for you in the cases above.

Generate GUID in MySQL for existing Data?

I faced mostly the same issue. Im my case uuid is stored as BINARY(16) and has NOT NULL UNIQUE constraints. And i faced with the issue when the same UUID was generated for every row, and UNIQUE constraint does not allow this. So this query does not work:

UNHEX(REPLACE(uuid(), '-', ''))

But for me it worked, when i used such a query with nested inner select:

UNHEX(REPLACE((SELECT uuid()), '-', ''))

Then is produced unique result for every entry.

how to return a char array from a function in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
    int n,k=0;
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {
        ch1[k]=ch[i];
        i++;k++;
    }

    return (char *)ch1;
}

int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,s);
    printf("%s",test);
    free(test); //free the test 
    return 0;
}

This will compile fine without any warning

  1. #include stdlib.h
  2. pass test=substring(i,j,s);
  3. remove m as it is unused
  4. either declare char substring(int i,int j,char *ch) or define it before main

How can I put strings in an array, split by new line?

For anyone trying to display cronjobs in a crontab and getting frustrated on how to separate each line, use explode:

$output = shell_exec('crontab -l');
$cron_array = explode(chr(10),$output);

using '\n' doesnt seem to work but chr(10) works nicely :D

hope this saves some one some headaches.

What are the different NameID format used for?

It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:

  1. unspecified
  2. emailAddress – e.g. [email protected]
  3. X509SubjectName – e.g. CN=john,O=Company Ltd.,C=US
  4. WindowsDomainQualifiedName – e.g. CompanyDomain\John
  5. kerberos– e.g. john@realm
  6. entity – this one in used to identify entities that provide SAML-based services and looks like a URI
  7. persistent – this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.
  8. transient – opaque identifier which should be treated as temporary.

How to detect chrome and safari browser (webkit)

jQuery provides that:

if ($.browser.webkit){
    ...
}

Further reading at http://api.jquery.com/jQuery.browser/

Update

As noted in other answers/comments, it's always better to check for feature support than agent info. jQuery also provides an object for that: jQuery.support. Check the documentation to see the detailed list features to check for.

Copying from one text file to another using Python

Safe and memory-saving:

with open("out1.txt", "w") as fw, open("in.txt","r") as fr: 
    fw.writelines(l for l in fr if "tests/file/myword" in l)

It doesn't create temporary lists (what readline and [] would do, which is a non-starter if the file is huge), all is done with generator comprehensions, and using with blocks ensure that the files are closed on exit.

convert an enum to another type of enum

You can use ToString() to convert the first enum to its name, and then Enum.Parse() to convert the string back to the other Enum. This will throw an exception if the value is not supported by the destination enum (i.e. for an "Unknown" value)

Javascript string replace with regex to strip off illegal characters

Put them in brackets []:

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

sql use statement with variable

I have the same problem, I overcame it with an ugly -- but useful -- set of GOTOs.

The reason I call the "script runner" before everything is that I want to hide the complexity and ugly approach from any developer that just wants to work with the actual script. At the same time, I can make sure that the script is run in the two (extensible to three and more) databases in the exact same way.

GOTO ScriptRunner

ScriptExecutes:

--------------------ACTUAL SCRIPT--------------------
-------- Will be executed in DB1 and in DB2 ---------
--TODO: Your script right here

------------------ACTUAL SCRIPT ENDS-----------------

GOTO ScriptReturns

ScriptRunner:
    USE DB1
    GOTO ScriptExecutes

ScriptReturns:
    IF (db_name() = 'DB1')
    BEGIN
        USE DB2
        GOTO ScriptExecutes
    END

With this approach you get to keep your variables and SQL Server does not freak out if you happen to go over a DECLARE statement twice.

How to capitalize the first letter in a String in Ruby

capitalize first letter of first word of string

"kirk douglas".capitalize
#=> "Kirk douglas"

capitalize first letter of each word

In rails:

"kirk douglas".titleize
=> "Kirk Douglas"

OR

"kirk_douglas".titleize
=> "Kirk Douglas"    

In ruby:

"kirk douglas".split(/ |\_|\-/).map(&:capitalize).join(" ") 
#=> "Kirk Douglas"

OR

require 'active_support/core_ext'
"kirk douglas".titleize

Installing python module within code

import os
os.system('pip install requests')

I tried above for temporary solution instead of changing docker file. Hope these might be useful to some

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

Maybe it's too late but i found a solution:

You have to edit in the build.gradle either the compileSdkVersion --> to lastest (now it is 28). Like that:

android {
compileSdkVersion 28
defaultConfig {
    applicationId "NAME_OF_YOUR_PROJECT_DIRECTORY"
    minSdkVersion 21
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

or you can change the version of implementation:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    api 'com.android.support:design:27.+'
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Why can't I do <img src="C:/localfile.jpg">?

we can use javascript's FileReader() and it's readAsDataURL(fileContent) function to show local drive/folder file. Bind change event to image then call javascript's showpreview function. Try this -

<!doctype html>
<html>

<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;'>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
    <title></title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script type="text/javascript">
    function showpreview(e) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $("#previewImage").attr("src", e.target.result);
        }
        //Imagepath.files[0] is blob type
        reader.readAsDataURL(e.files[0]);
    }
    </script>
</head>
<body >
    <div>
    <input type="file" name="fileupload" value="fileupload" id="fileupload" onchange='showpreview(this)'>
    </div>
    <div>
        &nbsp;
    </div>
    <div>
    <img width="50%" id="previewImage">
    </div>
</body>
</html>

Convert to absolute value in Objective-C

You can use this function to get the absolute value:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}

request exceeds the configured maxQueryStringLength when using [Authorize]

In the root web.config for your project, under the system.web node:

<system.web>
    <httpRuntime maxUrlLength="10999" maxQueryStringLength="2097151" />
...

In addition, I had to add this under the system.webServer node or I got a security error for my long query strings:

<system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxUrl="10999" maxQueryString="2097151" />
      </requestFiltering>
    </security>
...

Best way to add Gradle support to IntelliJ Project

There is no need to remove any .iml files. Follow this:

  • close the project
  • File -> Open... and choose your newly created build.gradle
  • IntelliJ will ask you whether you want:
    • Open Existing Project
    • Delete Existing Project and Import
  • Choose the second option and you are done

In the shell, what does " 2>&1 " mean?

0 for input, 1 for stdout and 2 for stderr.

One Tip: somecmd >1.txt 2>&1 is correct, while somecmd 2>&1 >1.txt is totally wrong with no effect!

How to uninstall a Windows Service when there is no executable for it left on the system?

My favourite way of doing this is to use Sysinternals Autoruns application. Just select the service and press delete.

Get java.nio.file.Path object from java.io.File

As many have suggested, JRE v1.7 and above has File.toPath();

File yourFile = ...;
Path yourPath = yourFile.toPath();

On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;

File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());

How can I auto increment the C# assembly version via our CI platform (Hudson)?

Here's what I did, for stamping the AssemblyFileVersion attribute.

Removed the AssemblyFileVersion from AssemblyInfo.cs

Add a new, empty, file called AssemblyFileInfo.cs to the project.

Install the MSBuild community tasks toolset on the hudson build machine or as a NuGet dependency in your project.

Edit the project (csproj) file , it's just an msbuild file, and add the following.

Somewhere there'll be a <PropertyGroup> stating the version. Change that so it reads e.g.

 <Major>1</Major>
 <Minor>0</Minor>
 <!--Hudson sets BUILD_NUMBER and SVN_REVISION -->
 <Build>$(BUILD_NUMBER)</Build>
 <Revision>$(SVN_REVISION)</Revision>

Hudson provides those env variables you see there when the project is built on hudson (assuming it's fetched from subversion).

At the bottom of the project file, add

 <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')" />
  <Target Name="BeforeBuild" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')">
    <Message Text="Version: $(Major).$(Minor).$(Build).$(Revision)" />
    <AssemblyInfo CodeLanguage="CS" OutputFile="AssemblyFileInfo.cs" AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)" AssemblyConfiguration="$(Configuration)" Condition="$(Revision) != '' " />
  </Target>

This uses the MSBuildCommunityTasks to generate the AssemblyFileVersion.cs to include an AssemblyFileVersion attribute before the project is built. You could do this for any/all of the version attributes if you want.

The result is, whenever you issue a hudson build, the resulting assembly gets an AssemblyFileVersion of 1.0.HUDSON_BUILD_NR.SVN_REVISION e.g. 1.0.6.2632 , which means the 6'th build # in hudson, buit from the subversion revision 2632.

Cannot set property 'display' of undefined

document.getElementsByClassName('btn-pageMenu') delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display (if it's the first element from that list you want to change.

If you want to change style.display for all nodes loop through the list:

var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
  elems[i].style.display = 'block';
}

to be complete: if you use jquery it is as simple as:

?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????

design a stack such that getMinimum( ) should be O(1)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Solution 
{
    public class MinStack
    {
        public MinStack()
        {
            MainStack=new Stack<int>();
            Min=new Stack<int>();
        }

        static Stack<int> MainStack;
        static Stack<int> Min;

        public void Push(int item)
        {
            MainStack.Push(item);

            if(Min.Count==0 || item<Min.Peek())
                Min.Push(item);
        }

        public void Pop()
        {
            if(Min.Peek()==MainStack.Peek())
                Min.Pop();
            MainStack.Pop();
        }
        public int Peek()
        {
            return MainStack.Peek();
        }

        public int GetMin()
        {
            if(Min.Count==0)
                throw new System.InvalidOperationException("Stack Empty"); 
            return Min.Peek();
        }
    }
}

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

How to get values and keys from HashMap?

for (Map.Entry<String, Tab> entry : hash.entrySet()) {
    String key = entry.getKey();
    Tab tab = entry.getValue();
    // do something with key and/or tab
}

Works like a charm.

How to detect DataGridView CheckBox event change?

Removing the focus after the cell value changes allow the values to update in the DataGridView. Remove the focus by setting the CurrentCell to null.

private void DataGridView1OnCellValueChanged(object sender, DataGridViewCellEventArgs dataGridViewCellEventArgs)
{
    // Remove focus
    dataGridView1.CurrentCell = null;
    // Put in updates
    Update();
}

private void DataGridView1OnCurrentCellDirtyStateChanged(object sender, EventArgs eventArgs)
{
    if (dataGridView1.IsCurrentCellDirty)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }

}

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

Ok, so you've switched the column from Number to VARCHAR(5). Now you need to update the zipcode field to be left-padded. The SQL to do that would be:

UPDATE MyTable
SET ZipCode = LPAD( ZipCode, 5, '0' );

This will pad all values in the ZipCode column to 5 characters, adding '0's on the left.

Of course, now that you've got all of your old data fixed, you need to make sure that your any new data is also zero-padded. There are several schools of thought on the correct way to do that:

  • Handle it in the application's business logic. Advantages: database-independent solution, doesn't involve learning more about the database. Disadvantages: needs to be handled everywhere that writes to the database, in all applications.

  • Handle it with a stored procedure. Advantages: Stored procedures enforce business rules for all clients. Disadvantages: Stored procedures are more complicated than simple INSERT/UPDATE statements, and not as portable across databases. A bare INSERT/UPDATE can still insert non-zero-padded data.

  • Handle it with a trigger. Advantages: Will work for Stored Procedures and bare INSERT/UPDATE statements. Disadvantages: Least portable solution. Slowest solution. Triggers can be hard to get right.

In this case, I would handle it at the application level (if at all), and not the database level. After all, not all countries use a 5-digit Zipcode (not even the US -- our zipcodes are actually Zip+4+2: nnnnn-nnnn-nn) and some allow letters as well as digits. Better NOT to try and force a data format and to accept the occasional data error, than to prevent someone from entering the correct value, even though it's format isn't quite what you expected.

C convert floating point to int

Use in C

int C = var_in_float;

They will convert implicit

Sending private messages to user

This is pretty simple here is an example

Add your command code here like:

if (cmd === `!dm`) {
 let dUser =
  message.guild.member(message.mentions.users.first()) ||
  message.guild.members.get(args[0]);
 if (!dUser) return message.channel.send("Can't find user!");
 if (!message.member.hasPermission('ADMINISTRATOR'))
  return message.reply("You can't you that command!");
 let dMessage = args.join(' ').slice(22);
 if (dMessage.length < 1) return message.reply('You must supply a message!');

 dUser.send(`${dUser} A moderator from WP Coding Club sent you: ${dMessage}`);

 message.author.send(
  `${message.author} You have sent your message to ${dUser}`
 );
}

Java enum - why use toString instead of name

name() is a "built-in" method of enum. It is final and you cannot change its implementation. It returns the name of enum constant as it is written, e.g. in upper case, without spaces etc.

Compare MOBILE_PHONE_NUMBER and Mobile phone number. Which version is more readable? I believe the second one. This is the difference: name() always returns MOBILE_PHONE_NUMBER, toString() may be overriden to return Mobile phone number.

Multiple arguments to function called by pthread_create()?

struct arg_struct *args = (struct arg_struct *)args;

--> this assignment is wrong, I mean the variable argument should be used in this context. Cheers!!!

Display number always with 2 decimal places in <input>

If you are using Angular 2 (apparently it also works for Angular 4 too), you can use the following to round to two decimal places{{ exampleNumber | number : '1.2-2' }}, as in:

<ion-input value="{{ exampleNumber | number : '1.2-2' }}"></ion-input>

BREAKDOWN

'1.2-2' means {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits

Credit due here and here

CSS text-overflow in a table cell?

Why does this happen?

It seems this section on w3.org suggests that text-overflow applies only to block elements:

11.1.  Overflow Ellipsis: the ‘text-overflow’ property

text-overflow      clip | ellipsis | <string>  
Initial:           clip   
APPLIES TO:        BLOCK CONTAINERS               <<<<
Inherited:         no  
Percentages:       N/A  
Media:             visual  
Computed value:    as specified  

The MDN says the same.

This jsfiddle has your code (with a few debug modifications), which works fine if it's applied to a div instead of a td. It also has the only workaround I could quickly think of, by wrapping the contents of the td in a containing div block. However, that looks like "ugly" markup to me, so I'm hoping someone else has a better solution. The code to test this looks like this:

_x000D_
_x000D_
td, div {_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
  border: 1px solid red;_x000D_
  width: 80px;_x000D_
}
_x000D_
Works, but no tables anymore:_x000D_
<div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div>_x000D_
_x000D_
Works, but non-semantic markup required:_x000D_
<table><tr><td><div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div></td></tr></table>
_x000D_
_x000D_
_x000D_

How to populate a dropdownlist with json data in jquery?

try this one its worked for me

_x000D_
_x000D_
$(document).ready(function(e){_x000D_
        $.ajax({_x000D_
           url:"fetch",_x000D_
           processData: false,_x000D_
           dataType:"json",_x000D_
           type: 'POST',_x000D_
           cache: false,_x000D_
           success: function (data, textStatus, jqXHR) {_x000D_
                        _x000D_
                         $.each(data.Table,function(i,tweet){_x000D_
      $("#list").append('<option value="'+tweet.actor_id+'">'+tweet.first_name+'</option>');_x000D_
   });}_x000D_
        });_x000D_
    });
_x000D_
_x000D_
_x000D_

IndentationError: unexpected indent error

The error is pretty straightforward - the line starting with check_exists_sql isn't indented properly. From the context of your code, I'd indent it and the following lines to match the line before it:

   #open db connection
   db = MySQLdb.connect("localhost","root","str0ng","TESTDB")

   #prepare a cursor object using cursor() method
   cursor = db.cursor()

   #see if any links in the DB match the crawled link
   check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link']

   cursor.execute(check_exists_sql)

And keep indenting it until the for loop ends (all the way through to and including items.append(item).

how to bypass Access-Control-Allow-Origin?

Warning, Chrome (and other browsers) will complain that multiple ACAO headers are set if you follow some of the other answers.

The error will be something like XMLHttpRequest cannot load ____. The 'Access-Control-Allow-Origin' header contains multiple values '____, ____, ____', but only one is allowed. Origin '____' is therefore not allowed access.

Try this:

$http_origin = $_SERVER['HTTP_ORIGIN'];

$allowed_domains = array(
  'http://domain1.com',
  'http://domain2.com',
);

if (in_array($http_origin, $allowed_domains))
{  
    header("Access-Control-Allow-Origin: $http_origin");
}

how to check if a file is a directory or regular file in python?

Many of the Python directory functions are in the os.path module.

import os
os.path.isdir(d)

How to change visibility of layout programmatically

Have a look at View.setVisibility(View.GONE / View.VISIBLE / View.INVISIBLE).

From the API docs:

public void setVisibility(int visibility)

    Since: API Level 1

    Set the enabled state of this view.
    Related XML Attributes: android:visibility

Parameters:
visibility     One of VISIBLE, INVISIBLE, or GONE.

Note that LinearLayout is a ViewGroup which in turn is a View. That is, you may very well call, for instance, myLinearLayout.setVisibility(View.VISIBLE).

This makes sense. If you have any experience with AWT/Swing, you'll recognize it from the relation between Container and Component. (A Container is a Component.)

How to persist a property of type List<String> in JPA?

Here is the solution for storing a Set using @Converter and StringTokenizer. A bit more checks against @jonck-van-der-kogel solution.

In your Entity class:

@Convert(converter = StringSetConverter.class)
@Column
private Set<String> washSaleTickers;

StringSetConverter:

package com.model.domain.converters;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

@Converter
public class StringSetConverter implements AttributeConverter<Set<String>, String> {
    private final String GROUP_DELIMITER = "=IWILLNEVERHAPPEN=";

    @Override
    public String convertToDatabaseColumn(Set<String> stringList) {
        if (stringList == null) {
            return new String();
        }
        return String.join(GROUP_DELIMITER, stringList);
    }

    @Override
    public Set<String> convertToEntityAttribute(String string) {
        Set<String> resultingSet = new HashSet<>();
        StringTokenizer st = new StringTokenizer(string, GROUP_DELIMITER);
        while (st.hasMoreTokens())
            resultingSet.add(st.nextToken());
        return resultingSet;
    }
}

Running Java Program from Command Line Linux

(This is the KISS answer.)

Let's say you have several .java files in the current directory:

$ ls -1 *.java
javaFileName1.java
javaFileName2.java

Let's say each of them have a main() method (so they are programs, not libs), then to compile them do:

javac *.java -d .

This will generate as many subfolders as "packages" the .java files are associated to. In my case all java files where inside under the same package name packageName, so only one folder was generated with that name, so to execute each of them:

java -cp . packageName.javaFileName1
java -cp . packageName.javaFileName2

Invalid attempt to read when no data is present

You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.

Add default value of datetime field in SQL Server to a timestamp

In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP. The datatype of that column may be datetime or datetime2.

e.g.

Create Table Student
(
  Name varchar(50),
  DateOfAddmission datetime default CURRENT_TIMESTAMP
);

Error: Could not find or load main class in intelliJ IDE

Simple solution is go to the backed folder in command line, where the root folder of the project. You should have SBT installed in your machine.

If you have sbt installed, please run the command "sbt package", this will recompile the project if it success, come back to the intelliJ it will work.

Why use 'virtual' for class properties in Entity Framework model definitions?

In the context of EF, marking a property as virtual allows EF to use lazy loading to load it. For lazy loading to work EF has to create a proxy object that overrides your virtual properties with an implementation that loads the referenced entity when it is first accessed. If you don't mark the property as virtual then lazy loading won't work with it.

List files recursively in Linux CLI with path relative to the current directory

Use find:

find . -name \*.txt -print

On systems that use GNU find, like most GNU/Linux distributions, you can leave out the -print.

String variable interpolation Java

Just to add that there is also java.text.MessageFormat with the benefit of having numeric argument indexes.

Appending the 1st example from the documentation

int planet = 7;
String event = "a disturbance in the Force";

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
    planet, new Date(), event);

Result:

At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Selecting Values from Oracle Table Variable / Array?

The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)

Very basic sample:

declare
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
  pidms TPidmList;
begin
  select distinct sgbstdn_pidm
  bulk collect into pidms
  from sgbstdn
  where sgbstdn_majr_code_1 = 'HS04'
  and sgbstdn_program_1 = 'HSCOMPH';

  -- do something with pidms

  open :someCursor for
    select value(t) pidm
    from table(pidms) t;
end;

When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.

e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)

However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.

create package Abc as
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList;

  function Test1(list in TPidmList) return PLS_Integer;
  -- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
  procedure Test2(list in TPidmList);
end;

create package body Abc as

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList is
    result TPidmList;
  begin
    select distinct sgbstdn_pidm
    bulk collect into result
    from sgbstdn
    where sgbstdn_majr_code_1 = majorCode
    and sgbstdn_program_1 = program;

    return result;
  end;

  function Test1(list in TPidmList) return PLS_Integer is
    result PLS_Integer := 0;
  begin
    if list is null or list.Count = 0 then
      return result;
    end if;

    for i in list.First .. list.Last loop
      if ... then
        result := result + list(i);
      end if;
    end loop;
  end;

  procedure Test2(list in TPidmList) as
  begin
    ...
  end;

  return result;
end;

How to call it:

declare
  pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
  xyz PLS_Integer;
begin
  Abc.Test2(pidms);
  xyz := Abc.Test1(pidms);
  ...

  open :someCursor for
    select value(t) as Pidm,
           xyz as SomeValue
    from   table(pidms) t;
end;

Store text file content line by line into array

The simplest solution:

List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]); 

Note that java.nio.file.Files is since 1.7

jQuery equivalent to Prototype array.last()

url : www.mydomain.com/user1/1234

$.params = window.location.href.split("/"); $.params[$.params.length-1];

You can split based on your query string separator

How to subtract X days from a date using Java calendar?

Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.

FYI in Joda Time you could do

DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);

How can I strip first X characters from string using sed?

This will do the job too:

echo "$pid"|awk '{print $2}'

Shortcut for creating single item list in C#

Simply use this:

List<string> list = new List<string>() { "single value" };

You can even omit the () braces:

List<string> list = new List<string> { "single value" };

Update: of course this also works for more than one entry:

List<string> list = new List<string> { "value1", "value2", ... };

RegEx: Grabbing values between quotation marks

This version

  • accounts for escaped quotes
  • controls backtracking

    /(["'])((?:(?!\1)[^\\]|(?:\\\\)*\\[^\\])*)\1/
    

Verifying a specific parameter with Moq

If the verification logic is non-trivial, it will be messy to write a large lambda method (as your example shows). You could put all the test statements in a separate method, but I don't like to do this because it disrupts the flow of reading the test code.

Another option is to use a callback on the Setup call to store the value that was passed into the mocked method, and then write standard Assert methods to validate it. For example:

// Arrange
MyObject saveObject;
mock.Setup(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()))
        .Callback<int, MyObject>((i, obj) => saveObject = obj)
        .Returns("xyzzy");

// Act
// ...

// Assert
// Verify Method was called once only
mock.Verify(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()), Times.Once());
// Assert about saveObject
Assert.That(saveObject.TheProperty, Is.EqualTo(2));

Powershell: convert string to number

Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).

Give this method a try:

[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)

$intNum

'App not Installed' Error on Android

My problem was: I used the Debug Apk, that was generated while I did the Run command from Android Studio

Solution was: Instead of using this file, clean project and click Build > Build APK(s) from Android Studio. Then you can use the generated APK from the usual folder (app/build/outputs/apk/debug/)

The file that was generated like this installed without a problem.

What does the following Oracle error mean: invalid column index

the final sql statement is something like:

select col_1 from table_X where col_2 = 'abcd';

i run this inside my SQL IDE and everything is ok.

Next, i try to build this statement with java:

String queryString= "select col_1 from table_X where col_2 = '?';";
PreparedStatement stmt = con.prepareStatement(queryString);
stmt.setString(1, "abcd"); //raises java.sql.SQLException: Invalid column index

Although the sql statement (the first one, ran against the database) contains quotes around string values, and also finishes with a semicolumn, the string that i pass to the PreparedStatement should not contain quotes around the wildcard character ?, nor should it finish with semicolumn.

i just removed the characters that appear on white background

"select col_1 from table_X where col_2 = ' ? ' ; ";

to obtain

"select col_1 from table_X where col_2 = ?";

(i found the solution here: https://coderanch.com/t/424689/databases/java-sql-SQLException-Invalid-column)

iOS 8 UITableView separator inset 0 not working

I made it work by doing this:

tableView.separatorInset = UIEdgeInsetsZero;
tableView.layoutMargins = UIEdgeInsetsZero;
cell.layoutMargins = UIEdgeInsetsZero;

How to easily get network path to the file you are working on?

Easiest way to find address path in Excel 2010:

File - info - properties (on right) - (drop-down menu) - advanced properties - general tab

You will get to the same properties box that was so simple to find in Excel 2003.

How to detect a USB drive has been plugged in?

Here is a code that works for me, which is a part from the website above combined with my early trials: http://www.codeproject.com/KB/system/DriveDetector.aspx

This basically makes your form listen to windows messages, filters for usb drives and (cd-dvds), grabs the lparam structure of the message and extracts the drive letter.

protected override void WndProc(ref Message m)
    {

        if (m.Msg == WM_DEVICECHANGE)
        {
            DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
            if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) &&  (vol.dbcv_devicetype == DBT_DEVTYPVOLUME) )
            {
                MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
            }
            if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
            {
                MessageBox.Show("usb out");
            }
        }
        base.WndProc(ref m);
    }

    [StructLayout(LayoutKind.Sequential)] //Same layout in mem
    public struct DEV_BROADCAST_VOLUME
    {
        public int dbcv_size;
        public int dbcv_devicetype;
        public int dbcv_reserved;
        public int dbcv_unitmask;
    }

    private static char DriveMaskToLetter(int mask)
    {
        char letter;
        string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
        int cnt = 0;
        int pom = mask / 2;
        while (pom != 0)    // while there is any bit set in the mask shift it right        
        {        
            pom = pom / 2;
            cnt++;
        }
        if (cnt < drives.Length)
            letter = drives[cnt];
        else
            letter = '?';
        return letter;
    }

Do not forget to add this:

using System.Runtime.InteropServices;

and the following constants:

    const int WM_DEVICECHANGE = 0x0219; //see msdn site
    const int DBT_DEVICEARRIVAL = 0x8000;
    const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
    const int DBT_DEVTYPVOLUME = 0x00000002;  

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

For your needs, use ConcurrentHashMap. It allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).

Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.

MySQL Cannot Add Foreign Key Constraint

  • Engine should be the same e.g. InnoDB
  • Datatype should be the same, and with same length. e.g. VARCHAR(20)
  • Collation Columns charset should be the same. e.g. utf8
    Watchout: Even if your tables have same Collation, columns still could have different one.
  • Unique - Foreign key should refer to field that is unique (usually primary key) in the reference table.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Image encryption/decryption using AES256 symmetric block ciphers

Warning: This answer contains code you should not use as it is insecure (using SHA1PRNG for key derivation and using AES in ECB mode)

Instead (as of 2016), use PBKDF2WithHmacSHA1 for key derivation and AES in CBC or GCM mode (GCM provides both privacy and integrity)

You could use functions like these:

private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(clear);
    return encrypted;
}

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    return decrypted;
}

And invoke them like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object   
byte[] b = baos.toByteArray();  

byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();    

// encrypt
byte[] encryptedData = encrypt(key,b);
// decrypt
byte[] decryptedData = decrypt(key,encryptedData);

This should work, I use similar code in a project right now.

Split string into strings by length?

The string splitting is required in many cases like where you have to sort the characters of the string given, replacing a character with an another character etc. But all these operations can be performed with the following mentioned string splitting methods.

The string splitting can be done in two ways:

  1. Slicing the given string based on the length of split.

  2. Converting the given string to a list with list(str) function, where characters of the string breakdown to form the the elements of a list. Then do the required operation and join them with 'specified character between the characters of the original string'.join(list) to get a new processed string.

How do you determine the size of a file in C?

I used this set of code to find the file length.

//opens a file with a file descriptor
FILE * i_file;
i_file = fopen(source, "r");

//gets a long from the file descriptor for fstat
long f_d = fileno(i_file);
struct stat buffer;
fstat(f_d, &buffer);

//stores file size
long file_length = buffer.st_size;
fclose(i_file);

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

HTML/Javascript Button Click Counter

Don't use the word "click" as the function name. It's a reserved keyword in JavaScript. In the bellow code I’ve used "hello" function instead of "click"

<html>
<head>
    <title>Space Clicker</title>
</head>

<body>
    <script type="text/javascript">

    var clicks = 0;
    function hello() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
    };
    </script>
    <button type="button" onclick="hello()">Click me</button>
    <p>Clicks: <a id="clicks">0</a></p>

</body></html>

Git merge error "commit is not possible because you have unmerged files"

So from the error above. All you have to do to fix this issue is to revert your code. (git revert HEAD) then git pull and then redo your changes, then git pull again and was able to commit or merge with no errors.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I was experiencing the same issue in IE11. None of these answers solved my issue. After digging a bit, I noticed that the browser was running in Enterprise mode. (verify by hitting F12 and click the emulation tab, look for browser profile dropdown) The setting was locked, not allowing me to change the setting.

I was able to change the profile to Desktop after deleting CurrentVersion from the following registry key:

HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer\Main\EnterpriseMode

After changing the mode to Desktop the answers on this post will work.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

For me the problem was with my targets tests. I already had the $(inherited) flag in my main app target.

I added it to MyAppTests Other Linker flags. After that when I ran pod install the warning message was gone. enter image description here

Py_Initialize fails - unable to load the file system codec

In my cases, for windows, if you have multiple python versions installed, if PYTHONPATH is pointing to one version the other ones didn't work. I found that if you just remove PYTHONPATH, they all work fine

How to permanently remove few commits from remote branch

Just note to use the last_working_commit_id, when reverting a non-working commit

git reset --hard <last_working_commit_id>

So we must not reset to the commit_id that we don't want.

Then sure, we must push to remote branch:

git push --force

Using multiple .cpp files in c++ program?

You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.

// main.cpp
#include "second.h"
int main () {
    secondFunction();
}

// second.h
void secondFunction();

// second.cpp
#include "second.h"
void secondFunction() {
   // do stuff
}

Jquery mouseenter() vs mouseover()

Though they operate the same way, however, the mouseenter event only triggers when the mouse pointer enters the selected element. The mouseover event is triggered if a mouse pointer enters any child elements as well.

What is the difference between hg forget and hg remove?

If you use "hg remove b" against a file with "A" status, which means it has been added but not commited, Mercurial will respond:

  not removing b: file has been marked for add (use forget to undo)

This response is a very clear explication of the difference between remove and forget.

My understanding is that "hg forget" is for undoing an added but not committed file so that it is not tracked by version control; while "hg remove" is for taking out a committed file from version control.

This thread has a example for using hg remove against files of 7 different types of status.

How to increase apache timeout directive in .htaccess?

Just in case this helps anyone else:

If you're going to be adding the TimeOut directive, and your website uses multiple vhosts (eg. one for port 80, one for port 443), then don't forget to add the directive to all of them!

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I got the same error message for two separate reasons, so you can add them to your debugging checklist:

Context: Xcode 6.4, iOS:8.4. I was adding a toolbar with custom UIBarButtons to load with the UIKeyboardTypeNumberPad (Swift: UIKeyboardType.numberPad) , namely "Done" and "+/-". I had this problem when:

  1. My UIToolbar was declared as a property, but I had forgotten to explicitly alloc/init it.

  2. I had left off the last line, [myCustomToolbar sizeToFit];, which sounds like it's the same family as Holden's answer (my code here: https://stackoverflow.com/a/32016397/4898050).

Good luck

IF a == true OR b == true statement

check this Twig Reference.

You can do it that simple:

{% if (a or b) %}
    ...
{% endif %}

SQL Server: Query fast, but slow from procedure

I found the problem, here's the script of the slow and fast versions of the stored procedure:

dbo.ViewOpener__RenamedForCruachan__Slow.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
    @SessionGUID uniqueidentifier
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

dbo.ViewOpener__RenamedForCruachan__Fast.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
    @SessionGUID uniqueidentifier 
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:

Slow: SET ANSI_NULLS OFF

Fast: SET ANSI_NULLS ON


This answer also could be made to make sense, since the view does have a join clause that says:

(table.column IS NOT NULL)

So there is some NULLs involved.


The explanation is further proved by returning to Query Analizer, and running

SET ANSI_NULLS OFF

.

DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'

.

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank

And the query is slow.


So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off, rather than ANSI_NULLS on, which is QA's default.

Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS option in the stored procedure dialog:

Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

How to move git repository with all branches from bitbucket to github?

Here are the steps to move a private Git repository:

Step 1: Create Github repository

First, create a new private repository on Github.com. It’s important to keep the repository empty, e.g. don’t check option Initialize this repository with a README when creating the repository.

Step 2: Move existing content

Next, we need to fill the Github repository with the content from our Bitbucket repository:

  1. Check out the existing repository from Bitbucket:
    $ git clone https://[email protected]/USER/PROJECT.git
  1. Add the new Github repository as upstream remote of the repository checked out from Bitbucket:
    $ cd PROJECT
    $ git remote add upstream https://github.com:USER/PROJECT.git
  1. Push all branches (below: just master) and tags to the Github repository:
    $ git push upstream master
    $ git push --tags upstream

Step 3: Clean up old repository

Finally, we need to ensure that developers don’t get confused by having two repositories for the same project. Here is how to delete the Bitbucket repository:

  1. Double-check that the Github repository has all content

  2. Go to the web interface of the old Bitbucket repository

  3. Select menu option Setting > Delete repository

  4. Add the URL of the new Github repository as redirect URL

With that, the repository completely settled into its new home at Github. Let all the developers know!

JavaScript checking for null vs. undefined and difference between == and ===

How do I check a variable if it's null or undefined

just check if a variable has a valid value like this :

if(variable)

it will return true if variable does't contain :

  • null
  • undefined
  • 0
  • false
  • "" (an empty string)
  • NaN

Hibernate: How to fix "identifier of an instance altered from X to Y"?

Are you changing the primary key value of a User object somewhere? You shouldn't do that. Check that your mapping for the primary key is correct.

What does your mapping XML file or mapping annotations look like?

Getting the closest string match

A sample using C# is here.

public static void Main()
{
    Console.WriteLine("Hello World " + LevenshteinDistance("Hello","World"));
    Console.WriteLine("Choice A " + LevenshteinDistance("THE BROWN FOX JUMPED OVER THE RED COW","THE RED COW JUMPED OVER THE GREEN CHICKEN"));
    Console.WriteLine("Choice B " + LevenshteinDistance("THE BROWN FOX JUMPED OVER THE RED COW","THE RED COW JUMPED OVER THE RED COW"));
    Console.WriteLine("Choice C " + LevenshteinDistance("THE BROWN FOX JUMPED OVER THE RED COW","THE RED FOX JUMPED OVER THE BROWN COW"));
}

public static float LevenshteinDistance(string a, string b)
{
    var rowLen = a.Length;
    var colLen = b.Length;
    var maxLen = Math.Max(rowLen, colLen);

    // Step 1
    if (rowLen == 0 || colLen == 0)
    {
        return maxLen;
    }

    /// Create the two vectors
    var v0 = new int[rowLen + 1];
    var v1 = new int[rowLen + 1];

    /// Step 2
    /// Initialize the first vector
    for (var i = 1; i <= rowLen; i++)
    {
        v0[i] = i;
    }

    // Step 3
    /// For each column
    for (var j = 1; j <= colLen; j++)
    {
        /// Set the 0'th element to the column number
        v1[0] = j;

        // Step 4
        /// For each row
        for (var i = 1; i <= rowLen; i++)
        {
            // Step 5
            var cost = (a[i - 1] == b[j - 1]) ? 0 : 1;

            // Step 6
            /// Find minimum
            v1[i] = Math.Min(v0[i] + 1, Math.Min(v1[i - 1] + 1, v0[i - 1] + cost));
        }

        /// Swap the vectors
        var vTmp = v0;
        v0 = v1;
        v1 = vTmp;
    }

    // Step 7
    /// The vectors were swapped one last time at the end of the last loop,
    /// that is why the result is now in v0 rather than in v1
    return v0[rowLen];
}

The output is:

Hello World 4
Choice A 15
Choice B 6
Choice C 8

Python: 'break' outside loop

Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.

What are you trying to do? Perhaps you should use sys.exit() or return instead?

Customizing the template within a Directive

Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.

Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.

The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:

    angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        template: function(element, attrs) {
           var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
             return htmlText;
        }
        compile: function(element, attrs)
        {
           //do whatever else is necessary
        }
    }
})

Why do you have to link the math library in C?

Because time() and some other functions are builtin defined in the C library (libc) itself and GCC always links to libc unless you use the -ffreestanding compile option. However math functions live in libm which is not implicitly linked by gcc.

How to return first 5 objects of Array in Swift?

Update for swift 4:

[0,1,2,3,4,5].enumerated().compactMap{ $0 < 10000 ? $1 : nil }

For swift 3:

[0,1,2,3,4,5].enumerated().flatMap{ $0 < 10000 ? $1 : nil }

Animate background image change with jQuery

<style type="text/css">
    #homepage_outter { position:relative; width:100%; height:100%;}
    #homepage_inner { position:absolute; top:0; left:0; z-index:10; width:100%; height:100%;}
    #homepage_underlay { position:absolute; top:0; left:0; z-index:9; width:800px; height:500px; display:none;}
</style>

<script type="text/javascript">
    $(function () {

        $('a').hover(function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/nutrition_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });

        }, function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });


        });

    });

</script>


<body>
<div id="homepage_outter">
    <div id="homepage_inner">
        <a href="#" id="run">run</a>
    </div>
    <div id="homepage_underlay"></div>
</div>

CRON job to run on the last day of the month

What about this?

edit user's .bashprofile adding:

export LAST_DAY_OF_MONTH=$(cal | awk '!/^$/{ print $NF }' | tail -1)

Then add this entry to crontab:

mm hh * * 1-7 [[ $(date +'%d') -eq $LAST_DAY_OF_MONTH ]] && /absolutepath/myscript.sh

Which characters make a URL invalid?

All valid characters that can be used in a URI (a URL is a type of URI) are defined in RFC 3986.

All other characters can be used in a URL provided that they are "URL Encoded" first. This involves changing the invalid character for specific "codes" (usually in the form of the percent symbol (%) followed by a hexadecimal number).

This link, HTML URL Encoding Reference, contains a list of the encodings for invalid characters.

Boto3 to download all files from a S3 Bucket

import boto3, os

s3 = boto3.client('s3')

def download_bucket(bucket):
    paginator = s3.get_paginator('list_objects_v2')
    pages = paginator.paginate(Bucket=bucket)
    for page in pages:
      if 'Contents' in page:
        for obj in page['Contents']:
            os.path.dirname(obj['Key']) and os.makedirs(os.path.dirname(obj['Key']), exist_ok=True) 
            try:
                s3.download_file(bucket, obj['Key'], obj['Key'])
            except NotADirectoryError:
                pass

# Change bucket_name to name of bucket that you want to download
download_bucket(bucket_name)

This should work for all number of objects (also when there are more than 1000). Each paginator page can contain up to 1000 objects.Notice extra param in os.makedirs function - exist_ok=True which cause that it's not throwing error when path exist)

Liquibase lock - reasons?

I appreciate this wasn't the OP's issue, but I ran into this issue recently with a different cause. For reference, I was using the Liquibase Maven plugin (liquibase-maven-plugin:3.1.1) with SQL Server.

Anyway, I'd erroneously copied and pasted a SQL Server "use" statement into one of my scripts that switches databases, so liquibase was running and updating the DATABASECHANGELOGLOCK, acquiring the lock in the correct database, but then switching databases to apply the changes. Not only could I NOT see my changes or liquibase audit in the correct database, but of course, when I ran liquibase again, it couldn't acquire the lock, as the lock had been released in the "wrong" database, and so was still locked in the "correct" database. I'd have expected liquibase to check the lock was still applied before releasing it, and maybe that is a bug in liquibase (I haven't checked yet), but it may well be addressed in later versions! That said, I suppose it could be considered a feature!

Quite a bit of a schoolboy error, I know, but I raise it here in case anyone runs into the same problem!

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

How to get the IP address of the docker host from inside a docker container

So... if you are running your containers using a Rancher server, Rancher v1.6 (not sure if 2.0 has this) containers have access to http://rancher-metadata/ which has a lot of useful information.

From inside the container the IP address can be found here: curl http://rancher-metadata/latest/self/host/agent_ip

For more details see: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-service/

What are the differences between virtual memory and physical memory?

I am shamelessly copying the excerpts from man page of top

VIRT -- Virtual Image (kb) The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.

SWAP -- Swapped size (kb) Memory that is not resident but is present in a task. This is memory that has been swapped out but could include additional non- resident memory. This column is calculated by subtracting physical memory from virtual memory

Count unique values in a column in Excel

My data set is D3:D786, Column headings in D2, function in D1. Formula will ignore blank values.

=SUM(IF(FREQUENCY(IF(SUBTOTAL(3,OFFSET(D3,ROW(D3:D786)-ROW(D3),,1)),IF(D3:D786<>"",MATCH("~"&D3:D786,D3:D786&"",0))),ROW(D3:D786)-ROW(D3)+1),1))

When entering the formula, CTRL + SHIFT + ENTER

I found this at the site below, there's more explanations there about Excel that i didn't understand, if you're into that sort of thing.

http://www.mrexcel.com/forum/excel-questions/553903-count-unique-values-filtered-column.html#post2735467

I copied and pasted my dataset into a different sheet to verify it and it's worked for me.

Process with an ID #### is not running in visual studio professional 2013 update 3

Deleting the hidden .vs folder didn't work for me since the port specified in my app was being used by another app. Doing the following worked for me:

  1. Went to properties and then click the web tab.
  2. Changed the port number in the Start Url and the Project URL.
  3. Clicked Create Virtual Directory.
  4. Save and Press F5.

How to get JSON objects value if its name contains dots?

Just to make use of updated solution try using lodash utility https://lodash.com/docs#get

How to append data to a json file?

this, work for me :

with open('file.json', 'a') as outfile:
    outfile.write(json.dumps(data))
    outfile.write(",")
    outfile.close()

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Bottom Line

Use either COUNT(field) or COUNT(*), and stick with it consistently, and if your database allows COUNT(tableHere) or COUNT(tableHere.*), use that.

In short, don't use COUNT(1) for anything. It's a one-trick pony, which rarely does what you want, and in those rare cases is equivalent to count(*)

Use count(*) for counting

Use * for all your queries that need to count everything, even for joins, use *

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But don't use COUNT(*) for LEFT joins, as that will return 1 even if the subordinate table doesn't match anything from parent table

SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Don't be fooled by those advising that when using * in COUNT, it fetches entire row from your table, saying that * is slow. The * on SELECT COUNT(*) and SELECT * has no bearing to each other, they are entirely different thing, they just share a common token, i.e. *.

An alternate syntax

In fact, if it is not permitted to name a field as same as its table name, RDBMS language designer could give COUNT(tableNameHere) the same semantics as COUNT(*). Example:

For counting rows we could have this:

SELECT COUNT(emp) FROM emp

And they could make it simpler:

SELECT COUNT() FROM emp

And for LEFT JOINs, we could have this:

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But they cannot do that (COUNT(tableNameHere)) since SQL standard permits naming a field with the same name as its table name:

CREATE TABLE fruit -- ORM-friendly name
(
fruit_id int NOT NULL,
fruit varchar(50), /* same name as table name, 
                and let's say, someone forgot to put NOT NULL */
shape varchar(50) NOT NULL,
color varchar(50) NOT NULL
)

Counting with null

And also, it is not a good practice to make a field nullable if its name matches the table name. Say you have values 'Banana', 'Apple', NULL, 'Pears' on fruit field. This will not count all rows, it will only yield 3, not 4

SELECT count(fruit) FROM fruit

Though some RDBMS do that sort of principle (for counting the table's rows, it accepts table name as COUNT's parameter), this will work in Postgresql (if there is no subordinate field in any of the two tables below, i.e. as long as there is no name conflict between field name and table name):

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But that could cause confusion later if we will add a subordinate field in the table, as it will count the field(which could be nullable), not the table rows.

So to be on the safe side, use:

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

count(1): The one-trick pony

In particular to COUNT(1), it is a one-trick pony, it works well only on one table query:

SELECT COUNT(1) FROM tbl

But when you use joins, that trick won't work on multi-table queries without its semantics being confused, and in particular you cannot write:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

So what's the meaning of COUNT(1) here?

SELECT boss.boss_id, COUNT(1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Is it this...?

-- counting all the subordinates only
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Or this...?

-- or is that COUNT(1) will also count 1 for boss regardless if boss has a subordinate
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

By careful thought, you can infer that COUNT(1) is the same as COUNT(*), regardless of type of join. But for LEFT JOINs result, we cannot mold COUNT(1) to work as: COUNT(subordinate.boss_id), COUNT(subordinate.*)

So just use either of the following:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Works on Postgresql, it's clear that you want to count the cardinality of the set

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Another way to count the cardinality of the set, very English-like (just don't make a column with a name same as its table name) : http://www.sqlfiddle.com/#!1/98515/7

select boss.boss_name, count(subordinate)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You cannot do this: http://www.sqlfiddle.com/#!1/98515/8

select boss.boss_name, count(subordinate.1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You can do this, but this produces wrong result: http://www.sqlfiddle.com/#!1/98515/9

select boss.boss_name, count(1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

Use Async/Await with Axios in React.js

Async/Await with axios 

  useEffect(() => {     
    const getData = async () => {  
      await axios.get('your_url')  
      .then(res => {  
        console.log(res)  
      })  
      .catch(err => {  
        console.log(err)  
      });  
    }  
    getData()  
  }, [])

LINQ select one field from list of DTO objects to array

In the case you're interested in extremely minor, almost immeasurable performance increases, add a constructor to your Line class, giving you such:

public class Line
{
    public Line(string sku, int qty)
    {
        this.Sku = sku;
        this.Qty = qty;
    }

    public string Sku { get; set; }
    public int Qty    { get; set; }
}

Then create a specialized collection class based on List<Line> with one new method, Add:

public class LineList : List<Line>
{
    public void Add(string sku, int qty)
    {
        this.Add(new Line(sku, qty));
    }
}

Then the code which populates your list gets a bit less verbose by using a collection initializer:

LineList myLines = new LineList
{
    { "ABCD1", 1 },
    { "ABCD2", 1 },
    { "ABCD3", 1 }
};

And, of course, as the other answers state, it's trivial to extract the SKUs into a string array with LINQ:

string[] mySKUsArray = myLines.Select(myLine => myLine.Sku).ToArray();

Why Choose Struct Over Class?

Here are some other reasons to consider:

  1. structs get an automatic initializer that you don't have to maintain in code at all.

    struct MorphProperty {
       var type : MorphPropertyValueType
       var key : String
       var value : AnyObject
    
       enum MorphPropertyValueType {
           case String, Int, Double
       }
     }
    
     var m = MorphProperty(type: .Int, key: "what", value: "blah")
    

To get this in a class, you would have to add the initializer, and maintain the intializer...

  1. Basic collection types like Array are structs. The more you use them in your own code, the more you will get used to passing by value as opposed to reference. For instance:

    func removeLast(var array:[String]) {
       array.removeLast()
       println(array) // [one, two]
    }
    
    var someArray = ["one", "two", "three"]
    removeLast(someArray)
    println(someArray) // [one, two, three]
    
  2. Apparently immutability vs. mutability is a huge topic, but a lot of smart folks think immutability -- structs in this case -- is preferable. Mutable vs immutable objects

Change the selected value of a drop-down list with jQuery

<asp:DropDownList ID="DropUserType" ClientIDMode="Static" runat="server">
     <asp:ListItem Value="1" Text="aaa"></asp:ListItem>
     <asp:ListItem Value="2" Text="bbb"></asp:ListItem>
</asp:DropDownList>

ClientIDMode="Static"

$('#DropUserType').val('1');

Copy data into another table

INSERT INTO DestinationTable(SupplierName, Country)
SELECT SupplierName, Country FROM SourceTable;

It is not mandatory column names to be same.

Converting milliseconds to minutes and seconds with Javascript

There is probably a better way to do this, but it gets the job done:

var ms = 298999;
var min = ms / 1000 / 60;
var r = min % 1;
var sec = Math.floor(r * 60);
if (sec < 10) {
    sec = '0'+sec;
}
min = Math.floor(min);
console.log(min+':'+sec);

Not sure why you have the << operator in your minutes line, I don't think it's needed just floor the minutes before you display.

Getting the remainder of the minutes with % gives you the percentage of seconds elapsed in that minute, so multiplying it by 60 gives you the amount of seconds and flooring it makes it more fit for display although you could also get sub-second precision if you want.

If seconds are less than 10 you want to display them with a leading zero.

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Having Django serve downloadable files

For a very simple but not efficient or scalable solution, you can just use the built in django serve view. This is excellent for quick prototypes or one-off work, but as has been mentioned throughout this question, you should use something like apache or nginx in production.

from django.views.static import serve
filepath = '/some/path/to/local/file.txt'
return serve(request, os.path.basename(filepath), os.path.dirname(filepath))

React.js: onChange event for contentEditable

This probably isn't exactly the answer you're looking for, but having struggled with this myself and having issues with suggested answers, I decided to make it uncontrolled instead.

When editable prop is false, I use text prop as is, but when it is true, I switch to editing mode in which text has no effect (but at least browser doesn't freak out). During this time onChange are fired by the control. Finally, when I change editable back to false, it fills HTML with whatever was passed in text:

/** @jsx React.DOM */
'use strict';

var React = require('react'),
    escapeTextForBrowser = require('react/lib/escapeTextForBrowser'),
    { PropTypes } = React;

var UncontrolledContentEditable = React.createClass({
  propTypes: {
    component: PropTypes.func,
    onChange: PropTypes.func.isRequired,
    text: PropTypes.string,
    placeholder: PropTypes.string,
    editable: PropTypes.bool
  },

  getDefaultProps() {
    return {
      component: React.DOM.div,
      editable: false
    };
  },

  getInitialState() {
    return {
      initialText: this.props.text
    };
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.editable && !this.props.editable) {
      this.setState({
        initialText: nextProps.text
      });
    }
  },

  componentWillUpdate(nextProps) {
    if (!nextProps.editable && this.props.editable) {
      this.getDOMNode().innerHTML = escapeTextForBrowser(this.state.initialText);
    }
  },

  render() {
    var html = escapeTextForBrowser(this.props.editable ?
      this.state.initialText :
      this.props.text
    );

    return (
      <this.props.component onInput={this.handleChange}
                            onBlur={this.handleChange}
                            contentEditable={this.props.editable}
                            dangerouslySetInnerHTML={{__html: html}} />
    );
  },

  handleChange(e) {
    if (!e.target.textContent.trim().length) {
      e.target.innerHTML = '';
    }

    this.props.onChange(e);
  }
});

module.exports = UncontrolledContentEditable;

Newtonsoft JSON Deserialize

You can implement a class that holds the fields you have in your JSON

class MyData
{
    public string t;
    public bool a;
    public object[] data;
    public string[][] type;
}

and then use the generic version of DeserializeObject:

MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
    // Do something with typeStr
}

Documentation: Serializing and Deserializing JSON

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How to initialize an array in one step using Ruby?

Along with the above answers , you can do this too

    =>  [*'1'.."5"]   #remember *
    => ["1", "2", "3", "4", "5"]

Calling a Sub in VBA

For anyone still coming to this post, the other option is to simply omit the parentheses:

Sub SomeOtherSub(Stattyp As String)
    'Daty and the other variables are defined here

    CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2

End Sub

The Call keywords is only really in VBA for backwards compatibilty and isn't actually required.

If however, you decide to use the Call keyword, then you have to change your syntax to suit.

'// With Call
Call Foo(Bar)

'// Without Call
Foo Bar

Both will do exactly the same thing.


That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call keyword and the parentheses

How to clear the canvas for redrawing

Use: context.clearRect(0, 0, canvas.width, canvas.height);

This is the fastest and most descriptive way to clear the entire canvas.

Do not use: canvas.width = canvas.width;

Resetting canvas.width resets all canvas state (e.g. transformations, lineWidth, strokeStyle, etc.), it is very slow (compared to clearRect), it doesn't work in all browsers, and it doesn't describe what you are actually trying to do.

Dealing with transformed coordinates

If you have modified the transformation matrix (e.g. using scale, rotate, or translate) then context.clearRect(0,0,canvas.width,canvas.height) will likely not clear the entire visible portion of the canvas.

The solution? Reset the transformation matrix prior to clearing the canvas:

// Store the current transformation matrix
context.save();

// Use the identity matrix while clearing the canvas
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);

// Restore the transform
context.restore();

Edit: I've just done some profiling and (in Chrome) it is about 10% faster to clear a 300x150 (default size) canvas without resetting the transform. As the size of your canvas increases this difference drops.

That is already relatively insignificant, but in most cases you will be drawing considerably more than you are clearing and I believe this performance difference be irrelevant.

100000 iterations averaged 10 times:
1885ms to clear
2112ms to reset and clear

Hibernate error - QuerySyntaxException: users is not mapped [from users]

You must type in the same name in your select query as your entity or class(case sensitive) . i.e. select user from className/Entity Name user;

Set JavaScript variable = null, or leave undefined?

Be careful if you use this value to assign some object's property and call JSON.stringify later* - nulls will remain, but undefined properties will be omited, as in example below:

_x000D_
_x000D_
var a, b = null;_x000D_
_x000D_
c = {a, b};_x000D_
_x000D_
console.log(c);_x000D_
console.log(JSON.stringify(c)) // a omited
_x000D_
_x000D_
_x000D_

*or some utility function/library that works in similar way or uses JSON.stringify underneath

How can I disable the UITableView selection?

You can use ....

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

Function ereg_replace() is deprecated - How to clear this bug?

IIRC they suggest using the preg_ functions instead (in this case, preg_replace).

How do I remove a MySQL database?

I needed to correct the privileges.REVOKE ALL PRIVILEGES ONlogs.* FROM 'root'@'root'; GRANT ALL PRIVILEGES ONlogs.* TO 'root'@'root'WITH GRANT OPTION;

To get total number of columns in a table in sql

In MS-SQL Server 7+:

SELECT count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'mytable'

Could not open input file: composer.phar

Question already answered by the OP, but I am posting this answer for anyone having similar problem, retting to

Could not input open file: composer.phar

error message.

Simply go to your project directory/folder and do a

composer update

Assuming this is where you have your web application:

/Library/WebServer/Documents/zendframework

change directory to it, and then run composer update.

Align image to left of text on same line - Twitter Bootstrap3

For Bootstrap 3.

<div class="paragraphs">
  <div class="row">
    <div class="col-md-4">
      <div class="content-heading clearfix media">
           <h3>Experience &nbsp </h3>
           <img class="pull-left" src="../site/img/success32.png"/>
      </div>
      <p>Donec id elit non mi porta gravida at eget metus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
    </div>
  </div>
</div>

How to put a component inside another component in Angular2?

I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent] from decorator.

import {myDirective} from './myDirective';

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

How to sum the values of one column of a dataframe in spark/scala

Simply apply aggregation function, Sum on your column

df.groupby('steps').sum().show()

Follow the Documentation http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html

Check out this link also https://www.analyticsvidhya.com/blog/2016/10/spark-dataframe-and-operations/

Selenium Finding elements by class name in python

You can try to get the list of all elements with class = "content" by using find_elements_by_class_name:

a = driver.find_elements_by_class_name("content")

Then you can click on the link that you are looking for.

Using sendmail from bash script for multiple recipients

Try doing this :

recipients="[email protected],[email protected],[email protected]"

And another approach, using shell here-doc :

/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from

Example Message
EOF

Be sure to separate the headers from the body with a blank line as per RFC 822.

Passing multiple argument through CommandArgument of Button in Asp.net

If you want to pass two values, you can use this approach

<asp:LinkButton ID="RemoveFroRole" Text="Remove From Role" runat="server"
CommandName='<%# Eval("UserName") %>' CommandArgument='<%# Eval("RoleName") %>'
 OnClick="RemoveFromRole_Click" />

Basically I am treating {CommmandName,CommandArgument} as key value. Set both from database field. You will have to use OnClick event and use OnCommand event in this case, which I think is more clean code.

How to pass an array into a SQL Server stored procedure

It took me a long time to figure this out, so in case anyone needs it...

This is based on the SQL 2005 method in Aaron's answer, and using his SplitInts function (I just removed the delim param since I'll always use commas). I'm using SQL 2008 but I wanted something that works with typed datasets (XSD, TableAdapters) and I know string params work with those.

I was trying to get his function to work in a "where in (1,2,3)" type clause, and having no luck the straight-forward way. So I created a temp table first, and then did an inner join instead of the "where in". Here is my example usage, in my case I wanted to get a list of recipes that don't contain certain ingredients:

CREATE PROCEDURE dbo.SOExample1
    (
    @excludeIngredientsString varchar(MAX) = ''
    )
AS
    /* Convert string to table of ints */
    DECLARE @excludeIngredients TABLE (ID int)
    insert into @excludeIngredients
    select ID = Item from dbo.SplitInts(@excludeIngredientsString)

    /* Select recipies that don't contain any ingredients in our excluded table */
   SELECT        r.Name, r.Slug
FROM            Recipes AS r LEFT OUTER JOIN
                         RecipeIngredients as ri inner join
                         @excludeIngredients as ei on ri.IngredientID = ei.ID
                         ON r.ID = ri.RecipeID
WHERE        (ri.RecipeID IS NULL)

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

From what I can see there are helper methods inside the ControllerBase class. Just use the StatusCode method:

[HttpPost]
public IActionResult Post([FromBody] string something)
{    
    //...
    try
    {
        DoSomething();
    }
    catch(Exception e)
    {
         LogException(e);
         return StatusCode(500);
    }
}

You may also use the StatusCode(int statusCode, object value) overload which also negotiates the content.

What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

From the answer here, spark.sql.shuffle.partitions configures the number of partitions that are used when shuffling data for joins or aggregations.

spark.default.parallelism is the default number of partitions in RDDs returned by transformations like join, reduceByKey, and parallelize when not set explicitly by the user. Note that spark.default.parallelism seems to only be working for raw RDD and is ignored when working with dataframes.

If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions) (don't forget to assign it to a new val) in your code.


To change the settings in your code you can simply do:

sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")

Alternatively, you can make the change when submitting the job to a cluster with spark-submit:

./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300

How to sort by Date with DataTables jquery plugin?

Click on the "show details" link under Date (dd/mm/YYY), then you can copy and paste that plugin code provided there


Update: I think you can just switch the order of the array, like so:

jQuery.fn.dataTableExt.oSort['us_date-asc']  = function(a,b) {
    var usDatea = a.split('/');
    var usDateb = b.split('/');

    var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
    var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;

    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
    var usDatea = a.split('/');
    var usDateb = b.split('/');

    var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
    var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;

    return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
};

All I did was switch the __date_[1] (day) and __date_[0] (month), and replaced uk with us so you won't get confused. I think that should take care of it for you.


Update #2: You should be able to just use the date object for comparison. Try this:

jQuery.fn.dataTableExt.oSort['us_date-asc']  = function(a,b) {
 var x = new Date(a),
     y = new Date(b);
 return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
 var x = new Date(a),
     y = new Date(b);
 return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
};

SQL Server converting varbinary to string

Here is a simple example I wrote to convert and convert back using the 2 convert methods, I also checked it with a fixed string

declare @VB1 VARBINARY(500),@VB2 VARBINARY(500),@VB3 VARBINARY(500)

declare @S1 VARCHAR(500)

SET @VB1=HASHBYTES('SHA1','Test')

SET @S1=CONVERT(varchar(500),@VB1,2)

SET @VB2=CONVERT(varbinary(500),@S1,2)

SET @VB3=CONVERT(varbinary(500),'640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA',2)

SELECT @VB1,@S1,@VB2,@VB3

IF @VB1=@VB2 PRINT 'They Match(2)'

IF @VB1=@VB3 PRINT 'They Match(3)'

PRINT str(Len(@VB1))

PRINT str(Len(@S1))

PRINT str(Len(@VB2))

SET @VB1=HASHBYTES('SHA1','Test')

SET @S1=CONVERT(varchar(500),@VB1,1)

SET @VB2=CONVERT(varbinary(500),@S1,1)

SELECT @VB1,@S1,@VB2

IF @VB1=@VB2 PRINT 'They Match(1)'

PRINT str(Len(@VB1))

PRINT str(Len(@S1))

PRINT str(Len(@VB2))

and the output

||| 0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA

(1 row(s) affected)

They Match(2)

They Match(3)

    20
    40
    20

|| 0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA

(1 row(s) affected)

They Match(1)

    20
    42
    20

PuTTY scripting to log onto host

mputty can do that but it does not seem to work always. (if that wait period is too slow)

mputty uses putty and it extends putty. There is an option to run a script. If it does not work, make sure that wait period before typing is a high value or increase that value. See putty sessions , then name of session, right mouse button,properties/script page.

Pip error: Microsoft Visual C++ 14.0 is required

You need to install Microsoft Visual C++ 14.0 to install pycrypto:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.

In the comments you ask about methods of installing pycrypto that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.

I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.

After you have installed Visual C++, just re-run the original command:

pip install -U steem

To find out what the various install options mean, run this command:

pip help install

The help for the -U option says

-U, --upgrade        Upgrade all specified packages to the newest available
                     version. The handling of dependencies depends on the
                     upgrade-strategy used.

If you do not already have the steem library installed, you can run the command without the -U option.

Pipe subprocess standard output to a variable

If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output() command. Here is an example:

output = subprocess.check_output('ls')

To also redirect stderr you can use the following:

output = subprocess.check_output('ls', stderr=subprocess.STDOUT)



In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.

output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)

Creating multiline strings in JavaScript

Also do note that, when extending string over multiple lines using forward backslash at end of each line, any extra characters (mostly spaces, tabs and comments added by mistake) after forward backslash will cause unexpected character error, which i took an hour to find out

var string = "line1\  // comment, space or tabs here raise error
line2";

Copying HTML code in Google Chrome's inspect element

  1. Select the <html> tag in Elements.
  2. Do CTRL-C.
  3. Check if there is only lefting <!DOCTYPE html> before the <html>.

How do I pass options to the Selenium Chrome driver using Python?

This is how I did it.

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-extensions')

chrome = webdriver.Chrome(chrome_options=chrome_options)

How do I move focus to next input with jQuery?

The easiest way is to remove it from the tab index all together:

$('#control').find('input[readonly]').each(function () {
    $(this).attr('tabindex', '-1');
});

I already use this on a couple of forms.

When do we need curly braces around shell variables?

Following SierraX and Peter's suggestion about text manipulation, curly brackets {} are used to pass a variable to a command, for instance:

Let's say you have a sposi.txt file containing the first line of a well-known Italian novel:

> sposi="somewhere/myfolder/sposi.txt"
> cat $sposi

Ouput: quel ramo del lago di como che volge a mezzogiorno

Now create two variables:

# Search the 2nd word found in the file that "sposi" variable points to
> word=$(cat $sposi | cut -d " " -f 2)

# This variable will replace the word
> new_word="filone"

Now substitute the word variable content with the one of new_word, inside sposi.txt file

> sed -i "s/${word}/${new_word}/g" $sposi
> cat $sposi

Ouput: quel filone del lago di como che volge a mezzogiorno

The word "ramo" has been replaced.

How can I remove a commit on GitHub?

Delete the most recent commit, keeping the work you've done:

git reset --soft HEAD~1

Delete the most recent commit, destroying the work you've done:

git reset --hard HEAD~1

Center a H1 tag inside a DIV

You can use display: table-cell in order to render the div as a table cell and then use vertical-align like you would do in a normal table cell.

#AlertDiv {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

You can try it here: http://jsfiddle.net/KaXY5/424/

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

When you encounter exceptions like this, the most useful information is generally at the bottom of the stacktrace:

Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
  at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
  ...
  at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:246)

The problem is that Tomcat can't find com.mysql.jdbc.Driver. This is usually caused by the JAR containing the MySQL driver not being where Tomcat expects to find it (namely in the webapps/<yourwebapp>/WEB-INF/lib directory).

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

On my system (OSX 10.6) that package is at

/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py

I hope that helps you figure out if it's missing or just not on your path.

Error inflating class android.support.v7.widget.Toolbar?

In the case of Xamarin in VS, you must add

Theme = "@style/MyThemesss"

to youractivity.cs.

I add this and go on.

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

ValueError: unsupported format character while forming strings

I was using python interpolation and forgot the ending s character:

a = dict(foo='bar')
print("What comes after foo? %(foo)" % a) # Should be %(foo)s

Watch those typos.

How to send a correct authorization header for basic authentication

NodeJS answer:

In case you wanted to do it with NodeJS: make a GET to JSON endpoint with Authorization header and get a Promise back:

First

npm install --save request request-promise

(see on npm) and then in your .js file:

var requestPromise = require('request-promise');

var user = 'user';
var password = 'password';

var base64encodedData = Buffer.from(user + ':' + password).toString('base64');

requestPromise.get({
  uri: 'https://example.org/whatever',
  headers: {
    'Authorization': 'Basic ' + base64encodedData
  },
  json: true
})
.then(function ok(jsonData) {
  console.dir(jsonData);
})
.catch(function fail(error) {
  // handle error
});

Foreign Key to multiple tables

Yet another option is to have, in Ticket, one column specifying the owning entity type (User or Group), second column with referenced User or Group id and NOT to use Foreign Keys but instead rely on a Trigger to enforce referential integrity.

Two advantages I see here over Nathan's excellent model (above):

  • More immediate clarity and simplicity.
  • Simpler queries to write.

How do I bottom-align grid elements in bootstrap fluid layout

This is an updated solution for Bootstrap 3 (should work for older versions though) that uses CSS/LESS only:

http://jsfiddle.net/silb3r/0srp42pb/11/

You set the font-size to 0 on the row (otherwise you'll end up with a pesky space between columns), then remove the column floats, set display to inline-block, re-set their font-size, and then vertical-align can be set to anything you need.

No jQuery required.

How to sum all column values in multi-dimensional array?

Here's a version where the array keys may not be the same for both arrays, but you want them all to be there in the final array.

function array_add_by_key( $array1, $array2 ) {
    foreach ( $array2 as $k => $a ) {
        if ( array_key_exists( $k, $array1 ) ) {
            $array1[$k] += $a;
        } else {
            $array1[$k] = $a;
        }
    }
    return $array1;
}

How do you post to the wall on a facebook page (not profile)

You can make api calls by choosing the HTTP method and setting optional parameters:

$facebook->api('/me/feed/', 'post', array(
    'message' => 'I want to display this message on my wall'
));

Submit Post to Facebook Wall :

Include the fbConfig.php file to connect Facebook API and get the access token.

Post message, name, link, description, and the picture will be submitted to Facebook wall. Post submission status will be shown.

If FB access token ($accessToken) is not available, the Facebook Login URL will be generated and the user would be redirected to the FB login page.

Post to facebook wall php sdk

<?php
//Include FB config file
require_once 'fbConfig.php';

if(isset($accessToken)){
    if(isset($_SESSION['facebook_access_token'])){
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }else{
        // Put short-lived access token in session
        $_SESSION['facebook_access_token'] = (string) $accessToken;

        // OAuth 2.0 client handler helps to manage access tokens
        $oAuth2Client = $fb->getOAuth2Client();

        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

        // Set default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }

    //FB post content
    $message = 'Test message from CodexWorld.com website';
    $title = 'Post From Website';
    $link = 'http://www.codexworld.com/';
    $description = 'CodexWorld is a programming blog.';
    $picture = 'http://www.codexworld.com/wp-content/uploads/2015/12/www-codexworld-com-programming-blog.png';

    $attachment = array(
        'message' => $message,
        'name' => $title,
        'link' => $link,
        'description' => $description,
        'picture'=>$picture,
    );

    try{
        //Post to Facebook
        $fb->post('/me/feed', $attachment, $accessToken);

        //Display post submission status
        echo 'The post was submitted successfully to Facebook timeline.';
    }catch(FacebookResponseException $e){
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    }catch(FacebookSDKException $e){
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }
}else{
    //Get FB login URL
    $fbLoginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);

    //Redirect to FB login
    header("Location:".$fbLoginURL);
}

Refrences:

https://github.com/facebookarchive/facebook-php-sdk

https://developers.facebook.com/docs/pages/publishing/

https://developers.facebook.com/docs/php/gettingstarted

http://www.pontikis.net/blog/auto_post_on_facebook_with_php

https://www.codexworld.com/post-to-facebook-wall-from-website-php-sdk/

PHP code to get selected text of a combo box

You can achive this with creating new array:

<?php
$array = array(1 => "Toyota", 2 => "Nissan", 3 => "BMW");

if (isset ($_POST['search'])) {
  $maker = mysql_real_escape_string($_POST['Make']);
  echo $array[$maker];
}
?>

Finding an elements XPath using IE Developer tool

If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):

http://westciv.com/mri/

For Xpath:

http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html

Download an SVN repository?

.NET utility for downloading google code project files(SVN). Also has Git support. Requires .Net 2.0

http://downloadsvn.codeplex.com/

Fixed position but relative to container

Check this:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body style="width: 1000px !important;margin-left: auto;margin-right: auto">
        <div style="width: 100px; height: 100px; background-color: #ccc; position:fixed;">
        </div>
        <div id="1" style="width: 100%; height: 600px; background-color: #800000">
        </div>
        <div id="2" style="width: 100%; height: 600px; background-color: #100000">
        </div>
        <div id="3" style="width: 100%; height: 600px; background-color: #400000">
        </div>
    </body>
</html>

Java socket API: How to tell if a connection has been closed?

I faced similar problem. In my case client must send data periodically. I hope you have same requirement. Then I set SO_TIMEOUT socket.setSoTimeout(1000 * 60 * 5); which is throw java.net.SocketTimeoutException when specified time is expired. Then I can detect dead client easily.

How to indent a few lines in Markdown markup?

Another alternative is to use a markdown editor like StackEdit. It converts html (or text) into markdown in a WYSIWYG editor. You can create indents, titles, lists in the editor, and it will show you the corresponding text in markdown format. You can then save, publish, share, or download the file. You can access it on their website - no downloads required!

Measure string size in Bytes in php

PHP's strlen() function returns the number of ASCII characters.

strlen('borsc') -> 5 (bytes)

strlen('boršc') -> 7 (bytes)

$limit_in_kBytes = 20000;

$pointer = 0;
while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){
    $str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
    // here you can handle (0 - n) parts of string
    $pointer++;
}

$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
// here you can handle last part of string

.. or you can use a function like this:

function parseStrToArr($string, $limit_in_kBytes){
    $ret = array();

    $pointer = 0;
    while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){
        $ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
        $pointer++;
    }

    $ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);

    return $ret;
}

$arr = parseStrToArr($your_string, $limit_in_kBytes = 20000);

SQL Server ON DELETE Trigger

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    DELETE FROM database2.dbo.table2
    WHERE bar = 4 AND ID IN(SELECT deleted.id FROM deleted)
GO

jquery $.each() for objects

You are indeed passing the first data item to the each function.

Pass data.programs to the each function instead. Change the code to as below:

<script>     
    $(document).ready(function() {         
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };         
        $.each(data.programs, function(key,val) {             
            alert(key+val);         
        });     
    }); 
</script> 

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

Try reopening VS code or Atom with more specific directory where your app.js is present. I had a lot of folders opened and this problem occured. But once I opened my specific folder and tried once again, it worked.

How to bring a window to the front?

The rules governing what happens when you .toFront() a JFrame are the same in windows and in linux :

-> if a window of the existing application is currently the focused window, then focus swaps to the requested window -> if not, the window merely flashes in the taskbar

BUT :

-> new windows automatically get focus

So let's exploit this ! You want to bring a window to the front, how to do it ? Well :

  1. Create an empty non-purpose window
  2. Show it
  3. Wait for it to show up on screen (setVisible does that)
  4. When shown, request focus for the window you actually want to bring the focus to
  5. hide the empty window, destroy it

Or, in java code :

// unminimize if necessary
this.setExtendedState(this.getExtendedState() & ~JFrame.ICONIFIED);

// don't blame me, blame my upbringing
// or better yet, blame java !
final JFrame newFrame = new JFrame();
newFrame.add(new JLabel("boembabies, is this in front ?"));

newFrame.pack();
newFrame.setVisible(true);
newFrame.toFront();

this.toFront();
this.requestFocus();

// I'm not 100% positive invokeLater is necessary, but it seems to be on
// WinXP. I'd be lying if I said I understand why
SwingUtilities.invokeLater(new Runnable() {
  @Override public void run() {
    newFrame.setVisible(false);
  }
});

What does asterisk * mean in Python?

A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.

Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.

def f0(a)
def f1(*a)
def f2(**a)
def f3(*a, **b)
etc...

Convert hex color value ( #ffffff ) to integer value

Answer is really simple guys, in android if you want to convert hex color in to int, just use android Color class, example shown as below

this is for light gray color

Color.parseColor("#a8a8a8");

Thats it and you will get your result.

Environ Function code samples for VBA

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:

set

If you wanted to get the username, you would do:

Environ("username")

If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")

References

Efficiently sorting a numpy array in descending order?

Be careful with dimensions.

Let

x  # initial numpy array
I = np.argsort(x) or I = x.argsort() 
y = np.sort(x)    or y = x.sort()
z  # reverse sorted array

Full Reverse

z = x[I[::-1]]
z = -np.sort(-x)
z = np.flip(y)
  • flip changed in 1.15, previous versions 1.14 required axis. Solution: pip install --upgrade numpy.

First Dimension Reversed

z = y[::-1]
z = np.flipud(y)
z = np.flip(y, axis=0)

Second Dimension Reversed

z = y[::-1, :]
z = np.fliplr(y)
z = np.flip(y, axis=1)

Testing

Testing on a 100×10×10 array 1000 times.

Method       | Time (ms)
-------------+----------
y[::-1]      | 0.126659  # only in first dimension
-np.sort(-x) | 0.133152
np.flip(y)   | 0.121711
x[I[::-1]]   | 4.611778

x.sort()     | 0.024961
x.argsort()  | 0.041830
np.flip(x)   | 0.002026

This is mainly due to reindexing rather than argsort.

# Timing code
import time
import numpy as np


def timeit(fun, xs):
    t = time.time()
    for i in range(len(xs)):  # inline and map gave much worse results for x[-I], 5*t
        fun(xs[i])
    t = time.time() - t
    print(np.round(t,6))

I, N = 1000, (100, 10, 10)
xs = np.random.rand(I,*N)
timeit(lambda x: np.sort(x)[::-1], xs)
timeit(lambda x: -np.sort(-x), xs)
timeit(lambda x: np.flip(x.sort()), xs)
timeit(lambda x: x[x.argsort()[::-1]], xs)
timeit(lambda x: x.sort(), xs)
timeit(lambda x: x.argsort(), xs)
timeit(lambda x: np.flip(x), xs)

Get div to take up 100% body height, minus fixed-height header and footer

This question has been pretty well answered, but I'm taking the liberty of adding a javascript solution. Just give the element that you want to 'expand' the id footerspacerdiv, and this javascript snippet will expand that div until the page takes up the full height of the browser window.

It works based on the observation that, when a page is less than the full height of the browser window, document.body.scrollHeight is equal to document.body.clientHeight. The while loop increases the height of footerspacerdiv until document.body.scrollHeight is greater than document.body.clientHeight. At this point, footerspacerdiv will actually be 1 pixel too tall, and the browser will show a vertical scroll bar. So, the last line of the script reduces the height of footerspacerdiv by one pixel to make the page height exactly the height of the browser window.

By placing footerspacerdiv just above the 'footer' of the page, this script can be used to 'push the footer down' to the bottom of the page, so that on short pages, the footer is flush with the bottom of the browser window.

<script>    
//expand footerspacer div so that footer goes to bottom of page on short pages        
  var objSpacerDiv=document.getElementById('footerspacer');          
  var bresize=0;   

  while(document.body.scrollHeight<=document.body.clientHeight) {
    objSpacerDiv.style.height=(objSpacerDiv.clientHeight+1)+"px";
    bresize=1;
  }             
  if(bresize) { objSpacerDiv.style.height=(objSpacerDiv.clientHeight-1)+"px"; }               
 </script>

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

Jquery checking success of ajax post

using jQuery 1.8 and above, should use the following:

var request = $.ajax({
    type: 'POST',
    url: 'mmm.php',
    data: { abc: "abcdefghijklmnopqrstuvwxyz" } })
    .done(function(data) { alert("success"+data.slice(0, 100)); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

check out the docs as @hitautodestruct stated.

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

Reposting this here for others from the requests issue page:

Requests' does not support doing this before version 1. Subsequent to version 1, you are expected to subclass the HTTPAdapter, like so:

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
import ssl

class MyAdapter(HTTPAdapter):
    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=ssl.PROTOCOL_TLSv1)

When you've done that, you can do this:

import requests
s = requests.Session()
s.mount('https://', MyAdapter())

Any request through that session object will then use TLSv1.

HttpServletRequest to complete URL

Use the following methods on HttpServletRequest object

java.lang.String getRequestURI() -Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.

java.lang.StringBuffer getRequestURL() -Reconstructs the URL the client used to make the request.

java.lang.String getQueryString() -Returns the query string that is contained in the request URL after the path.

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

I encountered another problem that returns the same error.

Single quote issue

I used a json string with single quotes :

{
    'property': 1
}

But json.loads accepts only double quotes for json properties :

{
    "property": 1
}

Final comma issue

json.loads doesn't accept a final comma:

{
  "property": "text", 
  "property2": "text2",
}

Solution: ast to solve single quote and final comma issues

You can use ast (part of standard library for both Python 2 and 3) for this processing. Here is an example :

import ast
# ast.literal_eval() return a dict object, we must use json.dumps to get JSON string
import json

# Single quote to double with ast.literal_eval()
json_data = "{'property': 'text'}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with double quotes
json_data = '{"property": "text"}'
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with final coma
json_data = "{'property': 'text', 'property2': 'text2',}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property2": "text2", "property": "text"}

Using ast will prevent you from single quote and final comma issues by interpet the JSON like Python dictionnary (so you must follow the Python dictionnary syntax). It's a pretty good and safely alternative of eval() function for literal structures.

Python documentation warned us of using large/complex string :

Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.

json.dumps with single quotes

To use json.dumps with single quotes easily you can use this code:

import ast
import json

data = json.dumps(ast.literal_eval(json_data_single_quote))

ast documentation

ast Python 3 doc

ast Python 2 doc

Tool

If you frequently edit JSON, you may use CodeBeautify. It helps you to fix syntax error and minify/beautify JSON.

I hope it helps.

Variable used in lambda expression should be final or effectively final

In your example, you can replace the forEach with lamdba with a simple for loop and modify any variable freely. Or, probably, refactor your code so that you don't need to modify any variables. However, I'll explain for completeness what does the error mean and how to work around it.

Java 8 Language Specification, §15.27.2:

Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.

Basically you cannot modify a local variable (calTz in this case) from within a lambda (or a local/anonymous class). To achieve that in Java, you have to use a mutable object and modify it (via a final variable) from the lambda. One example of a mutable object here would be an array of one element:

private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone calTz) {
    TimeZone[] result = { null };
    try {
        cal.getComponents().getComponents("VTIMEZONE").forEach(component -> {
            ...
            result[0] = ...;
            ...
        }
    } catch (Exception e) {
        log.warn("Unable to determine ical timezone", e);
    }
    return result[0];
}

How to change content on hover

This exact example is present on mozilla developers page:

::after

As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);, and store it in data-descr="ADD" attribute of your HTML tag (which is nice because you can e.g translate it)

CSS content can only be usef with :after and :before pseudo-elements, so you can try to proceed with something like this:

.item a p.new-label span:after{
  position: relative;
  content: 'NEW'
}
.item:hover a p.new-label span:after {
  content: 'ADD';
}

The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.

How to create a timeline with LaTeX?

I have been struggling to find a proper way to create a timeline, which I could finally do with this modification. Usually while creating a timeline the problem was that I could not add a text to explain each date clearly with a longer text. I modified and further utilized @Zoe Gagnon's latex script. Please feel free to see the following:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}
\usepackage{rotating}

\begin{document}
    
\begin{center}
    \begin{tikzpicture}
        % draw horizontal line   
        \draw (-5,0) -- (6,0);
    
    
    % draw vertical lines
    \foreach \x in {-5,-4,-3,-2, -1,0,1,2}
    \draw (\x cm,3pt) -- (\x cm,-3pt);
    
    % draw nodes
    \draw (-5,0) node[below=3pt] {$ 0 $} node[above=3pt] {$  $};
    \draw (-4,0) node[below=3pt] {$ 1 $} node[above=3pt] {$\begin{turn}{45}
            All individuals vote
        \end{turn}$};
    \draw (-3,0) node[below=3pt] {$ 2 $} node[above=3pt] {$\begin{turn}{45} 
        Policy vector decided
        \end{turn}$};
    \draw (-2,0) node[below=3pt] {$ 3 $} node[above=3pt] {$\begin{turn}{45}  Becoming a bureaucrat \end{turn} $};
    \draw (-1,0) node[below=3pt] {$ 4 $} node[above=3pt] {$\begin{turn}{45} Bureaucrats' effort choice \end{turn}$};
    \draw (0,0) node[below=3pt] {$ 5 $} node[above=3pt] {$\begin{turn}{45} Tax evasion decision made \end{turn}$};
    \draw (1,0) node[below=3pt] {$  6$} node[above=3pt] {$\begin{turn}{45} $p(x_{t})$ tax evaders caught \end{turn}$};
    \draw (2,0) node[below=3pt] {$ 7 $} node[above=3pt] {$\begin{turn}{45} $q_{t}$ shirking bureaucrats \end{turn}$};
            \draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$\begin{turn}{45} Public service provided  \end{turn}   $};
\end{tikzpicture}
\end{center} 
\end{document}

Longer texts are not allowed, unfortunately. It will look like this:

visual depiction of the timeline above

Is there a decent wait function in C++?

Well, this is an old post but I will just contribute to the question -- someone may find it useful later:

adding 'cin.get();' function just before the return of the main() seems to always stop the program from exiting before printing the results: see sample code below:

int main(){ string fname, lname;

  //ask user to enter name first and last name
  cout << "Please enter your first name: ";
  cin >> fname;

  cout << "Please enter your last name: ";
  cin >> lname;     
  cout << "\n\n\n\nyour first name is: " << fname << "\nyour last name is: " 
  << lname <<endl;

  //stop program from exiting before printing results on the screen
  cin.get();
  return 0;

}

Add Auto-Increment ID to existing table?

Check for already existing primary key with different column. If yes, drop the primary key using:

ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO

and then write your query as it is.