Programs & Examples On #Mobile webkit

WebKit is an open source web browser engine that powers the pre-installed browsers for Android, iOS, RIM Blackberry, Symbian and WebOS.

CSS submit button weird rendering on iPad/iPhone

Add this code into the css file:

input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}

This will help.

How to flip background image using CSS?

According to w3schools: http://www.w3schools.com/cssref/css3_pr_transform.asp

The transform property is supported in Internet Explorer 10, Firefox, and Opera. Internet Explorer 9 supports an alternative, the -ms-transform property (2D transforms only). Safari and Chrome support an alternative, the -webkit-transform property (3D and 2D transforms). Opera supports 2D transforms only.

This is a 2D transform, so it should work, with the vendor prefixes, on Chrome, Firefox, Opera, Safari, and IE9+.

Other answers used :before to stop it from flipping the inner content. I used this on my footer (to vertically-mirror the image from my header):

HTML:

<footer>
<p><a href="page">Footer Link</a></p>
<p>&copy; 2014 Company</p>
</footer>

CSS:

footer {
background:url(/img/headerbg.png) repeat-x 0 0;

/* flip background vertically */
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

/* undo the vertical flip for all child elements */
footer * {
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

So you end up flipping the element and then re-flipping all its children. Works with nested elements, too.

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

You can make use of ::marker pseudo element. This is useful in situations when you need to have different character entities for each list item.

ul li::marker {
  content: " "; /* Your symbol here */
}

_x000D_
_x000D_
ul li:nth-child(1)::marker {
  content: "\26BD   ";
}

ul li:nth-child(2)::marker {
  content: "\26C5   ";
}

ul li:nth-child(3)::marker {
  content: "\26F3   ";
}

ul li::marker {
  font-size: 20px;
}

ul li {
  margin: 15px 0;
  font-family: sans-serif;
  background: #BADA55;
  color: black;
  padding-bottom: 10px;
  padding-left: 10px;
  padding-top: 5px;
}
_x000D_
<ul>
  <li>France Vs Croatia</li>
  <li>Cloudy with sunshine</li>
  <li>Golf session ahead</li>
</ul>
_x000D_
_x000D_
_x000D_

Is there a real solution to debug cordova apps

The best for me is to attach the Chrome debugger.

To do it, run your app in a emulator or device (using $cordova emulate)

then, open Google Chrome and go to chrome://inspect/

You'll see a list with running apps. Your app should be there. Click on "inspect".

A new window will open with developer tools. There you can click on "console" to check for errors

Index of Currently Selected Row in DataGridView

I modified @JayRiggs' answer, and this works. You need the if because sometimes the SelectedRows may be empty, so the index operation will throw a exception.

if (yourDGV.SelectedRows.Count>0){
    int index = yourDGV.SelectedRows[0].Index;
}

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

Example that works for me on OSX / MacOS (replace name of device)

~/Library/Android/sdk/emulator/emulator @Pixel_2_API_28 -no-snapshot -wipe-data

How to set time to 24 hour format in Calendar

You can set the calendar to use only AM or PM using

calendar.set(Calendar.AM_PM, int);

0 = AM

1 = PM

Hope this helps

Rails: How to list database tables/objects using the Rails console?

Its a start, it can list:

models = Dir.new("#{RAILS_ROOT}/app/models").entries

Looking some more...

window.print() not working in IE

I am also facing this problem.

Problem in IE is newWin.document.write(divToPrint.innerHTML);

when we remove this line print function in IE is working. but again problem still exist about the content of page.

You can open the page using window.open, and write the content in that page. then print function will work in IE.This is alternate solution.

Best luck.

@Pratik

Best way to overlay an ESRI shapefile on google maps?

Just to update these answers, ESRI has included this tool, known as Layer to KML in ArcMap 10.X. Also, a Map to KML tool exists.

Simply import the desired layer (vector or raster) and choose the output location, resolution, etc. Very simple tool.

Is Java a Compiled or an Interpreted programming language ?

The terms "interpreted language" or "compiled language" don't make sense, because any programming language can be interpreted and/or compiled.

As for the existing implementations of Java, most involve a compilation step to bytecode, so they involve compilation. The runtime also can load bytecode dynamically, so some form of a bytecode interpreter is always needed. That interpreter may or may not in turn use compilation to native code internally.

These days partial just-in-time compilation is used for many languages which were once considered "interpreted", for example JavaScript.

Rounding Bigdecimal values with 2 Decimal Places

Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)

Code example:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
    BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(b);
}

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

SQL Server: Importing database from .mdf?

Open SQL Management Studio Express and log in to the server to which you want to attach the database. In the 'Object Explorer' window, right-click on the 'Databases' folder and select 'Attach...' The 'Attach Databases' window will open; inside that window click 'Add...' and then navigate to your .MDF file and click 'OK'. Click 'OK' once more to finish attaching the database and you are done. The database should be available for use. best regards :)

what's the correct way to send a file from REST web service to client?

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

Java, Calculate the number of days between two dates

Java 8 and later: ChronoUnit.between

Use instances of ChronoUnit to calculate amount of time in different units (days,months, seconds).

For Example:

ChronoUnit.DAYS.between(startDate,endDate)

How to ssh connect through python Paramiko with ppk public key

For me I doing this:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

works for me pretty ok

Set an empty DateTime variable

Since DateTime is a value type you cannot assign null to it, but exactly for these cases (absence of a value) Nullable<T> was introduced - use a nullable DateTime instead:

DateTime? myTime = null;

How does delete[] know it's an array?

delete or delete[] would probably both free the memory allocated (memory pointed), but the big difference is that delete on an array won't call the destructor of each element of the array.

Anyway, mixing new/new[] and delete/delete[] is probably UB.

Changing file permission in Python

All the current answers clobber the non-writing permissions: they make the file readable-but-not-executable for everybody. Granted, this is because the initial question asked for 444 permissions -- but we can do better!

Here's a solution that leaves all the individual "read" and "execute" bits untouched. I wrote verbose code to make it easy to understand; you can make it more terse if you like.

import os
import stat

def remove_write_permissions(path):
    """Remove write permissions from this path, while keeping all other permissions intact.

    Params:
        path:  The path whose permissions to alter.
    """
    NO_USER_WRITING = ~stat.S_IWUSR
    NO_GROUP_WRITING = ~stat.S_IWGRP
    NO_OTHER_WRITING = ~stat.S_IWOTH
    NO_WRITING = NO_USER_WRITING & NO_GROUP_WRITING & NO_OTHER_WRITING

    current_permissions = stat.S_IMODE(os.lstat(path).st_mode)
    os.chmod(path, current_permissions & NO_WRITING)

Why does this work?

As John La Rooy pointed out,stat.S_IWUSR basically means "the bitmask for the user's write permissions". We want to set the corresponding permission bit to 0. To do that, we need the exact opposite bitmask (i.e., one with a 0 in that location, and 1's everywhere else). The ~ operator, which flips all the bits, gives us exactly that. If we apply this to any variable via the "bitwise and" operator (&), it will zero out the corresponding bit.

We need to repeat this logic with the "group" and "other" permission bits, too. Here we can save some time by just &'ing them all together (forming the NO_WRITING bit constant).

The last step is to get the current file's permissions, and actually perform the bitwise-and operation.

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Your code was compiled with Java 8.

Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.

Hope this helps...

How do you print in Sublime Text 2

One way to print your code is to push it to an online version control system like Github or Bitbucket. In your browser, navigate to the file and print it.

Doing it this way, you'll get syntax highlighting and version control.

How to customize message box

MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form

Using CMake to generate Visual Studio C++ project files

CMake is actually pretty good for this. The key part was everyone on the Windows side has to remember to run CMake before loading in the solution, and everyone on our Mac side would have to remember to run it before make.

The hardest part was as a Windows developer making sure your structural changes were in the cmakelist.txt file and not in the solution or project files as those changes would probably get lost and even if not lost would not get transferred over to the Mac side who also needed them, and the Mac guys would need to remember not to modify the make file for the same reasons.

It just requires a little thought and patience, but there will be mistakes at first. But if you are using continuous integration on both sides then these will get shook out early, and people will eventually get in the habit.

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

In here:

    if (ValidationUtils.isNullOrEmpty(lastName)) {
        registrationErrors.add(ValidationErrors.LAST_NAME);
    }
    if (!ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do

    if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.

Http Get using Android HttpURLConnection

If you just need a very simple call, you can use URL directly:

import java.net.URL;

    new URL("http://wheredatapp.com").openStream();

Difference between modes a, a+, w, w+, and r+ in built-in open function?

I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would raise an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Instances of the String constructor have a .search() method which accepts a RegExp and returns the index of the first match.

To start the search from a particular position (faking the second parameter of .indexOf()) you can slice off the first i characters:

str.slice(i).search(/re/)

But this will get the index in the shorter string (after the first part was sliced off) so you'll want to then add the length of the chopped off part (i) to the returned index if it wasn't -1. This will give you the index in the original string:

function regexIndexOf(text, re, i) {
    var indexInSuffix = text.slice(i).search(re);
    return indexInSuffix < 0 ? indexInSuffix : indexInSuffix + i;
}

Is there any way to start with a POST request using Selenium?

Short answer: No.

But you might be able to do it with a bit of filthing. If you open up a test page (with GET) then evaluate some JavaScript on that page you should be able to replicate a POST request. See JavaScript post request like a form submit to see how you can replicate a POST request in JavaScript.

Hope this helps.

What is VanillaJS?

Using "VanillaJS" means using plain JavaScript without any additional libraries like jQuery.

People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries.

Here's a funny site that jokingly talks about this: http://vanilla-js.com/

Is this the proper way to do boolean test in SQL?

If u r using SQLite3 beware:

It takes only 't' or 'f'. Not 1 or 0. Not TRUE OR FALSE.

Just learned the hard way.

ORA-28040: No matching authentication protocol exception

I was using eclipse and after trying all the other answers it didn't work for me. In the end, what worked for me was moving the ojdb7.jar to top in the Build Path. This occurs when multiple jars have conflicting same classes.

  1. Select project in Project Explorer
  2. Right click on Project -> Build Path -> Configure Build Path
  3. Go to Order and Export tab and select ojdbc.jar
  4. Click button TOP to move it to top

How to select a specific node with LINQ-to-XML

I'd use something like:

dim customer = (from c in xmldoc...<Customer> 
                where c.<ID>.Value=22 
                select c).SingleOrDefault 

Edit:

missed the c# tag, sorry......the example is in VB.NET

Android: Go back to previous activity

Just this

super.onBackPressed();

Retrieve specific commit from a remote Git repository

You can simply fetch the remote repo with:

git fetch <repo>

where,

  • <repo> can be a remote repo name (e.g. origin) or even a remote repo URL (e.g. https://git.foo.com/myrepo.git)

for example:

git fetch https://git.foo.com/myrepo.git 

after you fetched the repos you may merge the commits that you want (since the question is about retrieve one commit, instead merge you may use cherry-pick to pick just one commit):

git merge <commit>
  • <commit> can be the SHA1 commit

for example:

git cherry-pick 0a071603d87e0b89738599c160583a19a6d95545

or

git merge 0a071603d87e0b89738599c160583a19a6d95545

if is the latest commit that you want to merge, you also may use FETCH_HEAD variable :

git cherry-pick (or merge) FETCH_HEAD

How to remove a newline from a string in Bash

Under , there are some bashisms:

The tr command could be replaced by // bashism:

COMMAND=$'\nREBOOT\r   \n'
echo "|${COMMAND}|"
|
   OOT
|

echo "|${COMMAND//[$'\t\r\n']}|"
|REBOOT   |

echo "|${COMMAND//[$'\t\r\n ']}|"
|REBOOT|

See Parameter Expansion and QUOTING in bash's man page:

man -Pless\ +/\/pattern bash
man -Pless\ +/\\\'string\\\' bash

man -Pless\ +/^\\\ *Parameter\\\ Exp bash
man -Pless\ +/^\\\ *QUOTING bash

Further...

As asked by @AlexJordan, this will suppress all specified characters. So what if $COMMAND do contain spaces...

COMMAND=$'         \n        RE BOOT      \r           \n'
echo "|$COMMAND|"
|
           BOOT      
|

CLEANED=${COMMAND//[$'\t\r\n']}
echo "|$CLEANED|"
|                 RE BOOT                 |

shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}

CLEANED=${CLEANED%%*( )}
echo "|$CLEANED|"
|                 RE BOOT|

CLEANED=${CLEANED##*( )}
echo "|$CLEANED|"
|RE BOOT|

Shortly:

COMMAND=$'         \n        RE BOOT      \r           \n'
CLEANED=${COMMAND//[$'\t\r\n']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"
|RE BOOT|

Note: have extglob option to be enabled (shopt -s extglob) in order to use *(...) syntax.

StringUtils.isBlank() vs String.isEmpty()

The accepted answer from @arshajii is totally correct. However just being more explicit by saying below,

StringUtils.isBlank()

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true  
 StringUtils.isBlank(" ")       = true  
 StringUtils.isBlank("bob")     = false  
 StringUtils.isBlank("  bob  ") = false

StringUtils.isEmpty

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true  
 StringUtils.isEmpty(" ")       = false  
 StringUtils.isEmpty("bob")     = false  
 StringUtils.isEmpty("  bob  ") = false

How do I set up NSZombieEnabled in Xcode 4?

In Xcode > 4.3:

You click on the scheme drop down bar -> edit scheme -> arguments tab and then add NSZombieEnabled in the Environment Variables column and YES in the value column.

Good Luck !!!

PHP float with 2 decimal places: .00

try this

$result = number_format($FloatNumber, 2);

How to write PNG image to string with the PIL?

You can use the BytesIO class to get a wrapper around strings that behaves like a file. The BytesIO object provides the same interface as a file, but saves the contents just in memory:

import io

with io.BytesIO() as output:
    image.save(output, format="GIF")
    contents = output.getvalue()

You have to explicitly specify the output format with the format parameter, otherwise PIL will raise an error when trying to automatically detect it.

If you loaded the image from a file it has a format parameter that contains the original file format, so in this case you can use format=image.format.

In old Python 2 versions before introduction of the io module you would have used the StringIO module instead.

List of strings to one string

My vote is string.Join

No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.

IntelliJ: Working on multiple projects

  • new empty project
  • File -> New -> Module from Existing Sources

Android Canvas: drawing too large bitmap

This solution worked for me.

Add these lines in your Manifest application tag

android:largeHeap="true"
android:hardwareAccelerated="false"

    

Get Client Machine Name in PHP

Try

echo getenv('COMPUTERNAME');

This will return your computername.

How to increase the clickable area of a <a> tag button?

Big thanks to the contributors to the answers here, it pointed me in the right direction.

For the Bootstrap4 users out there, this worked for me. Sets the a link (tap target) to correct size to pass the Lighthouse Site Audit on mobiles.

    <span class="small">
         <a class="d-inline position-relative p-3 m-n3" style="z-index: 1;" href="/AdvancedSearch" title="Advanced Site Search using extra optional filters">Advanced Site Search</a>
    </span>

Convert from List into IEnumerable format

You need to

using System.Linq;

to use IEnumerable options at your List.

Opening a new tab to read a PDF file

On Chrome this has proven to work well for me.

<a href="newsletter_01.pdf" target="_new">Read more</a>

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

How to convert PDF files to images

(Disclaimer I worked on this component at Software Siglo XXI)

You could use Super Pdf2Image Converter to generate a TIFF multi-page file with all the rendered pages from the PDF in high resolution. It's available for both 32 and 64 bit and is very cheap and effective. I'd recommend you to try it.

Just one line of code...

GetImage(outputFileName, firstPage, lastPage, resolution, imageFormat)

Converts specifies pages to image and save them to outputFileName (tiff allows multi-page or creates several files)

You can take a look here: http://softwaresigloxxi.com/SuperPdf2ImageConverter.html

Why can't I declare static methods in an interface?

There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between

public interface Foo {
  public static int bar();
}

and

public interface Foo {
  public static int bar() {
    ...
  }
}

The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition.

Java could allow the latter; and in fact, starting in Java 8, it does!

case in sql stored procedure on SQL Server

CASE isn't used for flow control... for this, you would need to use IF...

But, there's a set-based solution to this problem instead of the procedural approach:

UPDATE tblEmployee
SET 
  InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
  OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
  Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID

Note that the ELSE will preserves the original value if the @NewStatus condition isn't met.

How to add a touch event to a UIView?

In Swift 4.2 and Xcode 10

Use UITapGestureRecognizer for to add touch event

//Add tap gesture to your view
let tap = UITapGestureRecognizer(target: self, action: #selector(handleGesture))
yourView.addGestureRecognizer(tap)

// GestureRecognizer
@objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
//Write your code here
}

If you want to use SharedClass

//This is my shared class
import UIKit

class SharedClass: NSObject {

    static let sharedInstance = SharedClass()

    //Tap gesture function
    func addTapGesture(view: UIView, target: Any, action: Selector) {
        let tap = UITapGestureRecognizer(target: target, action: action)
        view.addGestureRecognizer(tap)
    }
} 

I have 3 views in my ViewController called view1, view2 and view3.

override func viewDidLoad() {
    super.viewDidLoad()
    //Add gestures to your views
    SharedClass.sharedInstance.addTapGesture(view: view1, target: self, action: #selector(handleGesture))
    SharedClass.sharedInstance.addTapGesture(view: view2, target: self, action: #selector(handleGesture))
    SharedClass.sharedInstance.addTapGesture(view: view3, target: self, action: #selector(handleGesture2))

}

// GestureRecognizer
@objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
    print("printed 1&2...")
}
// GestureRecognizer
@objc func handleGesture2(gesture: UITapGestureRecognizer) -> Void {
    print("printed3...")
}

Check synchronously if file/directory exists in Node.js

The documents on fs.stat() says to use fs.access() if you are not going to manipulate the file. It did not give a justification, might be faster or less memeory use?

I use node for linear automation, so I thought I share the function I use to test for file existence.

var fs = require("fs");

function exists(path){
    //Remember file access time will slow your program.
    try{
        fs.accessSync(path);
    } catch (err){
        return false;
    }
    return true;
}

Check if a string is html or not

There is an NPM package is-html that can attempt to solve this https://github.com/sindresorhus/is-html

Configure Log4net to write to multiple files

Yes, just add multiple FileAppenders to your logger. For example:

<log4net>
    <appender name="File1Appender" type="log4net.Appender.FileAppender">
        <file value="log-file-1.txt" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %message%newline" />
        </layout>
    </appender>
    <appender name="File2Appender" type="log4net.Appender.FileAppender">
        <file value="log-file-2.txt" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %message%newline" />
        </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="File1Appender" />
        <appender-ref ref="File2Appender" />
    </root>
</log4net>

Proper use cases for Android UserManager.isUserAGoat()?

In the discipline of speech recognition, users are divided into goats and sheeps.

For instance, here on page 89:

Sheeps are people for whom speech recognition works exceptionally well, and goats are people for whom it works exceptionally poorly. Only the voice recognizer knows what separates them. People can't predict whose voice will be recognized easily and whose won't. The best policy is to design the interface so it can handle all kinds of voices in all kinds of environments

Maybe, it is planned to mark Android users as goats in the future to be able to configure the speech recognition engine for goats' needs. ;-)

How to modify list entries during for loop?

In short, to do modification on the list while iterating the same list.

list[:] = ["Modify the list" for each_element in list "Condition Check"]

example:

list[:] = [list.remove(each_element) for each_element in list if each_element in ["data1", "data2"]]

IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    
    SELECT * FROM table
    WHERE column = ANY(subquery);
    

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);
    

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

Bootstrap: Collapse other sections when one is expanded

Bootstrap 3 example with side by side buttons below the content

_x000D_
_x000D_
.panel-heading {_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.panel-group .panel+.panel {_x000D_
  margin: 0;_x000D_
  border: 0;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
  border: 0 !important;_x000D_
  -webkit-box-shadow: none !important;_x000D_
  box-shadow: none !important;_x000D_
  background-color: transparent !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
_x000D_
<div class="panel-group" id="accordion">_x000D_
    <div class="panel panel-default">_x000D_
        <div id="collapse1" class="panel-collapse collapse in">_x000D_
            <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class="panel panel-default">_x000D_
        <div id="collapse2" class="panel-collapse collapse">_x000D_
            <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class="panel panel-default">_x000D_
        <div id="collapse3" class="panel-collapse collapse">_x000D_
            <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
    <h4 class="panel-title">_x000D_
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>_x000D_
    </h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
    <h4 class="panel-title">_x000D_
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>_x000D_
    </h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
    <h4 class="panel-title">_x000D_
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collaple Group 3</a>_x000D_
    </h4>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Bootstrap 3 example with side by side buttons above the content

_x000D_
_x000D_
.panel-heading {_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.panel-group .panel+.panel {_x000D_
  margin: 0;_x000D_
  border: 0;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
  border: 0 !important;_x000D_
  -webkit-box-shadow: none !important;_x000D_
  box-shadow: none !important;_x000D_
  background-color: transparent !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="panel-heading">_x000D_
    <h4 class="panel-title">_x000D_
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>_x000D_
    </h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
    <h4 class="panel-title">_x000D_
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>_x000D_
    </h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
    <h4 class="panel-title">_x000D_
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collaple Group 3</a>_x000D_
    </h4>_x000D_
</div>_x000D_
<div class="panel-group" id="accordion">_x000D_
    <div class="panel panel-default">_x000D_
        <div id="collapse1" class="panel-collapse collapse in">_x000D_
            <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class="panel panel-default">_x000D_
        <div id="collapse2" class="panel-collapse collapse">_x000D_
            <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class="panel panel-default">_x000D_
        <div id="collapse3" class="panel-collapse collapse">_x000D_
            <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Javascript event handler with parameters

let obj = MyObject();

elem.someEvent( function(){ obj.func(param) } );

//calls the MyObject.func, passing the param.

Is there a 'box-shadow-color' property?

Maybe this is new (I am also pretty crap at css3), but I have a page that uses exactly what you suggest:

-moz-box-shadow: 10px 10px 5px #384e69;
-webkit-box-shadow: 10px 10px 5px #384e69;
box-shadow: 10px 10px 5px #384e69;}

.. and it works fine for me (in Chrome at least).

What is the mouse down selector in CSS?

Pro-tip Note: for some reason, CSS syntax needs the :active snippet after the :hover for the same element in order to be effective

http://www.w3schools.com/cssref/sel_active.asp

SASS - use variables across multiple files

How about writing some color-based class in a global sass file, thus we don't need to care where variables are. Just like the following:

// base.scss 
@import "./_variables.scss";

.background-color{
    background: $bg-color;
}

and then, we can use the background-color class in any file. My point is that I don't need to import variable.scss in any file, just use it.

In AngularJS, what's the difference between ng-pristine and ng-dirty?

Both directives obviously serve the same purpose, and though it seems that the decision of the angular team to include both interfere with the DRY principle and adds to the payload of the page, it still is rather practical to have them both around. It is easier to style your input elements as you have both .ng-pristine and .ng-dirty available for styling in your css files. I guess this was the primary reason for adding both directives.

Sending credentials with cross-domain posts?

Functionality is supposed to be broken in jQuery 1.5.

Since jQuery 1.5.1 you should use xhrFields param.

$.ajaxSetup({
    type: "POST",
    data: {},
    dataType: 'json',
    xhrFields: {
       withCredentials: true
    },
    crossDomain: true
});

Docs: http://api.jquery.com/jQuery.ajax/

Reported bug: http://bugs.jquery.com/ticket/8146

How to compare datetime with only date in SQL Server

According to your query Select * from [User] U where U.DateCreated = '2014-02-07'

SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220 with 2014-02-07 00:00:00.000 for equality). that's why result of comparison is false

Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'.

Remove composer

During the installation you got a message Composer successfully installed to: ... this indicates where Composer was installed. But you might also search for the file composer.phar on your system.

Then simply:

  1. Delete the file composer.phar.
  2. Delete the Cache Folder:
    • Linux: /home/<user>/.composer
    • Windows: C:\Users\<username>\AppData\Roaming\Composer

That's it.

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

How to convert JSON object to an Typescript array?

That's correct, your response is an object with fields:

{
    "page": 1,
    "results": [ ... ]
}

So you in fact want to iterate the results field only:

this.data = res.json()['results'];

... or even easier:

this.data = res.json().results;

How to get data from observable in angular2

Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http it returns observable instead of promise, like you did

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()

.map() is used to convert the observable (received from http request)to any form like .json(), .text() as stated in Angular's official website,

.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

Did you create a new project or did you clone an existing project?

If you cloned an existing project it's very important to run

composer install

That way all the dependencies that are missing will be installed.

But if you create a new project you should run this command to make a new project using composer

composer create-project laravel/laravel name-of-your-project

Only detect click event on pseudo-element

None of these answers are reliable, and mine wont be much more reliable.

Caveats aside, if you do get into the lucky scenario where the element you're trying to have clicked doesn't have padding (such that all of the "inner" space of the element is completely covered by sub-elements), then you can check the target of the click event against the container itself. If it matches, that means you've clicked a :before or :after element.

Obviously this would not be feasible with both types (before and after) however I have implemented it as a hack/speed fix and it is working very well, without a bunch of position checking, which may be inaccurate depending on about a million different factors.

Validate SSL certificates with Python

I was having the same problem but wanted to minimize 3rd party dependencies (because this one-off script was to be executed by many users). My solution was to wrap a curl call and make sure that the exit code was 0. Worked like a charm.

How do you make Git work with IntelliJ?

On unix systems, you can use the following command to determine where git is installed:

whereis git

If you are using MacOS and did a recent update, it is possible you have to agree to the licence terms again. Try typing 'git' in a terminal, and see if you get the following message:

Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.

Why doesn't RecyclerView have onItemClickListener()?

How to put it all together example...

  • onClick() handling
  • Cursor - RecyclerView
  • ViewHolder types

    public class OrderListCursorAdapter extends CursorRecyclerViewAdapter<OrderListCursorAdapter.ViewHolder> {
    
    private static final String TAG = OrderListCursorAdapter.class.getSimpleName();
    private static final int ID_VIEW_HOLDER_ACTUAL = 0;
    private static final int ID_VIEW_HOLDER = 1;
    
    public OrderListCursorAdapter(Context context, Cursor cursor) {
        super(context, cursor);
    }
    
    public static class ViewHolderActual extends ViewHolder {
        private static final String TAG = ViewHolderActual.class.getSimpleName();
        protected IViewHolderClick listener;
        protected Button button;
    
        public ViewHolderActual(View v, IViewHolderClick listener) {
            super(v, listener);
            this.listener = listener;
            button = (Button) v.findViewById(R.id.orderList_item_button);
            button.setOnClickListener(this);
        }
    
        public void initFromData(OrderData data) {
            Log.d(TAG, "><initFromData(data=" + data + ")");
            orderId = data.getId();
            vAddressStart.setText(data.getAddressStart());
            vAddressEnd.setText(data.getAddressEnd());
        }
    
        @Override
        public void onClick(View view) {
            if (view instanceof Button) {
                listener.onButtonClick((Button) view, getPosition(), this);
            } else {
                super.onClick(view);
            }
        }
    
        public interface IViewHolderClick extends ViewHolder.IViewHolderClick {
            public void onButtonClick(Button button, int position, ViewHolder viewHolder);
        }
    }
    
    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private static final String TAG = ViewHolder.class.getSimpleName();
        protected long orderId;
        protected IViewHolderClick listener;
        protected TextView vAddressStart;
        protected TextView vAddressEnd;
        protected TextView vStatus;
    
        public ViewHolder(View v, IViewHolderClick listener) {
            super(v);
            this.listener = listener;
            v.setOnClickListener(this);
    
            vAddressStart = (TextView) v.findViewById(R.id.addressStart);
            vAddressEnd = (TextView) v.findViewById(R.id.addressEnd);
            vStatus = (TextView) v.findViewById(R.id.status);
        }
    
        public void initFromData(OrderData data) {
            Log.d(TAG, "><initFromData(data=" + data + ")");
            orderId = data.getId();
            vAddressStart.setText(data.getAddressStart());
            vAddressEnd.setText(data.getAddressEnd());
        }
    
        public long getOrderId() {
            return orderId;
        }
    
        @Override
        public void onClick(View view) {
            listener.onCardClick(view, getPosition(), this);
        }
    
        public interface IViewHolderClick {
            public void onCardClick(View view, int position, ViewHolder viewHolder);
        }
    }
    
    @Override
    public int getItemViewType(int position) {
        return position == 0 ? ID_VIEW_HOLDER_ACTUAL : ID_VIEW_HOLDER;
    }
    
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.d(TAG, ">>onCreateViewHolder(parent=" + parent + ", viewType=" + viewType + ")");
    
        ViewHolder result;
    
        switch (viewType) {
            case ID_VIEW_HOLDER_ACTUAL: {
                View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout_actual, parent, false);
                result = new ViewHolderActual(itemView, new ViewHolderActual.IViewHolderClick() {
                    @Override
                    public void onCardClick(View view, int position, ViewHolder viewHolder) {
                        Log.d(TAG, "><onCardClick(view=" + view + ", position=" + position + ", viewHolder=" + viewHolder + ")");
                        Intent intent = new Intent(view.getContext(), OrderDetailActivity.class);
                        intent.putExtra(OrderDetailActivity.ARG_ORDER_ID, viewHolder.getOrderId());
                        view.getContext().startActivity(intent);
                    }
    
                    @Override
                    public void onButtonClick(Button button, int position, ViewHolder viewHolder) {
                        Log.d(TAG, "><onButtonClick(button=" + button + ", position=" + position + ", viewHolder=" + viewHolder + ")");
                        Intent intent = new Intent(button.getContext(), OrderMapActivity.class);
                        intent.putExtra(OrderMapActivity.ARG_ORDER_ID, viewHolder.getOrderId());
                        button.getContext().startActivity(intent);
                    }
                });
                break;
            }
            case ID_VIEW_HOLDER:
            default: {
                View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
                result = new ViewHolder(itemView, new ViewHolder.IViewHolderClick() {
                    @Override
                    public void onCardClick(View view, int position, ViewHolder viewHolder) {
                        Log.d(TAG, "><onCardClick(view=" + view + ", position=" + position + ", viewHolder=" + viewHolder + ")");
                        Intent intent = new Intent(view.getContext(), OrderDetailActivity.class);
                        intent.putExtra(OrderDetailActivity.ARG_ORDER_ID, viewHolder.getOrderId());
                        view.getContext().startActivity(intent);
                    }
                });
                break;
            }
        }
    
        Log.d(TAG, "<<onCreateViewHolder(parent=" + parent + ", viewType=" + viewType + ")= " + result);
        return result;
    }
    
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) {
        Log.d(TAG, "><onBindViewHolder(viewHolder=" + viewHolder + ", cursor=" + cursor + ")");
        final OrderData orderData = new OrderData(cursor);
        viewHolder.initFromData(orderData);
    }
    }
    

Why is it not advisable to have the database and web server on the same machine?

  1. Security. Your web server lives in a DMZ, accessible to the public internet and taking untrusted input from anonymous users. If your web server gets compromised, and you've followed least privilege rules in connecting to your DB, the maximum exposure is what your app can do through the database API. If you have a business tier in between, you have one more step between your attacker and your data. If, on the other hand, your database is on the same server, the attacker now has root access to your data and server.
  2. Scalability. Keeping your web server stateless allows you to scale your web servers horizontally pretty much effortlessly. It is very difficult to horizontally scale a database server.
  3. Performance. 2 boxes = 2 times the CPU, 2 times the RAM, and 2 times the spindles for disk access.

All that being said, I can certainly see reasonable cases that none of those points really matter.

Why is @font-face throwing a 404 error on woff files?

Also check your URL rewriter. It may throw 404 if something "weird" was found.

Install apps silently, with granted INSTALL_PACKAGES permission

I tried on rooted Android 4.2.2 and this method works for me:

private void installApk(String filename) {
    File file = new File(filename); 
    if(file.exists()){
        try {   
            final String command = "pm install -r " + file.getAbsolutePath();
            Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
     }
}

How do I give text or an image a transparent background using CSS?

This is the best solution I could come up with, NOT using CSS 3. And it works great on Firefox, Chrome, and Internet Explorer as far as I can see.

Put a container div and two children divs at the same level, one for content, one for the background. And using CSS, auto-size the background to fit the content and put the background actually in the back using z-index.

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
}_x000D_
.content {_x000D_
  position: relative;_x000D_
  color: White;_x000D_
  z-index: 5;_x000D_
}_x000D_
.background {_x000D_
  position: absolute;_x000D_
  top: 0px;_x000D_
  left: 0px;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: Black;_x000D_
  z-index: 1;_x000D_
  /* These three lines are for transparency in all browsers. */_x000D_
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";_x000D_
  filter: alpha(opacity=50);_x000D_
  opacity: .5;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    Here is the content._x000D_
    <br/>Background should grow to fit._x000D_
  </div>_x000D_
  <div class="background"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

m2eclipse not finding maven dependencies, artifacts not found

Okay I fixed this thing. Had to first convert the projects to Maven Projects, then remove them from the Eclipse workspace, and then re-import them.

Get top 1 row of each group

SELECT * FROM
DocumentStatusLogs JOIN (
  SELECT DocumentID, MAX(DateCreated) DateCreated
  FROM DocumentStatusLogs
  GROUP BY DocumentID
  ) max_date USING (DocumentID, DateCreated)

What database server? This code doesn't work on all of them.

Regarding the second half of your question, it seems reasonable to me to include the status as a column. You can leave DocumentStatusLogs as a log, but still store the latest info in the main table.

BTW, if you already have the DateCreated column in the Documents table you can just join DocumentStatusLogs using that (as long as DateCreated is unique in DocumentStatusLogs).

Edit: MsSQL does not support USING, so change it to:

ON DocumentStatusLogs.DocumentID = max_date.DocumentID AND DocumentStatusLogs.DateCreated = max_date.DateCreated

Where are Docker images stored on the host machine?

I use the boot2docker for Docker on Mac OSX, so the images is stored into the /Users/<USERNAME>/VirtualBox VMs/boot2docker-vm/boot2docker-vm.vmdk.

How do I set the value property in AngularJS' ng-options?

If you want to change the value of your option elements because the form will eventually be submitted to the server, instead of doing this,

<select name="text" ng-model="text" ng-options="select p.text for p in resultOptions"></select>

You can do this:

<select ng-model="text" ng-options="select p.text for p in resultOptions"></select>
<input type="hidden" name="text" value="{{ text }}" />

The expected value will then be sent through the form under the correct name.

Comparing two columns, and returning a specific adjacent cell in Excel

In cell D2 and copied down:

=IF(COUNTIF($A$2:$A$5,C2)=0,"",VLOOKUP(C2,$A$2:$B$5,2,FALSE))

Execute a file with arguments in Python shell

import sys
import subprocess

subprocess.call([sys.executable, 'abc.py', 'argument1', 'argument2'])

Do a "git export" (like "svn export")?

As simple as clone then delete the .git folder:

git clone url_of_your_repo path_to_export && rm -rf path_to_export/.git

Full Page <iframe>

Here's the working code. Works in desktop and mobile browsers. hope it helps. thanks for everyone responding.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Test Layout</title>
        <style type="text/css">
            body, html
            {
                margin: 0; padding: 0; height: 100%; overflow: hidden;
            }

            #content
            {
                position:absolute; left: 0; right: 0; bottom: 0; top: 0px; 
            }
        </style>
    </head>
    <body>
        <div id="content">
            <iframe width="100%" height="100%" frameborder="0" src="http://cnn.com" />
        </div>
    </body>
</html>

how to add lines to existing file using python

If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

How to format numbers?

_x000D_
_x000D_
function numberWithCommas(x) {_x000D_
  x=String(x).toString();_x000D_
  var afterPoint = '';_x000D_
  if(x.indexOf('.') > 0)_x000D_
     afterPoint = x.substring(x.indexOf('.'),x.length);_x000D_
  x = Math.floor(x);_x000D_
  x=x.toString();_x000D_
  var lastThree = x.substring(x.length-3);_x000D_
  var otherNumbers = x.substring(0,x.length-3);_x000D_
  if(otherNumbers != '')_x000D_
      lastThree = ',' + lastThree;_x000D_
  return otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;_x000D_
}_x000D_
_x000D_
console.log(numberWithCommas(100000));_x000D_
console.log(numberWithCommas(10000000));
_x000D_
_x000D_
_x000D_

Output

1,00,000
1,00,00,000

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

For completeness, the answer to Asp.Net Core tag in web.config causes failure may also be the solution to the problem here. If the .NET Core Windows Server Hosting bundle is not installed then IIS cannot recognize the aspNetCore section in web.config. https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-3.1#install-the-net-core-hosting-bundle claims to be a direct download to the current version.

How to check radio button is checked using JQuery?

Given a group of radio buttons:

<input type="radio" id="radio1" name="radioGroup" value="1">
<input type="radio" id="radio2" name="radioGroup" value="2">

You can test whether a specific one is checked using jQuery as follows:

if ($("#radio1").prop("checked")) {
   // do something
}

// OR
if ($("#radio1").is(":checked")) {
   // do something
}

// OR if you don't have ids set you can go by group name and value
// (basically you need a selector that lets you specify the particular input)
if ($("input[name='radioGroup'][value='1']").prop("checked"))

You can get the value of the currently checked one in the group as follows:

$("input[name='radioGroup']:checked").val()

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Call Javascript onchange event by programmatically changing textbox value

You can fire the event simply with

document.getElementById("elementID").onchange();

I dont know if this doesnt work on some browsers, but it should work on FF 3 and IE 7+

delete all from table

There is a mySQL bug report from 2004 that still seems to have some validity. It seems that in 4.x, this was fastest:

DROP table_name
CREATE TABLE table_name

TRUNCATE table_name was DELETE FROM internally back then, providing no performance gain.

This seems to have changed, but only in 5.0.3 and younger. From the bug report:

[11 Jan 2005 16:10] Marko Mäkelä

I've now implemented fast TRUNCATE TABLE, which will hopefully be included in MySQL 5.0.3.

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

This is a quirk of the C grammar. A label (Cleanup:) is not allowed to appear immediately before a declaration (such as char *str ...;), only before a statement (printf(...);). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.

You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:

int main (void) 
{
    char *str;
    printf("Hello ");
    goto Cleanup;
Cleanup:
    str = "World\n";
    printf("%s\n", str);
    return 0;
}

Node.js global variables

You can just use the global object.

var X = ['a', 'b', 'c'];
global.x = X;

console.log(x);
//['a', 'b', 'c']

Android canvas draw rectangle

Try paint.setStyle(Paint.Style.STROKE)?

SQL Server procedure declare a list

You could declare a variable as a temporary table like this:

declare @myList table (Id int)

Which means you can use the insert statement to populate it with values:

insert into @myList values (1), (2), (5), (7), (10)

Then your select statement can use either the in statement:

select * from DBTable
where id in (select Id from @myList)

Or you could join to the temporary table like this:

select *
from DBTable d
join @myList t on t.Id = d.Id

And if you do something like this a lot then you could consider defining a user-defined table type so you could then declare your variable like this:

declare @myList dbo.MyTableType

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.

First we create "Parent" object function

function Parent(){

}

Then add a prototype to "Parent" object function

 Parent.prototype = {
 primitive : 1,
 object : {
    one : 1
   }
}

Create "Child" object function

function Child(){

}

Assign child prototype (Make child prototype inherit from parent prototype)

Child.prototype = Object.create(Parent.prototype);

Assign proper "Child" prototype constructor

Child.prototype.constructor = Child;

Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects

Child.prototype.changeProps = function(){
    this.primitive = 2;
    this.object.one = 2;
};

Initiate Parent (dad) and Child (son) objects.

var dad = new Parent();
var son = new Child();

Call Child (son) changeProps method

son.changeProps();

Check the results.

Parent primitive property did not change

console.log(dad.primitive); /* 1 */

Child primitive property changed (rewritten)

console.log(son.primitive); /* 2 */

Parent and Child object.one properties changed

console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */

Working example here http://jsbin.com/xexurukiso/1/edit/

More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create

How to read lines of a file in Ruby

Ruby does have a method for this:

File.readlines('foo').each do |line|

http://ruby-doc.org/core-1.9.3/IO.html#method-c-readlines

How can I format a decimal to always show 2 decimal places?

>>> print "{:.2f}".format(1.123456)
1.12

You can change 2 in 2f to any number of decimal points you want to show.

EDIT:

From Python3.6, this translates to:

>>> print(f"{1.1234:.2f}")
1.12

CSS Selector for <input type="?"

Yes. IE7+ supports attribute selectors:

input[type=radio]
input[type^=ra]
input[type*=d]
input[type$=io]

Element input with attribute type which contains a value that is equal to, begins with, contains or ends with a certain value.

Other safe (IE7+) selectors are:

  • Parent > child that has: p > span { font-weight: bold; }
  • Preceded by ~ element which is: span ~ span { color: blue; }

Which for <p><span/><span/></p> would effectively give you:

<p>
    <span style="font-weight: bold;">
    <span style="font-weight: bold; color: blue;">
</p>

Further reading: Browser CSS compatibility on quirksmode.com

I'm surprised that everyone else thinks it can't be done. CSS attribute selectors have been here for some time already. I guess it's time we clean up our .css files.

How do I clear the std::queue efficiently?

You could create a class that inherits from queue and clear the underlying container directly. This is very efficient.

template<class T>
class queue_clearable : public std::queue<T>
{
public:
    void clear()
    {
        c.clear();
    }
};

Maybe your a implementation also allows your Queue object (here JobQueue) to inherit std::queue<Job> instead of having the queue as a member variable. This way you would have direct access to c.clear() in your member functions.

IndentationError: unindent does not match any outer indentation level

Firstly, just to remind you there is a logical error you better keep result=1 or else your output will be result=0 even after the loop runs.

Secondly you can write it like this:

import sys

def Factorial(n): # Return factorial
  result = 0
  for i in range (1,n):
     result = result * i

  print "factorial is ",result
  return result

Leaving a line will tell the python shell that the FOR statements have ended. If you have experience using the python shell then you can understand why we have to leave a line.

Validation of file extension before uploading file

None of the existing answers seemed quite compact enough for the simplicity of the request. Checking if a given file input field has an extension from a set can be accomplished as follows:

function hasExtension(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName);
}

So example usage might be (where upload is the id of a file input):

if (!hasExtension('upload', ['.jpg', '.gif', '.png'])) {
    // ... block upload
}

Or as a jQuery plugin:

$.fn.hasExtension = function(exts) {
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test($(this).val());
}

Example usage:

if (!$('#upload').hasExtension(['.jpg', '.png', '.gif'])) {
    // ... block upload
}

The .replace(/\./g, '\\.') is there to escape the dot for the regexp so that basic extensions can be passed in without the dots matching any character.

There's no error checking on these to keep them short, presumably if you use them you'll make sure the input exists first and the extensions array is valid!

How to delete duplicates on a MySQL table?

Deleting duplicates on MySQL tables is a common issue, that usually comes with specific needs. In case anyone is interested, here (Remove duplicate rows in MySQL) I explain how to use a temporary table to delete MySQL duplicates in a reliable and fast way, also valid to handle big data sources (with examples for different use cases).

Ali, in your case, you can run something like this:

-- create a new temporary table
CREATE TABLE tmp_table1 LIKE table1;

-- add a unique constraint    
ALTER TABLE tmp_table1 ADD UNIQUE(sid, title);

-- scan over the table to insert entries
INSERT IGNORE INTO tmp_table1 SELECT * FROM table1 ORDER BY sid;

-- rename tables
RENAME TABLE table1 TO backup_table1, tmp_table1 TO table1;

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

Pass array to MySQL stored routine

This helps for me to do IN condition Hope this will help you..

CREATE  PROCEDURE `test`(IN Array_String VARCHAR(100))
BEGIN
    SELECT * FROM Table_Name
    WHERE FIND_IN_SET(field_name_to_search, Array_String);

END//;

Calling:

 call test('3,2,1');

Session state can only be used when enableSessionState is set to true either in a configuration

Following answer from below given path worked fine.

I found a solution that worked perfectly! Add the following to web.config:

<system.webServer>
<modules>
<!-- UrlRewriter code here -->
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="" />
</modules>
</system.webServer>

Hope this helps someone else!

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

pip install pymysql

Then, edit the __init__.py file in your project origin dir(the same as settings.py)

add:

import pymysql

pymysql.install_as_MySQLdb()

What does Maven do, in theory and in practice? When is it worth to use it?

From the Sonatype doc:

The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.

I'd strongly recommend looking at the Sonatype doc and spending some time looking at the available plugins to understand the power of Maven.

Very briefly, it operates at a higher conceptual level than (say) Ant. With Ant, you'd specify the set of files and resources that you want to build, then specify how you want them jarred together, and specify the order that should occur in (clean/compile/jar). With Maven this is all implicit. Maven expects to find your files in particular places, and will work automatically with that. Consequently setting up a project with Maven can be a lot simpler, but you have to play by Maven's rules!

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

How to add manifest permission to an application?

Copy the following line to your application manifest file and paste before the <application> tag.

<uses-permission android:name="android.permission.INTERNET"/>

Placing the permission below the <application/> tag will work, but will give you warning. So take care to place it before the <application/> tag declaration.

How to format current time using a yyyyMMddHHmmss format?

Time package in Golang has some methods that might be worth looking.

func (Time) Format

func (t Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,

Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.

Source (http://golang.org/pkg/time/#Time.Format)

I also found an example of defining the layout (http://golang.org/src/pkg/time/example_test.go)

func ExampleTime_Format() {
        // layout shows by example how the reference time should be represented.
        const layout = "Jan 2, 2006 at 3:04pm (MST)"
        t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
        fmt.Println(t.Format(layout))
        fmt.Println(t.UTC().Format(layout))
        // Output:
    // Nov 10, 2009 at 3:00pm (PST)
        // Nov 10, 2009 at 11:00pm (UTC)
    }

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

Checking if a variable is defined?

defined? is great, but if you are in a Rails environment you can also use try, especially in cases where you want to check a dynamic variable name:

foo = 1
my_foo = "foo"
my_bar = "bar"
try(:foo)        # => 1
try(:bar)        # => nil
try(my_foo)      # => 1
try(my_bar)      # => nil

Python os.path.join() on a list

It's just the method. You're not missing anything. The official documentation shows that you can use list unpacking to supply several paths:

s = "c:/,home,foo,bar,some.txt".split(",")
os.path.join(*s)

Note the *s intead of just s in os.path.join(*s). Using the asterisk will trigger the unpacking of the list, which means that each list argument will be supplied to the function as a separate argument.

Check whether user has a Chrome extension installed

There's another method shown at this Google Groups post. In short, you could try detecting whether the extension icon loads successfully. This may be helpful if the extension you're checking for isn't your own.

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.

How do I get the current timezone name in Postgres 9.3?

It seems to work fine in Postgresql 9.5:

SELECT current_setting('TIMEZONE');

Volley JsonObjectRequest Post request not working

I had the same issue once, the empty POST array is caused due a redirection of the request (on your server side), fix the URL so it doesn't have to be redirected when it hits the server. For Example, if https is forced using the .htaccess file on your server side app, make sure your client request has the "https://" prefix. Usually when a redirect happens the POST array is lost. I Hope this helps!

ImportError: No module named psycopg2

I faced the same issue and resolved it with following commands:

sudo apt-get install libpq-dev
pip install psycopg2

How to count days between two dates in PHP?

In case your DateTime has also hour:minutes:seconds and you still want to have the number of days..

   /**
     * Returns the total number of days between to DateTimes, 
     * if it is within the same year
     * @param $start
     * @param $end
     */
    public function dateTimesToDays($start,$end){
       return intval($end->format('z')) - intval($start->format('z')) + 1;
    }

https://github.com/dukeatcoding/timespan-converter

How to debug "ImagePullBackOff"?

On GKE, if the pod is dead, it's best to check for the events. It will show in more detail what the error is about.

In my case, I had :

Failed to pull image "gcr.io/project/imagename@sha256:c8e91af54fc17faa1c49e2a05def5cbabf8f0a67fc558eb6cbca138061a8400a":
 rpc error: code = Unknown desc = error pulling image configuration: unknown blob

It turned out the image was damaged somehow. After repushing it and deploying with the new hash, it worked again.

How to check for null in Twig?

you can use the following code to check whether

{% if var is defined %}

var is variable is SET

{% endif %}

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

Oracle - How to create a materialized view with FAST REFRESH and JOINS

The key checks for FAST REFRESH includes the following:

1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.

No 3 is easy to miss and worth highlighting here

How to create an executable .exe file from a .m file

It used to be possible to compile Matlab to C with older versions of Matlab. Check out other tools that Matlab comes with.

Newest Matlab code can be exported as a Java's jar or a .Net Dll, etc. You can then write an executable against that library - it will be obfuscated by the way. The users will have to install a freely available Matlab Runtime.

Like others mentioned, mcc / mcc.exe is what you want to convert matlab code to C code.

Converting Select results into Insert script - SQL Server

Here is another method, which may be easier than installing plugins or external tools in some situations:

  • Do a select [whatever you need]INTO temp.table_namefrom [... etc ...].
  • Right-click on the database in the Object Explorer => Tasks => Generate Scripts
  • Select temp.table_name in the "Choose Objects" screen, click Next.
  • In the "Specify how scripts should be saved" screen:
    • Click Advanced, find the "Types of data to Script" property, select "Data only", close the advanced properties.
    • Select "Save to new query window" (unless you have thousands of records).
  • Click Next, wait for the job to complete, observe the resulting INSERT statements appear in a new query window.
  • Use Find & Replace to change all [temp.table_name] to [your_table_name].
  • drop table [temp.table_name].

PHP Foreach Arrays and objects

Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreach loop which cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:

foreach ($arr as $item) {
    echo $item->sm_id;
}

In this example each of our values in the $arr will be accessed in order as $item. So we can print our values directly off of that. We could also include the index if we wanted:

foreach ($arr as $index => $item) {
    echo "Item at index {$index} has sm_id value {$item->sm_id}";
}

Printing prime numbers from 1 through 100

While this is relatively more production grade prime number generator, it is still valid to use for finding prime numbers from 1 through 100. The code uses Miller-Rabin Primality Test to achieve calculate prime numbers. Since it is probabilistic method, the accuracy increases with value of k. While the focus is on readability of code rather than speed, on AWS r5.2xlarge instance it took 3.791s for prime number until 1,000,000.

// C++ program to print all primes smaller than or equal to 
// n using Miller-Rabin Primality Test
// Reference: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
// It is not particularly to optimized 
// since focus is readability
// Compile: g++  -std=c++17 -o prime prime.c++ -ltbb 

#include <execution>
#include <iostream>
#include <math.h>
using namespace std; 

int power(unsigned long int x, unsigned long y, unsigned long p){
    int res = 1;
    x = x % p;
    while (y > 0) {
        if (y & 1)
            res = (res * x) % p;
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}

bool millerTest(unsigned long d, unsigned long n) {
    unsigned long a = 2 + rand () % (n - 4);

    unsigned long x = power(a, d, n);

    if (x == 1  || x == n - 1)
        return true;

    while (d != n - 1){
        x = (x * x) % n;
        d *= 2;
        if (x == 1) return false;
        if (x == n - 1) return true;

    }
    return false;
}

bool isPrime(unsigned long n, int k) {
    if (n <= 1 || n == 4) return false;
    if (n <= 3) return true;

    unsigned long int d = n - 1;
    while (d % 2 == 0)
        d /= 2;
    for(int i = 0; i < k; i++){
        if (!millerTest(d, n))
            return false;
    }
    return true;
}




int main() 
{ 
    int n = 1000000;
    int k = 200; 
    vector<unsigned long> primeN(n);
    iota(primeN.begin(), primeN.end(), 1);

    vector<bool> isPrimeV(n);



    transform(execution::par,
        primeN.begin(), primeN.end(), 
        isPrimeV.begin(), 
        [k](unsigned long x) -> bool {
            return isPrime(x, k);
        });

    int count = accumulate(isPrimeV.begin(), isPrimeV.end(), 0, [](int d, bool v){
        if (v == true) return d += 1; else return d;
    });
    cout << count << endl;

    return 0; 
} 

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

In addition to trying 2Toad's answer, I also ended up having to close Visual Studio and delete my .vs folder. After that, everything built correctly.

Incidentally, the error I was encountering didn't specify my Temp folder at all, but was referencing something else that was obviously system-generated. I neglected to save the specific error :\

Printing the last column of a line in a file

One way using awk:

tail -f file.txt | awk '/A1/ { print $NF }'

Can I call a function of a shell script from another shell script?

You can't directly call a function in another shell script.

You can move your function definitions into a separate file and then load them into your script using the . command, like this:

. /path/to/functions.sh

This will interpret functions.sh as if it's content were actually present in your file at this point. This is a common mechanism for implementing shared libraries of shell functions.

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

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

The error can be caused by

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

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

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

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

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

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

Passing the wrong model from a view to a partial view

Given the following model

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

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

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

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

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

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

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

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

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

Declaring a model in a layout

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

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

CSS height 100% percent not working

Set the containing element/div to a height. Otherwise your asking the browser to set the height to 100% of an unknown value and it can't.

More info here: http://webdesign.about.com/od/csstutorials/f/set-css-height-100-percent.htm

How to import a module given its name as string?

Similar as @monkut 's solution but reusable and error tolerant described here http://stamat.wordpress.com/dynamic-module-import-in-python/:

import os
import imp

def importFromURI(uri, absl):
    mod = None
    if not absl:
        uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri))
    path, fname = os.path.split(uri)
    mname, ext = os.path.splitext(fname)

    if os.path.exists(os.path.join(path,mname)+'.pyc'):
        try:
            return imp.load_compiled(mname, uri)
        except:
            pass
    if os.path.exists(os.path.join(path,mname)+'.py'):
        try:
            return imp.load_source(mname, uri)
        except:
            pass

    return mod

Add list to set?

Please notice the function set.update(). The documentation says:

Update a set with the union of itself and others.

Difference between Python's Generators and Iterators

Previous answers missed this addition: a generator has a close method, while typical iterators don’t. The close method triggers a StopIteration exception in the generator, which may be caught in a finally clause in that iterator, to get a chance to run some clean-up. This abstraction makes it most usable in the large than simple iterators. One can close a generator as one could close a file, without having to bother about what’s underneath.

That said, my personal answer to the first question would be: iteratable has an __iter__ method only, typical iterators have a __next__ method only, generators has both an __iter__ and a __next__ and an additional close.

For the second question, my personal answer would be: in a public interface, I tend to favor generators a lot, since it’s more resilient: the close method an a greater composability with yield from. Locally, I may use iterators, but only if it’s a flat and simple structure (iterators does not compose easily) and if there are reasons to believe the sequence is rather short especially if it may be stopped before it reach the end. I tend to look at iterators as a low level primitive, except as literals.

For control flow matters, generators are an as much important concept as promises: both are abstract and composable.

When to favor ng-if vs. ng-show/ng-hide?

Depends on your use case but to summarise the difference:

  1. ng-if will remove elements from DOM. This means that all your handlers or anything else attached to those elements will be lost. For example, if you bound a click handler to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and your click handler will not work any more, even after ng-if later evaluates to true and displays the element. You will need to reattach the handler.
  2. ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to hide/show elements (note: you might need to add your own classes). This way your handlers that were attached to children will not be lost.
  3. ng-if creates a child scope while ng-show/ng-hide does not

Elements that are not in the DOM have less performance impact and your web app might appear to be faster when using ng-if compared to ng-show/ng-hide. In my experience, the difference is negligible. Animations are possible when using both ng-show/ng-hide and ng-if, with examples for both in the Angular documentation.

Ultimately, the question you need to answer is whether you can remove element from DOM or not?

How can I iterate over files in a given directory?

I'm not quite happy with this implementation yet, I wanted to have a custom constructor that does DirectoryIndex._make(next(os.walk(input_path))) such that you can just pass the path you want a file listing for. Edits welcome!

import collections
import os

DirectoryIndex = collections.namedtuple('DirectoryIndex', ['root', 'dirs', 'files'])

for file_name in DirectoryIndex(*next(os.walk('.'))).files:
    file_path = os.path.join(path, file_name)

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Can I assume (bool)true == (int)1 for any C++ compiler?

Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...

Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as ints that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h> only require zero or non-zero, not necessarily zero or one.

If you cast that to bool, zero will convert to false, and non-zero to true (as you'd expect).

How do I pick randomly from an array?

Random Number of Random Items from an Array

def random_items(array)
  array.sample(1 + rand(array.count))
end

Examples of possible results:

my_array = ["one", "two", "three"]
my_array.sample(1 + rand(my_array.count))

=> ["two", "three"]
=> ["one", "three", "two"]
=> ["two"]

What is the difference between 'git pull' and 'git fetch'?

This graphic could be of help. git pull is essentially equivalent to git fetch then git merge

This graphic could be of help. git pull is essentially equivalent to git fetch then git merge

try/catch with InputMismatchException creates infinite loop

To complement the AmitD answer:

Just copy/pasted your program and had this output:

Error!
Enter first num: 
.... infinite times ....

As you can see, the instruction:

n1 = input.nextInt();

Is continuously throwing the Exception when your double number is entered, and that's because your stream is not cleared. To fix it, follow the AmitD answer.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Pick a random value from an enum?

Here a version that uses shuffle and streams

List<Direction> letters = Arrays.asList(Direction.values());
Collections.shuffle(letters);
return letters.stream().findFirst().get();

Execution sequence of Group By, Having and Where clause in SQL Server?

WHERE is first, then you GROUP the result of the query, and last but not least HAVING-clause is taken to filter the grouped result. This is the "logical" order, I don't know how this is technically implemented in the engine.

Where to install Android SDK on Mac OS X?

A simple way is changing to required sdk in some android project the number of

compileSdkVersion

in build.gradle file and you can install with the manager

Using union and count(*) together in SQL query

Is your goal...

  1. To count all the instances of "Bob Jones" in both tables (for example)
  2. To count all the instances of "Bob Jones" in Results in one row and all the instances of "Bob Jones" in Archive_Results in a separate row?

Assuming it's #1 you'd want something like...

SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name

Find and copy files

for i in $(ls); do cp -r "$i" "$i"_dev; done;

What does $1 [QSA,L] mean in my .htaccess file?

If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,

RewriteCond %{REQUEST_FILENAME} !-d

and if the requested filename is not a regular file that exists,

RewriteCond %{REQUEST_FILENAME} !-f

and if the requested filename is not a symbolic link,

RewriteCond %{REQUEST_FILENAME} !-l

then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Apache docs #flag_qsa

Another Example:

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

With the [QSA] flag, a request for

/pages/123?one=two

will be mapped to

/page.php?page=123&one=two

Edit In Place Content Editing

I've modified your plunker to get it working via angular-xeditable:

http://plnkr.co/edit/xUDrOS?p=preview

It is common solution for inline editing - you creale hyperlinks with editable-text directive that toggles into <input type="text"> tag:

<a href="#" editable-text="bday.name" ng-click="myform.$show()" e-placeholder="Name">
    {{bday.name || 'empty'}}
</a>

For date I used editable-date directive that toggles into html5 <input type="date">.

Get selected option from select element

Try this:

$('#ddlCodes').change(function() {
  var option = this.options[this.selectedIndex];
  $('#txtEntry2').text($(option).text());
});

Android sqlite how to check if a record exists

SELECT EXISTS with LIMIT 1 is much faster.

Query Ex: SELECT EXISTS (SELECT * FROM table_name WHERE column='value' LIMIT 1);

Code Ex:

public boolean columnExists(String value) {
    String sql = "SELECT EXISTS (SELECT * FROM table_name WHERE column='"+value+"' LIMIT 1)";
    Cursor cursor = database.rawQuery(sql, null);
    cursor.moveToFirst();

    // cursor.getInt(0) is 1 if column with value exists
    if (cursor.getInt(0) == 1) { 
        cursor.close();
        return true;
    } else {
        cursor.close();
        return false;
    }
}

How do I make jQuery wait for an Ajax call to finish before it returns?

It should wait until get request completed. After that I'll return get request body from where function is called.

function foo() {
    var jqXHR = $.ajax({
        url: url,
        type: 'GET',
        async: false,
    });
    return JSON.parse(jqXHR.responseText);  
}

LaTeX package for syntax highlighting of code in various languages

After asking a similar question I’ve created another package which uses Pygments, and offers quite a few more options than texments. It’s called minted and is quite stable and usable.

Just to show it off, here’s a code highlighted with minted:

Example code

Generator expressions vs. list comprehensions

Sometimes you can get away with the tee function from itertools, it returns multiple iterators for the same generator that can be used independently.

How do I vertically center an H1 in a div?

Just use padding top and bottom, it will automatically center the content vertically.

Split string, convert ToList<int>() in one line

also you can use this Extension method

public static List<int> SplitToIntList(this string list, char separator = ',')
{
    return list.Split(separator).Select(Int32.Parse).ToList();
}

usage:

var numberListString = "1, 2, 3, 4";
List<int> numberList = numberListString.SplitToIntList(',');

How to run Python script on terminal?

You need python installed on your system. Then you can run this in the terminal in the correct directory:

python gameover.py

Is there a list of Pytz Timezones?

They appear to be populated by the tz database time zones found here.

enter image description here

How to find if a given key exists in a C++ std::map

template <typename T, typename Key>
bool key_exists(const T& container, const Key& key)
{
    return (container.find(key) != std::end(container));
}

Of course if you wanted to get fancier you could always template out a function that also took a found function and a not found function, something like this:

template <typename T, typename Key, typename FoundFunction, typename NotFoundFunction>
void find_and_execute(const T& container, const Key& key, FoundFunction found_function, NotFoundFunction not_found_function)
{
    auto& it = container.find(key);
    if (it != std::end(container))
    {
        found_function(key, it->second);
    }
    else
    {
        not_found_function(key);
    }
}

And use it like this:

    std::map<int, int> some_map;
    find_and_execute(some_map, 1,
        [](int key, int value){ std::cout << "key " << key << " found, value: " << value << std::endl; },
        [](int key){ std::cout << "key " << key << " not found" << std::endl; });

The downside to this is coming up with a good name, "find_and_execute" is awkward and I can't come up with anything better off the top of my head...

Unexpected end of file error

Goto SolutionExplorer (should be already visible, if not use menu: View->SolutionExplorer).

Find your .cxx file in the solution tree, right click on it and choose "Properties" from the popup menu. You will get window with your file's properties.

Using tree on the left side go to the "C++/Precompiled Headers" section. On the right side of the window you'll get three properties. Set property named "Create/Use Precompiled Header" to the value of "Not Using Precompiled Headers".

Authentication failed because remote party has closed the transport stream

Adding the below code helped me overcome the issue.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;

Which Java library provides base64 encoding/decoding?

Guava also has Base64 (among other encodings and incredibly useful stuff)

How should I throw a divide by zero exception in Java without actually dividing by zero?

You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an IllegalArgumentException. As the documentation says:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Which is exactly what is going on here.

if (divisor == 0) {
    throw new IllegalArgumentException("Argument 'divisor' is 0");
}

Margin between items in recycler view Android

  1. Find the attribute card_view:cardUseCompatPadding="true" in cards_layout.xml and delete it. Start app and you will find there is no margin between each cardview item.

  2. Add margin attributes you like. Ex:

    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp" 
    

SVG gradient using CSS

2019 Answer

With brand new css properties you can have even more flexibility with variables aka custom properties

_x000D_
_x000D_
.shape {
  width:500px;
  height:200px;
}

.shape .gradient-bg {
  fill: url(#header-shape-gradient) #fff;
}

#header-shape-gradient {
  --color-stop: #f12c06;
  --color-bot: #faed34;
}
_x000D_
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" class="shape">
  <defs>
    <linearGradient id="header-shape-gradient" x2="0.35" y2="1">
        <stop offset="0%" stop-color="var(--color-stop)" />
        <stop offset="30%" stop-color="var(--color-stop)" />
        <stop offset="100%" stop-color="var(--color-bot)" />
      </linearGradient>
  </defs>
  <g>
    <polygon class="gradient-bg" points="0,0 100,0 0,66" />
  </g>
</svg>
_x000D_
_x000D_
_x000D_

Just set a named variable for each stop in gradient and then customize as you like in css. You can even change their values dynamically with javascript, like:

document.querySelector('#header-shape-gradient').style.setProperty('--color-stop', "#f5f7f9");

How to get Rails.logger printing to the console/stdout when running rspec?

You can define a method in spec_helper.rb that sends a message both to Rails.logger.info and to puts and use that for debugging:

def log_test(message)
    Rails.logger.info(message)
    puts message
end

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

The Best way is to create a user for your application and assign the permissions that are suitable for that user. Dont use 'NT AUTHORITY\NETWORK SERVICE' as your user it has its own vulnerability and it is a user that has permissions to so many things on the OS level. Stay away from this built in user.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

If you are using NodeJs for your server side, just add these to your route and you will be Ok

     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Your route will then look somehow like this

    router.post('/odin', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


    return res.json({Name: req.body.name, Phone: req.body.phone});
});

Client side for Ajax call

 var sendingData = {
   name: "Odinfono Emmanuel",
   phone: "1234567890"
}

<script>
  $(document).ready(function(){

    $.ajax({
        url: 'http://127.0.0.1:3000/odin',            
        method: 'POST',
        type: 'json',
        data: sendingData,
        success: function (response) {
            console.log(response);
        },
        error: function (error) {
            console.log(error);
        }
        });
    });
</script>

You should have something like this in your browser console as response

{ name: "Odinfono Emmanuel", phone: "1234567890"}

Enjoy coding....

Lightweight XML Viewer that can handle large files

I have tried dozens of XML editors hoping to find one which would be able to do some kind of visualization. The best lightweight viewer for windows I have found was XMLMarker - too bad the project has been dead for some years now. It is not so useful as an editor, but it does a good job of displaying flat XML data as tables.

There are tons of free editors that do XML syntax highlighting, including vim, emacs, scite, eclipse (J2EE edition), jedit, notepad++.

For heavyweight XML features, like XPath support, XSLT editing and debugging, SOAP/WSDL there are some good commercial tools like, XMLSpy, Oxygen, StylusStudio.

JEdit is open-source and also has plugins for XML, XPath and XSLT.

Word-2003 is fairly good for visualizing (but don't use it for editing). Excel-2003 and up also does a good job at visualizing flat XML data and can apply XSL transformations (again, no good as an editor).

AJAX POST and Plus Sign ( + ) -- How to Encode?

If you have to do a curl in php, you should use urlencode() from PHP but individually!

strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")

If you do urlencode(strPOST), you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!

Example 1

$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B

Example 2

$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B

Example 1 is the good way to prepare string for POST in curl

Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!

Unable to open project... cannot be opened because the project file cannot be parsed

And once you get things working again you should look into using something like subversion or mercurial for backup and revision control. Remember that he electrons don't always go where they are supposed to, backup early and often!

Purpose of returning by const value?

In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that + returned a non-const value, and you could write:

(a + b).expensive();

In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.

In summary, there is a rationale for this practice, but it is essentially obsolete.

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

window.location.href and window.open () methods in JavaScript

window.location.href is not a method, it's a property that will tell you the current URL location of the browser. Changing the value of the property will redirect the page.

window.open() is a method that you can pass a URL to that you want to open in a new window. For example:

window.location.href example:

window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open() example:

window.open('http://www.google.com'); //This will open Google in a new window.

Additional Information:

window.open() can be passed additional parameters. See: window.open tutorial

How to replace an entire line in a text file by line number

You can even pass parameters to the sed command:

test.sh

#!/bin/bash
echo "-> start"
for i in $(seq 5); do
  # passing parameters to sed
  j=$(($i+3))
  sed -i "${j}s/.*/replaced by '$i'!/" output.dat
done
echo "-> finished"
exit 

orignial output.dat:

a
b
c
d
e
f
g
h
i
j

Executing ./test.sh gives the new output.dat

a
b
c
replaced by '1'!
replaced by '2'!
replaced by '3'!
replaced by '4'!
replaced by '5'!
i
j

Removing App ID from Developer Connection

Update: You can now remove an App ID (as noted by @Guru in the comments).

In the past, this was not possible: I had the same problem, and the folks at Apple replied that they will leave all of the App ID you create associated to your login, to keep track of a sort of history related to your login.

It seems that they finally changed idea about.

Is there a REAL performance difference between INT and VARCHAR primary keys?

It's not about performance. It's about what makes a good primary key. Unique and unchanging over time. You may think an entity such as a country code never changes over time and would be a good candidate for a primary key. But bitter experience is that is seldom so.

INT AUTO_INCREMENT meets the "unique and unchanging over time" condition. Hence the preference.

How do I POST urlencoded form data with $http without jQuery?

URL-encoding variables using only AngularJS services

With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:

  1. $httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)

  2. $httpParamSerializer - a serializer used by Angular itself for GET requests

Example usage

$http({
  url: 'some/api/endpoint',
  method: 'POST',
  data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
  }
}).then(function(response) { /* do something here */ });

See a more verbose Plunker demo


How are $httpParamSerializerJQLike and $httpParamSerializer different

In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.

For example (ignoring percent encoding of brackets):

Encoding an array

{sites:['google', 'Facebook']} // Object with array property

sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike

sites=google&sites=facebook // Result with $httpParamSerializer

Encoding an object

{address: {city: 'LA', country: 'USA'}} // Object with object property

address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike

address={"city": "LA", country: "USA"} // Result with $httpParamSerializer

How to position the form in the center screen?

Simply set location relative to null after calling pack on the JFrame, that's it.

e.g.,

  JFrame frame = new JFrame("FooRendererTest");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(mainPanel); // or whatever...
  frame.pack();
  frame.setLocationRelativeTo(null);  // *** this will center your app ***
  frame.setVisible(true);

Regex to extract substring, returning 2 results for some reason

I've just had the same problem.

You only get the text twice in your result if you include a match group (in brackets) and the 'g' (global) modifier. The first item always is the first result, normally OK when using match(reg) on a short string, however when using a construct like:

while ((result = reg.exec(string)) !== null){
    console.log(result);
}

the results are a little different.

Try the following code:

var regEx = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
var result = sample_string.match(regEx);
console.log(JSON.stringify(result));
// ["1 cat","2 fish"]

var reg = new RegExp('[0-9]+ (cat|fish)','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null) {
    console.dir(JSON.stringify(result))
};
// '["1 cat","cat"]'
// '["2 fish","fish"]'

var reg = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null){
    console.dir(JSON.stringify(result))
};
// '["1 cat","1 cat","cat"]'
// '["2 fish","2 fish","fish"]'

(tested on recent V8 - Chrome, Node.js)

The best answer is currently a comment which I can't upvote, so credit to @Mic.

How can I remove a style added with .css() function?

This one also work!!

$elem.attr('style','');

How to change screen resolution of Raspberry Pi

TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the

resolution 82   1920x1080   60Hz    1080p

hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1

Converting a string to an integer on Android

Use regular expression is best way to doing this as already mentioned by ashish sahu

public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}

Use find command but exclude files in two directories

Try something like

find . \( -type f -name \*_peaks.bed -print \) -or \( -type d -and \( -name tmp -or -name scripts \) -and -prune \)

and don't be too surprised if I got it a bit wrong. If the goal is an exec (instead of print), just substitute it in place.

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

You can disable any Python warnings via the PYTHONWARNINGS environment variable. In this case, you want:

export PYTHONWARNINGS="ignore:Unverified HTTPS request"

To disable using Python code (requests >= 2.16.0):

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

For requests < 2.16.0, see original answer below.

Original answer

The reason doing urllib3.disable_warnings() didn't work for you is because it looks like you're using a separate instance of urllib3 vendored inside of requests.

I gather this based on the path here: /usr/lib/python2.6/site-packages/requests/packages/urllib3/connectionpool.py

To disable warnings in requests' vendored urllib3, you'll need to import that specific instance of the module:

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

What are the benefits of using C# vs F# or F# vs C#?

To answer your question as I understand it: Why use C#? (You say you're already sold on F#.)

First off. It's not just "functional versus OO". It's "Functional+OO versus OO". C#'s functional features are pretty rudimentary. F#'s are not. Meanwhile, F# does almost all of C#'s OO features. For the most part, F# ends up as a superset of C#'s functionality.

However, there are a few cases where F# might not be the best choice:

  • Interop. There are plenty of libraries that just aren't going to be too comfortable from F#. Maybe they exploit certain C# OO things that F# doesn't do the same, or perhaps they rely on internals of the C# compiler. For example, Expression. While you can easily turn an F# quotation into an Expression, the result is not always exactly what C# would create. Certain libraries have a problem with this.

    • Yes, interop is a pretty big net and can result in a bit of friction with some libraries.

    • I consider interop to also include if you have a large existing codebase. It might not make sense to just start writing parts in F#.

  • Design tools. F# doesn't have any. Does not mean it couldn't have any, but just right now you can't whip up a WinForms app with F# codebehind. Even where it is supported, like in ASPX pages, you don't currently get IntelliSense. So, you need to carefully consider where your boundaries will be for generated code. On a really tiny project that almost exclusively uses the various designers, it might not be worth it to use F# for the "glue" or logic. On larger projects, this might become less of an issue.

    • This isn't an intrinsic problem. Unlike the Rex M's answer, I don't see anything intrinsic about C# or F# that make them better to do a UI with lots of mutable fields. Maybe he was referring to the extra overhead of having to write "mutable" and using <- instead of =.

    • Also depends on the library/designer used. We love using ASP.NET MVC with F# for all the controllers, then a C# web project to get the ASPX designers. We mix the actual ASPX "code inline" between C# and F#, depending on what we need on that page. (IntelliSense versus F# types.)

  • Other tools. They might just be expecting C# only and not know how to deal with F# projects or compiled code. Also, F#'s libraries don't ship as part of .NET, so you have a bit extra to ship around.

  • But the number one issue? People. If none of your developers want to learn F#, or worse, have severe difficulty comprehending certain aspects, then you're probably toast. (Although, I'd argue you're toast anyways in that case.) Oh, and if management says no, that might be an issue.

I wrote about this a while ago: Why NOT F#?

Tab space instead of multiple non-breaking spaces ("nbsp")?

&emsp;, &ensp;, &#8195; or &#8194; can be used.

W3 says...

The character entities &ensp; and &emsp; denote an en space and an em space respectively, where an en space is half the point size and an em space is equal to the point size of the current font. 

Read More at W3.org for HTML3

Read More at W3.org for HTML4

Even more at Wikipedia

Get Row Index on Asp.net Rowcommand event

protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    try
    {
        if (e.CommandName == "Delete")
        {
            GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
            int RemoveAt = gvr.RowIndex;
            DataTable dt = new DataTable();
            dt = (DataTable)ViewState["Products"];
            dt.Rows.RemoveAt(RemoveAt);
            dt.AcceptChanges();
            ViewState["Products"] = dt;
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}
protected void gvProductsList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    try
    {
        gvProductsList.DataSource = ViewState["Products"];
        gvProductsList.DataBind();
    }
    catch (Exception ex)
    {

    }
}

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.tridenthyundai.ains" />

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

<bean id="messageSource" 
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages" />
</bean>

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

new Runnable() but no new thread?

If you want to create a new Thread...you can do something like this...

Thread t = new Thread(new Runnable() { public void run() { 
  // your code goes here... 
}});

Why is it important to override GetHashCode when Equals method is overridden?

Just to add on above answers:

If you don't override Equals then the default behavior is that references of the objects are compared. The same applies to hashcode - the default implmentation is typically based on a memory address of the reference. Because you did override Equals it means the correct behavior is to compare whatever you implemented on Equals and not the references, so you should do the same for the hashcode.

Clients of your class will expect the hashcode to have similar logic to the equals method, for example linq methods which use a IEqualityComparer first compare the hashcodes and only if they're equal they'll compare the Equals() method which might be more expensive to run, if we didn't implement hashcode, equal object will probably have different hashcodes (because they have different memory address) and will be determined wrongly as not equal (Equals() won't even hit).

In addition, except the problem that you might not be able to find your object if you used it in a dictionary (because it was inserted by one hashcode and when you look for it the default hashcode will probably be different and again the Equals() won't even be called, like Marc Gravell explains in his answer, you also introduce a violation of the dictionary or hashset concept which should not allow identical keys - you already declared that those objects are essentially the same when you overrode Equals so you don't want both of them as different keys on a data structure which suppose to have a unique key. But because they have a different hashcode the "same" key will be inserted as different one.

How do I run a single test using Jest?

As said a previous answer, you can run the command

jest -t 'fix-order-test'

If you have an it inside of a describe block, you have to run

jest -t '<describeString> <itString>'