Programs & Examples On #Vertex buffer

Confirm button before running deleting routine from website

You could use JavaScript. Either put the code inline, into a function or use jQuery.

  1. Inline:

    <a href="deletelink" onclick="return confirm('Are you sure?')">Delete</a>
    
  2. In a function:

    <a href="deletelink" onclick="return checkDelete()">Delete</a>
    

    and then put this in <head>:

    <script language="JavaScript" type="text/javascript">
    function checkDelete(){
        return confirm('Are you sure?');
    }
    </script>
    

    This one has more work, but less file size if the list is long.

  3. With jQuery:

    <a href="deletelink" class="delete">Delete</a>
    

    And put this in <head>:

    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script language="JavaScript" type="text/javascript">
    $(document).ready(function(){
        $("a.delete").click(function(e){
            if(!confirm('Are you sure?')){
                e.preventDefault();
                return false;
            }
            return true;
        });
    });
    </script>
    

How do I use extern to share variables between source files?

With xc8 you have to be careful about declaring a variable as the same type in each file as you could , erroneously, declare something an int in one file and a char say in another. This could lead to corruption of variables.

This problem was elegantly solved in a microchip forum some 15 years ago /* See "http:www.htsoft.com" / / "forum/all/showflat.php/Cat/0/Number/18766/an/0/page/0#18766"

But this link seems to no longer work...

So I;ll quickly try to explain it; make a file called global.h.

In it declare the following

#ifdef MAIN_C
#define GLOBAL
 /* #warning COMPILING MAIN.C */
#else
#define GLOBAL extern
#endif
GLOBAL unsigned char testing_mode; // example var used in several C files

Now in the file main.c

#define MAIN_C 1
#include "global.h"
#undef MAIN_C

This means in main.c the variable will be declared as an unsigned char.

Now in other files simply including global.h will have it declared as an extern for that file.

extern unsigned char testing_mode;

But it will be correctly declared as an unsigned char.

The old forum post probably explained this a bit more clearly. But this is a real potential gotcha when using a compiler that allows you to declare a variable in one file and then declare it extern as a different type in another. The problems associated with that are if you say declared testing_mode as an int in another file it would think it was a 16 bit var and overwrite some other part of ram, potentially corrupting another variable. Difficult to debug!

What is the difference between CSS and SCSS?

css has variables as well. You can use them like this:

--primaryColor: #ffffff;
--width: 800px;

body {
    width: var(--width);
    color: var(--primaryColor);
}
.content{
    width: var(--width);
    background: var(--primaryColor);
}

MySQL Data Source not appearing in Visual Studio

Uninstall later version and install mysql-connector 6.3.9 for visual studio 2010.

After installing add the dll files and restart the visual studio.

It works fine.

What is a pre-revprop-change hook in SVN, and how do I create it?

For Windows, here's a link to an example batch file that only allows changes to the log message (not other properties):

http://ayria.livejournal.com/33438.html

Basically copy the code below into a text file and name it pre-revprop-change.bat and save it in the \hooks subdirectory for your repository.

@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5

:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME

:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION

:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY

goto :eof

:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT

:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT

:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT

:ERROR_EXIT
exit /b 1

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

You can make the id the primary key, and set member_id to NOT NULL UNIQUE. (Which you've done.) Columns that are NOT NULL UNIQUE can be the target of foreign key references, just like a primary key can. (I'm pretty sure that's true of all SQL platforms.)

At the conceptual level, there's no difference between PRIMARY KEY and NOT NULL UNIQUE. At the physical level, this is a MySQL issue; other SQL platforms will let you use a sequence without making it the primary key.

But if performance is really important, you should think twice about widening your table by four bytes per row for that tiny visual convenience. In addition, if you switch to INNODB in order to enforce foreign key constraints, MySQL will use your primary key in a clustered index. Since you're not using your primary key, I imagine that could hurt performance.

How to use JavaScript to change div backgroundColor

var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
  this.style.backgroundColor = 'green';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
  this.style.backgroundColor = 'transparent';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'transparent';
};

Toggle show/hide on click with jQuery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js</script>        <script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").toggle();
  });
});
</script>
</head>
<body>
<p>Welcome !!!</p>
<button>Toggle between hide() and show()</button>
</body>
</html>

Why use Optional.of over Optional.ofNullable?

This depends upon scenarios.

Let's say you have some business functionality and you need to process something with that value further but having null value at time of processing would impact it.

Then, in that case, you can use Optional<?>.

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .map(<doSomething>)
                      .orElse("Default value in case of null");

Get Request and Session Parameters and Attributes from JSF pages

You can like this:

#{requestScope["paramName"]} ,#{sessionScope["paramName"]}

Because requestScope or sessionScope is a Map object.

Elegant way to report missing values in a data.frame

Another graphical and interactive way is to use is.na10 function from heatmaply library:

library(heatmaply)

heatmaply(is.na10(airquality), grid_gap = 1, 
          showticklabels = c(T,F),
            k_col =3, k_row = 3,
            margins = c(55, 30), 
            colors = c("grey80", "grey20"))

enter image description here

Probably won't work well with large datasets..

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

Use Font Awesome Icon in Placeholder

There is some slight delay and jank as the font changes in the answer provided by Jason. Using the "change" event instead of "keyup" resolves this issue.

$('#iconified').on('change', function() {
    var input = $(this);
    if(input.val().length === 0) {
        input.addClass('empty');
    } else {
        input.removeClass('empty');
    }
});

Run jar file in command prompt

You can run a JAR file from the command line like this:

java -jar myJARFile.jar

bitwise XOR of hex numbers in python

here's a better function

def strxor(a, b):     # xor two strings of different lengths
    if len(a) > len(b):
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
    else:
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])

How to select different app.config for several build configurations

You should consider ConfigGen. It was developed for this purpose. It produces a config file for each deployment machine, based on a template file and a settings file. I know that this doesn't answer your question specifically, but it might well answer your problem.

So rather than Debug, Release etc, you might have Test, UAT, Production etc. You can also have different settings for each developer machine, so that you can generate a config specific to your dev machine and change it without affecting any one else's deployment.

An example of usage might be...

<Target Name="BeforeBuild">
    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t       
        $(ProjectDir)App.config.template.xml -o $(SolutionDir)ConfigGen" />

    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t
        $(ProjectDir)App.config.template.xml -l -n $(ProjectDir)App.config" />
</Target>

If you place this in your .csproj file, and you have the following files...

$(ProjectDir)App.Config.Settings.xls

MachineName        ConfigFilePath   SQLServer        

default             App.config      DEVSQL005
Test                App.config      TESTSQL005
UAT                 App.config      UATSQL005
Production          App.config      PRODSQL005
YourLocalMachine    App.config      ./SQLEXPRESS


$(ProjectDir)App.config.template.xml 

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=[%SQLServer%]; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

... then this will be the result...

From the first command, a config file generated for each environment specified in the xls file, placed in the output directory $(SolutionDir)ConfigGen

.../solutiondir/ConfigGen/Production/App.config

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=PRODSQL005; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

From the second command, the local App.config used on your dev machine will be replaced with the generated config specified by the local (-l) switch and the filename (-n) switch.

The response content cannot be parsed because the Internet Explorer engine is not available, or

I have had this issue also, and while -UseBasicParsing will work for some, if you actually need to interact with the dom it wont work. Try using a a group policy to stop the initial configuration window from ever appearing and powershell won't stop you anymore. See here https://wahlnetwork.com/2015/11/17/solving-the-first-launch-configuration-error-with-powershells-invoke-webrequest-cmdlet/

Took me just a few minutes once I found this page, once the GP is set, powershell will allow you through.

How to Copy Contents of One Canvas to Another Canvas Locally

@robert-hurst has a cleaner approach.

However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.

    // select canvas elements
    var sourceCanvas = document.getElementById("some-unique-id");
    var destCanvas = document.getElementsByClassName("some-class-selector")[0];

    //copy canvas by DataUrl
    var sourceImageData = sourceCanvas.toDataURL("image/png");
    var destCanvasContext = destCanvas.getContext('2d');

    var destinationImage = new Image;
    destinationImage.onload = function(){
      destCanvasContext.drawImage(destinationImage,0,0);
    };
    destinationImage.src = sourceImageData;

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

In .net 4.0 Microsoft removed the ability to add DLLs to the Assembly simply by dragging and dropping.

Instead you need to use gacutil.exe, or create an installer to do it. Microsoft actually doesn’t recommend using gacutil, but I went that route anyway.

To use gacutil on a development machine go to:
Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010)

Then use these commands to uninstall and Reinstall respectively. Note I did NOT include .dll in the uninstall command.
gacutil /u myDLL
gacutil /i "C:\Program Files\Custom\myDLL.dll"

To use Gacutil on a non-development machine you will have to copy the executable and config file from your dev machine to the production machine. It looks like there are a few different versions of Gacutil. The one that worked for me, I found here:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe.config

Copy the files here or to the appropriate .net folder;
C:\Windows\Microsoft.NET\Framework\v4.0.30319

Then use these commands to uninstall and reinstall respectively
"C:\Users\BHJeremy\Desktop\Installing to the Gac in .net 4.0\gacutil.exe" /u "myDLL"

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\gacutil.exe" /i "C:\Program Files\Custom\myDLL.dll"

Relative paths based on file location instead of current working directory

What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.

#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

cd "$parent_path"
cat ../some.text

This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh inside dir.

Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)

How to process SIGTERM signal gracefully?

A class based clean to use solution:

import signal
import time

class GracefulKiller:
  kill_now = False
  def __init__(self):
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)

  def exit_gracefully(self,signum, frame):
    self.kill_now = True

if __name__ == '__main__':
  killer = GracefulKiller()
  while not killer.kill_now:
    time.sleep(1)
    print("doing something in a loop ...")

  print("End of the program. I was killed gracefully :)")

Removing the password from a VBA project

Another way to remove VBA project password is;

  • Open xls file with a hex editor. (ie. Hex Edit http://www.hexedit.com/)
  • Search for DPB
  • Replace DPB to DPx
  • Save file.
  • Open file in Excel.
  • Click "Yes" if you get any message box.
  • Set new password from VBA Project Properties.
  • Close and open again file, then type your new password to unprotect.

UPDATE: For Excel 2010 (Works for MS Office Pro Plus 2010 [14.0.6023.1000 64bit]),

  • Open the XLSX file with 7zip

If workbook is protected:

  • Browse the folder xl
  • If the workbook is protected, right click workbook.xml and select Edit
  • Find the portion <workbookProtection workbookPassword="XXXX" lockStructure="1"/> (XXXX is your encrypted password)
  • Remove XXXX part. (ie. <workbookProtection workbookPassword="" lockStructure="1"/>)
  • Save the file.
  • When 7zip asks you to update the archive, say Yes.
  • Close 7zip and re-open your XLSX.
  • Click Protect Workbook on Review tab.
  • Optional: Save your file.

If worksheets are protected:

  • Browse to xl/worksheets/ folder.
  • Right click the Sheet1.xml, sheet2.xml, etc and select Edit.
  • Find the portion <sheetProtection password="XXXX" sheet="1" objects="1" scenarios="1" />
  • Remove the encrypted password (ie. <sheetProtection password="" sheet="1" objects="1" scenarios="1" />)
  • Save the file.
  • When 7zip asks you to update the archive, say Yes.
  • Close 7zip and re-open your XLSX.
  • Click Unprotect Sheet on Review tab.
  • Optional: Save your file.

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

The important thing about a sprint is that: within a sprint the functionality that is to be delivered is fixed.

A sprint is normally an iteration. But you can for example have a 4 week sprint, but have 4 one week "internal" iterations within that sprint.

There is a lot of discussion about the length of sprints. I think that if you do it according to the book they should all be the same length.

We have found that a short first sprint to get the development environment up and running, followed by longer basic functionality sprints, then short sprints towards the end of the project, has worked for us.

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

FWIW, in our case a (PHP) website running on IIS was showing this message on attempting to connect to a database.

The resolution was to edit the Anonymous Authentication on that website to use the Application pool identity (and we set the application pool entry up to use a service account designed for that website).

How can I get the baseurl of site?

you could possibly add in the port for non port 80/SSL?

something like:

if (HttpContext.Current.Request.ServerVariables["SERVER_PORT"] != null && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "80" && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "443")
            {
                port = String.Concat(":", HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString());
            }

and use that in the final result?

Excel function to get first word from sentence in other cell

I found this on exceljet.net and works for me:

=LEFT(B4,FIND(" ",B4)-1)

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

I had a run in with the same problem. My application was also a Silverlight application and the service was being called from a class library with a custom UserControl that was being used in it.

The solution is simple. Copy the endpoint definitions from the config file (e.g. ServiceReferences.ClientConfig) of the class library to the config file of the silverlight application. I know you'd expect it to work without having to do this, but apparently someone in Redmond had a vacation that day.

Error to run Android Studio

It's probably because you don't have jdk installed in your machine. I had exact same problem in first run. Open a terminal (CTRL+ALT+T) and type: sudo apt-get install openjdk-7-jdk

When done setup Java environment variable. Steps as follows:

  1. sudo gedit /etc/environment
  2. Either in the beginning or end of the file write: JAVA_HOME=/usr/lib/jvm/java-7-openjdk-i386 (location may vary depending on the installation of your Java)
  3. export JAVA_HOME
  4. save and exit editor.
  5. Load the path variable again using the terminal: . /etc/environment

Couple of helpful links for further clarifications:

Hope this helps.

Get user input from textarea

Tested with Angular2 RC2

I tried a code-snippet similar to yours and it works for me ;) see [(ngModel)] = "str" in my template If you push the button, the console logs the current content of the textarea-field. Hope it helps

textarea-component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'textarea-comp',
  template: `
      <textarea cols="30" rows="4" [(ngModel)] = "str"></textarea>
      <p><button (click)="pushMe()">pushMeToLog</button></p>
  `
})

  export class TextAreaComponent {
    str: string;

  pushMe() {
      console.log( "TextAreaComponent::str: " + this.str);
  }
}

python save image from url

import urllib.request
import os

img_url = "https://betanews.com/wp-content/uploads/2017/09/firefox-logo.jpg"
img_name = os.path.basename(img_url)
urllib.request.urlretrieve(img_url,img_name)

Check Whether a User Exists

user infomation is stored in /etc/passwd, so you can use "grep 'usename' /etc/passwd" to check if the username exist. meanwhile you can use "id" shell command, it will print the user id and group id, if the user does not exist, it will print "no such user" message.

How do I check if a type is a subtype OR the type of an object?

Apparently, no.

Here's the options:

Type.IsSubclassOf

As you've already found out, this will not work if the two types are the same, here's a sample LINQPad program that demonstrates:

void Main()
{
    typeof(Derived).IsSubclassOf(typeof(Base)).Dump();
    typeof(Base).IsSubclassOf(typeof(Base)).Dump();
}

public class Base { }
public class Derived : Base { }

Output:

True
False

Which indicates that Derived is a subclass of Base, but that Baseis (obviously) not a subclass of itself.

Type.IsAssignableFrom

Now, this will answer your particular question, but it will also give you false positives. As Eric Lippert has pointed out in the comments, while the method will indeed return True for the two above questions, it will also return True for these, which you probably don't want:

void Main()
{
    typeof(Base).IsAssignableFrom(typeof(Derived)).Dump();
    typeof(Base).IsAssignableFrom(typeof(Base)).Dump();
    typeof(int[]).IsAssignableFrom(typeof(uint[])).Dump();
}

public class Base { }
public class Derived : Base { }

Here you get the following output:

True
True
True

The last True there would indicate, if the method only answered the question asked, that uint[] inherits from int[] or that they're the same type, which clearly is not the case.

So IsAssignableFrom is not entirely correct either.

is and as

The "problem" with is and as in the context of your question is that they will require you to operate on the objects and write one of the types directly in code, and not work with Type objects.

In other words, this won't compile:

SubClass is BaseClass
^--+---^
   |
   +-- need object reference here

nor will this:

typeof(SubClass) is typeof(BaseClass)
                    ^-------+-------^
                            |
                            +-- need type name here, not Type object

nor will this:

typeof(SubClass) is BaseClass
^------+-------^
       |
       +-- this returns a Type object, And "System.Type" does not
           inherit from BaseClass

Conclusion

While the above methods might fit your needs, the only correct answer to your question (as I see it) is that you will need an extra check:

typeof(Derived).IsSubclassOf(typeof(Base)) || typeof(Derived) == typeof(Base);

which of course makes more sense in a method:

public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
    return potentialDescendant.IsSubclassOf(potentialBase)
           || potentialDescendant == potentialBase;
}

How to get an object's properties in JavaScript / jQuery?

Get FireBug for Mozilla Firefox.

use console.log(obj);

JavaScript: Class.method vs. Class.prototype.method

A. Static Method:

      Class.method = function () { /* code */ }
  1. method() here is a function property added to an another function (here Class).
  2. You can directly access the method() by the class / function name. Class.method();
  3. No need for creating any object/instance (new Class()) for accessing the method(). So you could call it as a static method.

B. Prototype Method (Shared across all the instances):

     Class.prototype.method = function () { /* code using this.values */ }
  1. method() here is a function property added to an another function protype (here Class.prototype).
  2. You can either directly access by class name or by an object/instance (new Class()).
  3. Added advantage - this way of method() definition will create only one copy of method() in the memory and will be shared across all the object's/instance's created from the Class

C. Class Method (Each instance has its own copy):

   function Class () {
      this.method = function () { /* do something with the private members */};
   }
  1. method() here is a method defined inside an another function (here Class).
  2. You can't directly access the method() by the class / function name. Class.method();
  3. You need to create an object/instance (new Class()) for the method() access.
  4. This way of method() definition will create a unique copy of the method() for each and every objects created using the constructor function (new Class()).
  5. Added advantage - Bcos of the method() scope it has the full right to access the local members(also called private members) declared inside the constructor function (here Class)

Example:

    function Class() {
        var str = "Constructor method"; // private variable
        this.method = function () { console.log(str); };
    }
    Class.prototype.method = function() { console.log("Prototype method"); };
    Class.method = function() { console.log("Static method"); };

    new Class().method();     // Constructor method
    // Bcos Constructor method() has more priority over the Prototype method()

    // Bcos of the existence of the Constructor method(), the Prototype method 
    // will not be looked up. But you call it by explicity, if you want.
    // Using instance
    new Class().constructor.prototype.method(); // Prototype method

    // Using class name
    Class.prototype.method(); // Prototype method

    // Access the static method by class name
    Class.method();           // Static method

How do I add options to a DropDownList using jQuery?

try this Function:

function addtoselect(param,value){
    $('#mySelectBox').append('&lt;option value='+value+'&gt;'+param+'&lt;/option&gt;');
}

to call onChange event after pressing Enter key

pressing Enter when the focus in on a form control (input) normally triggers a submit (onSubmit) event on the form itself (not the input) so you could bind your this.handleInput to the form onSubmit.

Alternatively you could bind it to the blur (onBlur) event on the input which happens when the focus is removed (e.g. tabbing to the next element that can get focus)

Converting an int into a 4 byte char array (C)

Why would you need an intermediate cast to void * in C++ Because cpp doesn't allow direct conversion between pointers, you need to use reinterpret_cast or casting to void* does the thing.

How to remove all characters after a specific character in python?

Split on your separator at most once, and take the first piece:

sep = '...'
stripped = text.split(sep, 1)[0]

You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

Is it possible to serialize and deserialize a class in C++?

I recommend Google protocol buffers. I had the chance to test drive the library on a new project and it's remarkably easy to use. The library is heavily optimized for performance.

Protobuf is different than other serialization solutions mentioned here in the sense that it does not serialize your objects, but rather generates code for objects that are serialization according to your specification.

SoapUI "failed to load url" error when loading WSDL

This could be a problem with IPV6 address SOAP UI picking. Adding the following JVM option fixed it for me:

-Djava.net.preferIPv4Stack=true

I added it here:

C:\Program Files\SmartBear\soapUI-4.5.2\bin\soapUI-4.5.2.vmoptions

WPF What is the correct way of using SVG files as icons in WPF

Install the SharpVectors library

Install-Package SharpVectors

Add the following in XAML

<UserControl xmlns:svgc="http://sharpvectors.codeplex.com/svgc">
    <svgc:SvgViewbox Source="/Icons/icon.svg"/>
</UserControl>

How to check if a value is not null and not empty string in JS

If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:

if(data !== null && data !== '') {
   // do something
}

Notice that I changed your code to check for type equality (!==|===).

If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:

if (data) {
  // do something
}

Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).

The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.

Synchronous request in Node.js

Another possibility is to set up a callback that tracks completed tasks:

function onApiResults(requestId, response, results) {
    requestsCompleted |= requestId;

    switch(requestId) {
        case REQUEST_API1:
            ...
            [Call API2]
            break;
        case REQUEST_API2:
            ...
            [Call API3]
            break;
        case REQUEST_API3:
            ...
            break;
    }

    if(requestId == requestsNeeded)
        response.end();
}

Then simply assign an ID to each and you can set up your requirements for which tasks must be completed before closing the connection.

const var REQUEST_API1 = 0x01;
const var REQUEST_API2 = 0x02;
const var REQUEST_API3 = 0x03;
const var requestsNeeded = REQUEST_API1 | REQUEST_API2 | REQUEST_API3;

Okay, it's not pretty. It is just another way to make sequential calls. It's unfortunate that NodeJS does not provide the most basic synchronous calls. But I understand what the lure is to asynchronicity.

How to center a component in Material-UI and make it responsive?

Another option is:

<Grid container justify = "center">
  <Your centered component/>
</Grid>

Why does my sorting loop seem to append an element where it shouldn't?

Starting from Java 8, you can also use parallelSort which is useful if you have arrays containing a lot of elements.

Example:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "b", "y" };
    Arrays.parallelSort(strings);
    System.out.println(Arrays.toString(strings));   // [a, b, c, x, y]
}

If you want to ignore the case, you can use:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "B", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.compareToIgnoreCase(o2);
        }
    });
    System.out.println(Arrays.toString(strings));   // [a, B, c, x, y]
}

otherwise B will be before a.

If you want to ignore the trailing spaces during the comparison, you can use trim():

public static void main(String[] args) {
    String[] strings = { "x", "  a", "c ", " b", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.trim().compareTo(o2.trim());
        }
    });
    System.out.println(Arrays.toString(strings)); // [  a,  b, c , x, y]
}

See:

$date + 1 year?

To add one year to todays date use the following:

$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));

For the other examples you must initialize $StartingDate with a timestamp value for example:

$StartingDate = mktime();  // todays date as a timestamp

Try this

$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 365 day"));

or

$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 1 year"));

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

To top up on @Tim Schmelter, in which to get back the List<int> instead,

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
   .Where(li => li.Selected)
   .Select(li => li.Value)
   .Select(int.Parse)
   .ToList();

OpenCV NoneType object has no attribute shape

I faced the same problem today, please check for the path of the image as mentioned by cybseccrypt. After imread, try printing the image and see. If you get a value, it means the file is open.

Code:

img_src = cv2.imread('/home/deepak/python-workout/box2.jpg',0) print img_src

Hope this helps!

How do I count unique values inside a list

If you would like to have a histogram of unique values here's oneliner

import numpy as np    
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))

Adding maven nexus repo to my pom.xml

From Maven - Settings Reference

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                  http://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <servers>
    <server>
      <id>server001</id>
      <username>my_login</username>
      <password>my_password</password>
      <privateKey>${user.home}/.ssh/id_dsa</privateKey>
      <passphrase>some_passphrase</passphrase>
      <filePermissions>664</filePermissions>
      <directoryPermissions>775</directoryPermissions>
      <configuration></configuration>
    </server>
  </servers>
  ...
</settings>

id: This is the ID of the server (not of the user to login as) that matches the id element of the repository/mirror that Maven tries to connect to.

username, password: These elements appear as a pair denoting the login and password required to authenticate to this server.

privateKey, passphrase: Like the previous two elements, this pair specifies a path to a private key (default is ${user.home}/.ssh/id_dsa) and a passphrase, if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.

filePermissions, directoryPermissions: When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corrosponding to *nix file permissions, ie. 664, or 775.

Note: If you use a private key to login to the server, make sure you omit the element. Otherwise, the key will be ignored.

All you should need is the id, username and password

The id and URL should be defined in your pom.xml like this:

<repositories>
    ...
    <repository>
        <id>acme-nexus-releases</id>
        <name>acme nexus</name>
        <url>https://nexus.acme.net/content/repositories/releases</url>
    </repository>
    ...
</repositories>

If you need a username and password to your server, you should encrypt it. Maven Password Encryption

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

In search of this same solution, I found what I needed under a different question in stackoverflow: Powershell-log-off-remote-session. The below one line will return a list of logged on users.

query user /server:$SERVER

jQuery trigger file input

This is a very old question, but unfortunately this issue is still relevant and requires a solution.

The (suprisingly simple) solution I've come up with is to "hide" the actual file input field and wrap it with a LABEL tag (can be based on Bootstrap and HTML5, for enhancement).

See here:Example code here

This way, the real file input field is invisible and all you see is the customized "button" which is actually a modified LABEL element. When you click on this LABEL element, the window for selecting a file comes up and the file you choose will go into the real file input field.

On top of that, you can manipulate the look and behaviour as you wish (for example: get the name of the selected file from the file input file, after selected, and show it somewhere. The LABEL element doesn't do that automatically, of course. I usually just put it inside the LABEL, as its text content).

Beware though! The manipulation of the look and behaviour of this is limited to whatever you can imagine and think of.    ;-)  ;-)

How to use Comparator in Java to sort

The solution can be optimized in following way: Firstly, use a private inner class as the scope for the fields is to be the enclosing class TestPeople so as the implementation of class People won't get exposed to outer world. This can be understood in terms of creating an APIthat expects a sorted list of people Secondly, using the Lamba expression(java 8) which reduces the code, hence development effort

Hence code would be as below:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class TestPeople {
    public static void main(String[] args) {
        ArrayList<People> peps = new ArrayList<>();// Be specific, to avoid
                                                    // classCast Exception

        TestPeople test = new TestPeople();

        peps.add(test.new People(123, "M", 14.25));
        peps.add(test.new People(234, "M", 6.21));
        peps.add(test.new People(362, "F", 9.23));
        peps.add(test.new People(111, "M", 65.99));
        peps.add(test.new People(535, "F", 9.23));

        /*
         * Collections.sort(peps);
         * 
         * for (int i = 0; i < peps.size(); i++){
         * System.out.println(peps.get(i)); }
         */

        // The above code can be replaced by followin:

        peps.sort((People p1, People p2) -> p1.getid() - p2.getid());

        peps.forEach((p) -> System.out.println(" " + p.toString()));

    }

    private class People {
        private int id;

        @Override
        public String toString() {
            return "People [id=" + id + ", info=" + info + ", price=" + price + "]";
        }

        private String info;
        private double price;

        public People(int newid, String newinfo, double newprice) {
            setid(newid);
            setinfo(newinfo);
            setprice(newprice);
        }

        public int getid() {
            return id;
        }

        public void setid(int id) {
            this.id = id;
        }

        public String getinfo() {
            return info;
        }

        public void setinfo(String info) {
            this.info = info;
        }

        public double getprice() {
            return price;
        }

        public void setprice(double price) {
            this.price = price;
        }
    }
}

When are static variables initialized?

The static variable can be intialize in the following three ways as follow choose any one you like

  1. you can intialize it at the time of declaration
  2. or you can do by making static block eg:

    static {
            // whatever code is needed for initialization goes here
        }
    
  3. There is an alternative to static blocks — you can write a private static method

    class name {
        public static varType myVar = initializeVar();
    
        private static varType initializeVar() {
            // initialization code goes here
        }
    }
    

SQL multiple column ordering

Multiple column ordering depends on both column's corresponding values: Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.

enter image description here

Now I perform Order By in these two columns by executing below command:

enter image description here

Now again I insert new values in these two columns, where Alphabet value in ASC order:

enter image description here

and the columns in Example table look like this. Now again perform the same operation:

enter image description here

You can see the values in the first column are in desc order but second column is not in ASC order.

Angular 4 - Select default value in dropdown [Reactive Forms]

As option, if you need just default text in dropdown without default value, try add <option disabled value="null">default text here</option> like this:

<select id="country" formControlName="country">
 <option disabled value="null">default text here</option>
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>

In Chrome and Firefox works fine.

How to make String.Contains case insensitive?

You can create your own extension method to do this:

public static bool Contains(this string source, string toCheck, StringComparison comp)
  {
    return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
  }

And then call:

 mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);

How do I remove a comma off the end of a string?

i guess you're concatenating something in the loop, like

foreach($a as $b)
  $string .= $b . ',';

much better is to collect items in an array and then join it with a delimiter you need

foreach($a as $b)
  $result[] = $b;

$result = implode(',', $result);

this solves trailing and double delimiter problems that usually occur with concatenation

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

Give attention to CHARSET and COLLATE parameters when you create a table. In terms of FOREIGN KEY problems something like that:

CREATE TABLE yourTableName (
....
....
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

In my case i couldn´t create the table with FOREIGN KEY references. First i got the Error Code 1005 which pretty much says nothing. Then i added COLLATE and finally the error message complaining about CHARSET.

Error Code: 1253. COLLATION 'utf8_unicode_ci' is not valid for CHARACTER SET 'latin1'

After that correction my issue was solved.

How to lay out Views in RelativeLayout programmatically?

From what I've been able to piece together, you have to add the view using LayoutParams.

LinearLayout linearLayout = new LinearLayout(this);

RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

parentView.addView(linearLayout, relativeParams);

All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.

TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);

Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());

Remove blank values from array using C#

I prefer to use two options, white spaces and empty:

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
test = test.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

How to read text file in JavaScript

my example

<html>

<head>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>

<body>
  <script>
    function PreviewText() {
      var oFReader = new FileReader();
      oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
      oFReader.onload = function(oFREvent) {
        document.getElementById("uploadTextValue").value = oFREvent.target.result;
        document.getElementById("obj").data = oFREvent.target.result;
      };
    };
    jQuery(document).ready(function() {
      $('#viewSource').click(function() {
        var text = $('#uploadTextValue').val();
        alert(text);
        //here ajax
      });
    });
  </script>
  <object width="100%" height="400" data="" id="obj"></object>
  <div>
    <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
    <input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
  </div>
  <a href="#" id="viewSource">Source file</a>
</body>

</html>

Python reading from a file and saving to utf-8

Process text to and from Unicode at the I/O boundaries of your program using open with the encoding parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False) is the encoding used), so I recommend always explicitly using the encoding parameter for portability and clarity (Python 3 syntax below):

with open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with open(filename, 'w', encoding='utf8') as f:
    f.write(text)

If still using Python 2 or for Python 2/3 compatibility, the io module implements open with the same semantics as Python 3's open and exists in both versions:

import io
with io.open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with io.open(filename, 'w', encoding='utf8') as f:
    f.write(text)

finding first day of the month in python

The arrow module will steer you around and away from subtle mistakes, and it's easier to use that older products.

import arrow

def cleanWay(oneDate):
    if currentDate.date().day > 25:
        return currentDate.replace(months=+1,day=1)
    else:
        return currentDate.replace(day=1)


currentDate = arrow.get('25-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))

currentDate = arrow.get('28-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))

In this case there is no need for you to consider the varying lengths of months, for instance. Here's the output from this script.

25-Feb-2017 01-Feb-2017
28-Feb-2017 01-Mar-2017

Change Toolbar color in Appcompat 21

If you want to change the color of your toolbar all throughout your app, leverage the styles.xml. In general, I avoid altering ui components in my java code unless I am trying to do something programatically. If this is a one time set, then you should be doing it in xml to make your code cleaner. Here is what your styles.xml will look like:

    <!-- Base application theme. -->
<style name="YourAppName.AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Color Primary will be your toolbar color -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <!-- Color Primary Dark will be your default status bar color -->
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>

Make sure you use the above style in your AndroidManifext.xml as such:

    <application
        android:theme="@style/YourAppName.AppTheme">
    </application>

I wanted different toolbar colors for different activities. So I leveraged styles again like this:

    <style name="YourAppName.AppTheme.Activity1">
    <item name="colorPrimary">@color/activity1_primary</item>
    <item name="colorPrimaryDark">@color/activity1_primaryDark</item>
</style>

<style name="YourAppName.AppTheme.Activity2">
    <item name="colorPrimary">@color/activity2_primary</item>
    <item name="colorPrimaryDark">@color/activity2_primaryDark</item>
</style>

again, apply the styles to each activity in your AndroidManifest.xml as such:

<activity
    android:name=".Activity2"
    android:theme="@style/YourAppName.AppTheme.Activity2"
</activity>

<activity
    android:name=".Activity1"
    android:theme="@style/YourAppName.AppTheme.Activity1"
</activity>

How do I get some variable from another class in Java?

Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.

TSQL Default Minimum DateTime

I think your only option here is a constant. With that said - don't use it - stick with nulls instead of bogus dates.

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT '1/1/1753'
)

How can I be notified when an element is added to the page?

Warning!

This answer is now outdated. DOM Level 4 introduced MutationObserver, providing an effective replacement for the deprecated mutation events. See this answer to another question for a better solution than the one presented here. Seriously. Don't poll the DOM every 100 milliseconds; it will waste CPU power and your users will hate you.

Since mutation events were deprecated in 2012, and you have no control over the inserted elements because they are added by someone else's code, your only option is to continuously check for them.

function checkDOMChange()
{
    // check for any new element being inserted here,
    // or a particular node being modified

    // call the function again after 100 milliseconds
    setTimeout( checkDOMChange, 100 );
}

Once this function is called, it will run every 100 milliseconds, which is 1/10 (one tenth) of a second. Unless you need real-time element observation, it should be enough.

JDK on OSX 10.7 Lion

You can download jdk6 here http://support.apple.com/kb/DL1573

Wish it helps

How to make sure docker's time syncs with that of the host?

You can add your local files (/etc/timezone and /etc/localtime) as volume in your Docker container.

Update your docker-compose.yml with the following lines.

volumes:
    - "/etc/timezone:/etc/timezone:ro"
    - "/etc/localtime:/etc/localtime:ro"

Now the container time is the same as on your host.

fatal: could not create work tree dir 'kivy'

Your current directory does not has the write/create permission to create kivy directory, thats why occuring this problem.

Your current directory give 777 rights and try it.

sudo chmod 777 DIR_NAME
cd DIR_NAME
git clone https://github.com/mygitusername/kivy.git

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

how to make a div to wrap two float divs inside?

HTML

<div id="wrapper">
    <div id="nav"></div>
    <div id="content"></div>      
    <div class="clearFloat"></div>
</div>

CSS

.clearFloat {
    font-size: 0px;
    line-height: 0px;
    margin: 0px;
    padding: 0px;
    clear: both;
    height: 0px;
}

Get value of a specific object property in C# without knowing the class behind

In some cases, Reflection doesn't work properly.

You could use dictionaries, if all item types are the same. For instance, if your items are strings :

Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);

Or ints:

Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);

jquery beforeunload when closing (not leaving) the page?

Try javascript into your Ajax

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Reference link

Example 2:

document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){
    window.btn_clicked = true;
};
window.onbeforeunload = function(){
    if(!window.btn_clicked){
        return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
    }
};

Here it will alert the user every time he leaves the page, until he clicks on the button.

DEMO: http://jsfiddle.net/DerekL/GSWbB/show/

Explode string by one or more spaces or tabs

To separate by tabs:

$comp = preg_split("/[\t]/", $var);

To separate by spaces/tabs/newlines:

$comp = preg_split('/\s+/', $var);

To seperate by spaces alone:

$comp = preg_split('/ +/', $var);

Class constants in python

class Animal:
    HUGE = "Huge"
    BIG = "Big"

class Horse:
    def printSize(self):
        print(Animal.HUGE)

MySQL combine two columns into one column

For the MySQL fans out there, I like the IFNULL() function. Other answers here suggest similar functionality with the ISNULL() function in some implementations. In my situation, I have a column of descriptions which is NOT NULL, and a column of serial numbers which may be NULL This is how I combined them into one column:

SELECT CONCAT(description,IFNULL(' SN: ', serial_number),'')) FROM my_table;

My results suggest that the results of concatenating a string with NULL results in a NULL. I have been getting the alternative value in those cases.

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

XmlSerializer xs = new XmlSerializer(typeof(User), new XmlRootAttribute("yourRootName")); 

how do I join two lists using linq or lambda expressions

It sounds like you want something like:

var query = from order in workOrders
            join plan in plans
                 on order.WorkOrderNumber equals plan.WorkOrderNumber
            select new
            {
                order.WorkOrderNumber,
                order.Description,
                plan.ScheduledDate
            };

jQuery append text inside of an existing paragraph tag

If you want to append text or html to span then you can do it as below.

$('p span#add_here').append('text goes here');

append will add text to span tag at the end.

to replace entire text or html inside of span you can use .text() or .html()

What is the difference between vmalloc and kmalloc?

You only need to worry about using physically contiguous memory if the buffer will be accessed by a DMA device on a physically addressed bus (like PCI). The trouble is that many system calls have no way to know whether their buffer will eventually be passed to a DMA device: once you pass the buffer to another kernel subsystem, you really cannot know where it is going to go. Even if the kernel does not use the buffer for DMA today, a future development might do so.

vmalloc is often slower than kmalloc, because it may have to remap the buffer space into a virtually contiguous range. kmalloc never remaps, though if not called with GFP_ATOMIC kmalloc can block.

kmalloc is limited in the size of buffer it can provide: 128 KBytes*). If you need a really big buffer, you have to use vmalloc or some other mechanism like reserving high memory at boot.

*) This was true of earlier kernels. On recent kernels (I tested this on 2.6.33.2), max size of a single kmalloc is up to 4 MB! (I wrote a fairly detailed post on this.) — kaiwan

For a system call you don't need to pass GFP_ATOMIC to kmalloc(), you can use GFP_KERNEL. You're not an interrupt handler: the application code enters the kernel context by means of a trap, it is not an interrupt.

Installing packages in Sublime Text 2

You may try to install Package Control first by following simple instructions available at Installation Guide (which is like 1. Open the Console, 2. Paste the code).

Then please check Package Docs Control Usage for Basic Functionality:

Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+P (Win, Linux) or CMD+Shift+P (OS X). All Package Control commands begin with Package Control:, so start by typing Package.

The command pallete will now show a number of commands. Most users will be interested in the following:

Install Package

Show a list of all available packages that are available for install. This will include all of the packages from the default channel, plus any from repositories you have added.

Regular expression for exact match of a string

In malfaux's answer '^' and '$' has been used to detect the beginning and the end of the text.
These are usually used to detect the beginning and the end of a line.
However this may be the correct way in this case.
But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.

/\b123456\b/

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

Xcode 10.1 Swift 4

This worked for me:

let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
...

The key was adding in the URLSessionDataTask type declaration.

Removing duplicates in the lists

All the order-preserving approaches I've seen here so far either use naive comparison (with O(n^2) time-complexity at best) or heavy-weight OrderedDicts/set+list combinations that are limited to hashable inputs. Here is a hash-independent O(nlogn) solution:

Update added the key argument, documentation and Python 3 compatibility.

# from functools import reduce <-- add this import on Python 3

def uniq(iterable, key=lambda x: x):
    """
    Remove duplicates from an iterable. Preserves order. 
    :type iterable: Iterable[Ord => A]
    :param iterable: an iterable of objects of any orderable type
    :type key: Callable[A] -> (Ord => B)
    :param key: optional argument; by default an item (A) is discarded 
    if another item (B), such that A == B, has already been encountered and taken. 
    If you provide a key, this condition changes to key(A) == key(B); the callable 
    must return orderable objects.
    """
    # Enumerate the list to restore order lately; reduce the sorted list; restore order
    def append_unique(acc, item):
        return acc if key(acc[-1][1]) == key(item[1]) else acc.append(item) or acc 
    srt_enum = sorted(enumerate(iterable), key=lambda item: key(item[1]))
    return [item[1] for item in sorted(reduce(append_unique, srt_enum, [srt_enum[0]]))] 

Windows could not start the Apache2 on Local Computer - problem

i faced the same issue, in my case i needed to add module in httpd.conf
the file was incomplete with incorrect keywords ( like LoadModule )
go to command line, go to C:\Apache24\bin

C:\Apache24\bin > httpd.exe

the reason for the error can be known from the output of the above command

Set variable in jinja

{{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

Result:

it worked

Using Oracle to_date function for date string with milliseconds

For three digits millisecond:

TO_CHAR(LN_AUTOD_UWRG_DTTM,'MM/DD/YYYY HH24:MI:SS.FF3')

For six digits millisecond:

TO_CHAR(LN_AUTOD_UWRG_DTTM,'MM/DD/YYYY HH24:MI:SS.FF'),

highlight the navigation menu for the current page

It seems to me that you need current code as this ".menu-current css", I am asking the same code that works like a charm, You could try something like this might still be some configuration

a:link, a:active {
    color: blue;
    text-decoration: none;
}

a:visited {
    color: darkblue;
    text-decoration: none;
}

a:hover {
    color: blue;
    text-decoration: underline;
}

div.menuv {
    float: left;
    width: 10em;
    padding: 1em;
    font-size: small;
}


div.menuv ul, div.menuv li, div.menuv .menuv-current li {
    margin: 0;
    padding: 0;
    list-style: none;
    margin-bottom: 5px;
    font-weight: normal;
}

div.menuv ul ul {
    padding-left: 12px;
}

div.menuv a:link, div.menuv a:visited, div.menuv a:active, div.menuv a:hover {
    display: block;
    text-decoration: none;
    padding: 2px 2px 2px 3px;
    border-bottom: 1px dotted #999999;
}

div.menuv a:hover, div.menuv .menuv-current li a:hover {
    padding: 2px 0px 2px 1px;
    border-left: 2px solid green;
    border-right: 2px solid green;
}

div.menuv .menuv-current {
    font-weight: bold;
}

div.menuv .menuv-current a:hover {
    padding: 2px 2px 2px 3px;
    border-left: none;
    border-right: none;
    border-bottom: 1px dotted #999999;
    color: darkblue;
}

Change arrow colors in Bootstraps carousel

With Font Awesome icons:

<!-- Controls -->
<a class="carousel-control-prev" href="#carousel-example-generic" role="button" data-slide="prev">
  <span class="fa fa-chevron-left fa-lg" style="color:red;"></span>
  <span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carousel-example-generic" role="button" data-slide="next">
  <span class="fa fa-chevron-right fa-lg" style="color:red;"></span>
  <span class="sr-only">Next</span>
</a>

Returning value from called function in a shell script

If it's just a true/false test, have your function return 0 for success, and return 1 for failure. The test would then be:

if function_name; then
  do something
else
  error condition
fi

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Replace one character with another in Bash

Try this for paths:

echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'

It replaces the space inside the double-quoted string with a + sing, then replaces the + sign with a backslash, then removes/replaces the double-quotes.

I had to use this to replace the spaces in one of my paths in Cygwin.

echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'

SQL Server - inner join when updating

This should do it:

UPDATE ProductReviews
SET    ProductReviews.status = '0'
FROM   ProductReviews
       INNER JOIN products
         ON ProductReviews.pid = products.id
WHERE  ProductReviews.id = '17190'
       AND products.shopkeeper = '89137'

Celery Received unregistered task of type (run example)

The answer to your problem lies in THE FIRST LINE of the output you provided in your question: /usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and is available to Python. "is available to Python." % (configname, ))). Without the right configuration Celery is not able to do anything.

Reason why it can't find the celeryconfig is most likely it is not in your PYTHONPATH.

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

std::cin input with spaces?

I rather use the following method to get the input:

#include <iostream>
#include <string>

using namespace std;

int main(void) {
    string name;

    cout << "Hello, Input your name please: ";
    getline(cin, name);

    return 0;
}

It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

Indexes of all occurrences of character in a string

Try this

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

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

Search environment variables. enter image description here

open the "edit the system environment variables". then click on "environment variables". enter image description here

Under "User variables" click on "Path" then "Edit". enter image description here

Find your Java path and click "Edit". enter image description here

then paste the path of your java installation folder. Mostly you can find it on a path similar to this. C:\Program Files\Java\jdk-12.0.2\bin

Then click OK. now in the start menu, type cmd. open the command prompt. type java -version If you did it right,it should show something like this. enter image description here

How to find length of a string array?

Since you haven't initialized car yet so it has no existence in JVM(Java Virtual Machine) so you have to initialize it first.

For instance :

car = new String{"Porsche","Lamborghini"};

Now your code will run fine.

INPUT:

String car [];
car = new String{"Porsche","Lamborghini"};
System.out.println(car.length);

OUTPUT:

2

Getting an "ambiguous redirect" error

put quotes around your variable. If it happens to have spaces, it will give you "ambiguous redirect" as well. also check your spelling

echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  "${OUPUT_RESULTS}"

eg of ambiguous redirect

$ var="file with spaces"
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> "${var}"
$ cat file\ with\ spaces
aaaa     dddd         mol_tag

How to sort a list of lists by a specific index of the inner list?

Itemgetter lets you to sort by multiple criteria / columns:

sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))

How to upload files to server using Putty (ssh)

Use WinSCP for file transfer over SSH, putty is only for SSH commands.

How can I open a URL in Android's web browser from my application?

Simply go with short one to open your Url in Browser:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);

Variables within app.config/web.config

For rolling out products where we need to configure a lot of items with similar values, we use small console apps that read the XML and update based on the parameters passed in. These are then called by the installer after it has asked the user for the required information.

The type WebMvcConfigurerAdapter is deprecated

Since Spring 5 you just need to implement the interface WebMvcConfigurer:

public class MvcConfig implements WebMvcConfigurer {

This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter class

See here:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.html

String delimiter in string.split method

StringTokenizer st = new StringTokenizer("1||1||Abdul-Jabbar||Karim||1996||1974",
             "||");
while(st.hasMoreTokens()){
     System.out.println(st.nextElement());
}

Answer will print

1 1 Abdul-Jabbar Karim 1996 1974

How to build an APK file in Eclipse?

Eclipse 3.7 (Indigo): Go to Windows -> Preferences -> Android -> Build and uncheck "Skip packaging and dexing until export or launch"

Also, you can build it manually via Menu -> Project -> **Uncheck "Build automatically"**.

Replace a string in a file with nodejs

<p>Please click in the following {{link}} to verify the account</p>


function renderHTML(templatePath: string, object) {
    const template = fileSystem.readFileSync(path.join(Application.staticDirectory, templatePath + '.html'), 'utf8');
    return template.match(/\{{(.*?)\}}/ig).reduce((acc, binding) => {
        const property = binding.substring(2, binding.length - 2);
        return `${acc}${template.replace(/\{{(.*?)\}}/, object[property])}`;
    }, '');
}
renderHTML(templateName, { link: 'SomeLink' })

for sure you can improve the reading template function to read as stream and compose the bytes by line to make it more efficient

Change the value in app.config file dynamically

This code works for me:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    config.AppSettings.Settings["test"].Value = "blah";       
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");

Note: it doesn't update the solution item 'app.config', but the '.exe.config' one in the bin/ folder if you run it with F5.

How to use filesaver.js

For people who want to load it in the console :

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js';
document.body.appendChild(s);

Then :

saveAs(new Blob([data], {type: "application/octet-stream ;charset=utf-8"}), "video.ts")

File will be save when you're out of a breakpoint (at least on Chrome)

Detect if value is number in MySQL

Another alternative that seems faster than REGEXP on my computer is

SELECT * FROM myTable WHERE col1*0 != col1;

This will select all rows where col1 starts with a numeric value.

How to increase executionTimeout for a long-running query?

You can set executionTimeout in web.config to support the longer execution time.

executionTimeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN

<httpRuntime  executionTimeout = "300" />

This make execution timeout to five minutes.

Optional Int32 attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging. The default is 110 seconds, Reference.

Converting a sentence string to a string array of words in Java

Try this:

String[] stringArray = Pattern.compile("ian").split(
"This is a sample sentence"
.replaceAll("[^\\p{Alnum}]+", "") //this will remove all non alpha numeric chars
);

for (int j=0; i<stringArray .length; j++) {
  System.out.println(i + " \"" + stringArray [j] + "\"");
}

Cannot install Aptana Studio 3.6 on Windows

Installing Aptana Studio in passive mode bypasses the installation of Git for Windows and Node.js.

Aptana_Studio_3_Setup_3.6.1 /passive /norestart

(I am unsure whether Aptana Studio will work properly without those "prerequisites", but it appears to.)

If you want a global installation in a specific directory, the command line is

Aptana_Studio_3_Setup_3.6.1.exe /passive /norestart ALLUSERS=1 APPDIR=c:\apps\AptanaStudio

How to unblock with mysqladmin flush hosts

mysqladmin is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).

You type that command from a shell prompt.

Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:

FLUSH HOSTS;

http://dev.mysql.com/doc/refman/5.6/en/flush.html

http://dev.mysql.com/doc/refman/5.6/en/mysqladmin.html

Bootstrap 3 and Youtube in Modal

If you don't want to edit the bootstrap CSS or all of the above doesn't help you at all (like in my case), there's an easy fix to get the video running in a modal on Firefox.

You just need to remove the "fade" class from the modal and as it opens the "in" class, too:

$('#myModal').on('shown.bs.modal', function () {
    $('#myModal').removeClass('in');
});

How to get text in QlineEdit when QpushButton is pressed in a string?

The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)

QObject(self.pb, SIGNAL("clicked()"), self.button_clicked)

def button_clicked(self):
  self.le.setText("shost")

I think this is what you want. I hope i got your question correctly :)

Get DateTime.Now with milliseconds precision

How can I exactly construct a time stamp of actual time with milliseconds precision?

I suspect you mean millisecond accuracy. DateTime has a lot of precision, but is fairly coarse in terms of accuracy. Generally speaking, you can't. Usually the system clock (which is where DateTime.Now gets its data from) has a resolution of around 10-15 ms. See Eric Lippert's blog post about precision and accuracy for more details.

If you need more accurate timing than this, you may want to look into using an NTP client.

However, it's not clear that you really need millisecond accuracy here. If you don't care about the exact timing - you just want to show the samples in the right order, with "pretty good" accuracy, then the system clock should be fine. I'd advise you to use DateTime.UtcNow rather than DateTime.Now though, to avoid time zone issues around daylight saving transitions, etc.

If your question is actually just around converting a DateTime to a string with millisecond precision, I'd suggest using:

string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                            CultureInfo.InvariantCulture);

(Note that unlike your sample, this is sortable and less likely to cause confusion around whether it's meant to be "month/day/year" or "day/month/year".)

PHP "php://input" vs $_POST

If post data is malformed, $_POST will not contain anything. Yet, php://input will have the malformed string.

For example there is some ajax applications, that do not form correct post key-value sequence for uploading a file, and just dump all the file as post data, without variable names or anything. $_POST will be empty, $_FILES empty also, and php://input will contain exact file, written as a string.

Change text (html) with .animate

Following the suggestion by JiminP....

I made a jsFiddle that will "smoothly" transition between two spans in case anyone is interested in seeing this in action. You have two main options:

  1. one span fades out at the same time as the other span is fading in
  2. one span fades out followed by the other span fading in.

The first time you click the button, number 1 above will occur. The second time you click the button, number 2 will occur. (I did this so you can visually compare the two effects.)

Try it Out: http://jsfiddle.net/jWcLz/594/

Details:

Number 1 above (the more difficult effect) is accomplished by positioning the spans directly on top of each other via CSS with absolute positioning. Also, the jQuery animates are not chained together, so that they can execute at the same time.

HTML

<div class="onTopOfEachOther">
    <span id='a'>Hello</span>
    <span id='b' style="display: none;">Goodbye</span>
</div>

<br />
<br />

<input type="button" id="btnTest" value="Run Test" />

CSS

.onTopOfEachOther {
    position: relative;
}
.onTopOfEachOther span {
    position: absolute;
    top: 0px;
    left: 0px;
}

JavaScript

$('#btnTest').click(function() {        
    fadeSwitchElements('a', 'b');    
}); 

function fadeSwitchElements(id1, id2)
{
    var element1 = $('#' + id1);
    var element2 = $('#' + id2);

    if(element1.is(':visible'))
    {
        element1.fadeToggle(500);
        element2.fadeToggle(500);
    }
    else
    {
         element2.fadeToggle(500, function() {
            element1.fadeToggle(500);
        });   
    }    
}

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

We encountered this issue and discovered that the error was being thrown when using (IE in our case) the browser logged in as the process account, then changing the session log in through the application (SharePoint). I believe this scenario passes two authentication schemes:

  1. Negotiate
  2. NTLM

The application hosted an *.asmx web service, that was being called on a load balanced server, initiating a web service call to itself using a WCF-like .NET3.5 binding.

Code that was used to call the web service:

public class WebServiceClient<T> : IDisposable
{
    private readonly T _channel;
    private readonly IClientChannel _clientChannel;

    public WebServiceClient(string url)
        : this(url, null)
    {
    }
    /// <summary>
    /// Use action to change some of the connection properties before creating the channel
    /// </summary>
    public WebServiceClient(string url,
         Action<CustomBinding, HttpTransportBindingElement, EndpointAddress, ChannelFactory> init)
    {
        var binding = new CustomBinding();
        binding.Elements.Add(
            new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8));
        var transport = url.StartsWith("https", StringComparison.InvariantCultureIgnoreCase)
                            ? new HttpsTransportBindingElement()
                            : new HttpTransportBindingElement();
        transport.AuthenticationScheme = System.Net.AuthenticationSchemes.Ntlm;
        binding.Elements.Add(transport);

        var address = new EndpointAddress(url);

        var factory = new ChannelFactory<T>(binding, address);
        factory.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

        if (init != null)
        {
            init(binding, transport, address, factory);
        }

        this._clientChannel = (IClientChannel)factory.CreateChannel();
        this._channel = (T)this._clientChannel;
    }

    /// <summary>
    /// Use this property to call service methods
    /// </summary>
    public T Channel
    {
        get { return this._channel; }
    }
    /// <summary>
    /// Use this porperty when working with
    /// Session or Cookies
    /// </summary>
    public IClientChannel ClientChannel
    {
        get { return this._clientChannel; }
    }

    public void Dispose()
    {
        this._clientChannel.Dispose();
    }
}

We discovered that if the session credential was the same as the browser's process account, then just NTLM was used and the call was successful. Otherwise it would result in this captured exception:

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'.

In the end, I am fairly certain that one of the authentication schemes would pass authentication while the other wouldn't, because it was not granted appropriate access.

Adding a column after another column within SQL

Assuming MySQL (EDIT: posted before the SQL variant was supplied):

ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn

The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Update for mid 2016:

The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!

Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!

Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!

Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot

  • Webpack
  • NPM as a build tool (no Gulp, Grunt or Bower)
  • React with Redux
  • ESLint
  • the list is long. Go and explore!

Your questions:

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

  • Everything belongs in package.json now

  • Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev (--save-dev updates your package.json by adding an entry to devDependencies)

  • Dependencies required for your application during runtime are in "dependencies" i.e. npm install lodash --save (--save updates your package.json by adding an entry to dependencies)

If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?

Always. Just because of comfort. When you add a flag (--save-dev or --save) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name is npm i -D package-name and shortcut for npm install --save package-name is npm i -S package-name

Checking if my Windows application is running

For my WPF application i've defined global app id and use semaphore to handle it.

public partial class App : Application
{      
    private const string AppId = "c1d3cdb1-51ad-4c3a-bdb2-686f7dd10155";

    //Passing name associates this sempahore system wide with this name
    private readonly Semaphore instancesAllowed = new Semaphore(1, 1, AppId);

    private bool WasRunning { set; get; }

    private void OnExit(object sender, ExitEventArgs e)
    {
        //Decrement the count if app was running
        if (this.WasRunning)
        {
            this.instancesAllowed.Release();
        }
    }

    private void OnStartup(object sender, StartupEventArgs e)
    {
        //See if application is already running on the system
        if (this.instancesAllowed.WaitOne(1000))
        {
            new MainWindow().Show();
            this.WasRunning = true;
            return;
        }

        //Display
        MessageBox.Show("An instance is already running");

        //Exit out otherwise
        this.Shutdown();
    }
}

File.Move Does Not Work - File Already Exists

Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.

if variable contains

You might want indexOf

if (code.indexOf("ST1") >= 0) { ... }
else if (code.indexOf("ST2") >= 0) { ... }

It checks if contains is anywhere in the string variable code. This requires code to be a string. If you want this solution to be case-insensitive you have to change the case to all the same with either String.toLowerCase() or String.toUpperCase().

You could also work with a switch statement like

switch (true) {
    case (code.indexOf('ST1') >= 0):
        document.write('code contains "ST1"');
        break;
    case (code.indexOf('ST2') >= 0):
        document.write('code contains "ST2"');        
        break;        
    case (code.indexOf('ST3') >= 0):
        document.write('code contains "ST3"');
        break;        
    }?

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

Disable F5 and browser refresh using JavaScript

var ctrlKeyDown = false;

$(document).ready(function(){    
    $(document).on("keydown", keydown);
    $(document).on("keyup", keyup);
});

function keydown(e) { 

    if ((e.which || e.keyCode) == 116 || ((e.which || e.keyCode) == 82 && ctrlKeyDown)) {
        // Pressing F5 or Ctrl+R
        e.preventDefault();
    } else if ((e.which || e.keyCode) == 17) {
        // Pressing  only Ctrl
        ctrlKeyDown = true;
    }
};

function keyup(e){
    // Key up Ctrl
    if ((e.which || e.keyCode) == 17) 
        ctrlKeyDown = false;
};

Perl: Use s/ (replace) and return new string

If you have Perl 5.14 or greater, you can use the /r option with the substitution operator to perform non-destructive substitution:

print "bla: ", $myvar =~ s/a/b/r, "\n";

In earlier versions you can achieve the same using a do() block with a temporary lexical variable, e.g.:

print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";

Clear ComboBox selected text

all depend on the configuration. for me works

comboBox.SelectedIndex = -1;

my configuration

DropDownStyle: DropDownList

(text can't be changed for the user)

HTTP response code for POST when resource already exists

Late to the game maybe but I stumbled upon this semantics issue while trying to make a REST API.

To expand a little on Wrikken's answer, I think you could use either 409 Conflict or 403 Forbidden depending on the situation - in short, use a 403 error when the user can do absolutely nothing to resolve the conflict and complete the request (e.g. they can't send a DELETE request to explicitly remove the resource), or use 409 if something could possibly be done.

10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

Nowadays, someone says "403" and a permissions or authentication issue comes to mind, but the spec says that it's basically the server telling the client that it's not going to do it, don't ask it again, and here's why the client shouldn't.

As for PUT vs. POST... POST should be used to create a new instance of a resource when the user has no means to or shouldn't create an identifier for the resource. PUT is used when the resource's identity is known.

9.6 PUT

...

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,

it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.

How to split the name string in mysql?

To get the rest of the string after the second instance of the space delimiter:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(MsgRest, ' ', 1), ' ', -1) AS EMailID
,  SUBSTRING_INDEX(SUBSTRING_INDEX(MsgRest, ' ', 2), ' ', -1) AS DOB
,  IF(
    LOCATE(' ', `MsgRest`) > 0,
    TRIM(SUBSTRING(SUBSTRING(`MsgRest`, LOCATE(' ', `MsgRest`) +1), 
         LOCATE(' ', SUBSTRING(`MsgRest`, LOCATE(' ', `MsgRest`) +1)) +1)),
    NULL
) AS Person
FROM inbox

M_PI works with math.h but not with cmath in Visual Studio

This is still an issue in VS Community 2015 and 2017 when building either console or windows apps. If the project is created with precompiled headers, the precompiled headers are apparently loaded before any of the #includes, so even if the #define _USE_MATH_DEFINES is the first line, it won't compile. #including math.h instead of cmath does not make a difference.

The only solutions I can find are either to start from an empty project (for simple console or embedded system apps) or to add /Y- to the command line arguments, which turns off the loading of precompiled headers.

For information on disabling precompiled headers, see for example https://msdn.microsoft.com/en-us/library/1hy7a92h.aspx

It would be nice if MS would change/fix this. I teach introductory programming courses at a large university, and explaining this to newbies never sinks in until they've made the mistake and struggled with it for an afternoon or so.

Node package ( Grunt ) installed but not available

On WIN7 I had to manually add the path to the npm folder (which contains the elusive 'grunt' file) to the Windows PATH environmental variable.
In my case that was C:\Users\mhaagsma\AppData\Roaming\npm

Rollback transaction after @Test

You need to run your test with a Spring context and a transaction manager, e.g.,

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {"/your-applicationContext.xml"})
@TransactionConfiguration(transactionManager="txMgr")
public class StudentSystemTest {

     @Test
     public void testTransactionalService() {
         // test transactional service
     }

     @Test
     @Transactional
     public void testNonTransactionalService() {
         // test non-transactional service
     }
}

See chapter 3.5.8. Transaction Management of the Spring reference for further details.

Have a reloadData for a UITableView animate when changing

You might want to use:

Objective-C

[UIView transitionWithView: self.tableView
                  duration: 0.35f
                   options: UIViewAnimationOptionTransitionCrossDissolve
                animations: ^(void)
 {
      [self.tableView reloadData];
 }
                completion: nil];

Swift

UIView.transitionWithView(tableView,
                          duration: 0.35,
                          options: .TransitionCrossDissolve,
                          animations:
{ () -> Void in
    self.tableView.reloadData()
},
                          completion: nil);

Swift 3, 4 & 5

UIView.transition(with: tableView,
                  duration: 0.35,
                  options: .transitionCrossDissolve,
                  animations: { self.tableView.reloadData() }) // left out the unnecessary syntax in the completion block and the optional completion parameter

No hassles. :D

You can also use any of the UIViewAnimationOptionTransitions you want for cooler effects:

  • transitionNone
  • transitionFlipFromLeft
  • transitionFlipFromRight
  • transitionCurlUp
  • transitionCurlDown
  • transitionCrossDissolve
  • transitionFlipFromTop
  • transitionFlipFromBottom

Visual Studio Error: (407: Proxy Authentication Required)

Using IDE configuration:

  1. Open Visual Studio 2012, click on Tools from the file menu bar and then click Options,

  2. From the Options window, expand the Source Control option, click on Plug-in Selection and make sure that the Current source control plug-in is set to Visual Studio Team Foundation Server.

  3. Next, click on the Visual Studio Team Foundation Server option under Source Control and perform the following steps: Check Use proxy server for file downloads. Enter the host name of your preferred Team Foundation Server 2010 Proxy server. Set the port to 443. Check Use SSL encryption (https) to connect.

  4. Click the OK button.

Using exe.config:

Modify the devenv.exe.config where IDE executable is like this:

<system.net> 
  <defaultProxy>  
   <proxy proxyaddress=”http://proxy:3128”
     bypassonlocal=”True” autoDetect=”True” /> 
   <bypasslist> 
   <add address=”http://URL”/>  
  </bypasslist> 
 </defaultProxy> 

Declare your proxy at proxyaddress and remember bypasslist urls and ip addresses will be excluded from proxy traffic.

Then restart visual studio to update changes.

How do I look inside a Python object?

There is a python code library build just for this purpose: inspect Introduced in Python 2.7

Convert list of ASCII codes to string (byte array) in Python

This is reviving an old question, but in Python 3, you can just use bytes directly:

>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

How to debug a GLSL shader?

The existing answers are all good stuff, but I wanted to share one more little gem that has been valuable in debugging tricky precision issues in a GLSL shader. With very large int numbers represented as a floating point, one needs to take care to use floor(n) and floor(n + 0.5) properly to implement round() to an exact int. It is then possible to render a float value that is an exact int by the following logic to pack the byte components into R, G, and B output values.

  // Break components out of 24 bit float with rounded int value
  // scaledWOB = (offset >> 8) & 0xFFFF
  float scaledWOB = floor(offset / 256.0);
  // c2 = (scaledWOB >> 8) & 0xFF
  float c2 = floor(scaledWOB / 256.0);
  // c0 = offset - (scaledWOB << 8)
  float c0 = offset - floor(scaledWOB * 256.0);
  // c1 = scaledWOB - (c2 << 8)
  float c1 = scaledWOB - floor(c2 * 256.0);

  // Normalize to byte range
  vec4 pix;  
  pix.r = c0 / 255.0;
  pix.g = c1 / 255.0;
  pix.b = c2 / 255.0;
  pix.a = 1.0;
  gl_FragColor = pix;

How do I make the return type of a method generic?

 private static T[] prepareArray<T>(T[] arrayToCopy, T value)
    {
        Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
        arrayToCopy[arrayToCopy.Length - 1] = value;
        return (T[])arrayToCopy;
    }

I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.

How would I stop a while loop after n amount of time?

Try the following:

import time
timeout = time.time() + 60*5   # 5 minutes from now
while True:
    test = 0
    if test == 5 or time.time() > timeout:
        break
    test = test - 1

You may also want to add a short sleep here so this loop is not hogging CPU (for example time.sleep(1) at the beginning or end of the loop body).

How to install packages offline?

If you want install python libs and their dependencies offline, finish following these steps on a machine with the same os, network connected, and python installed:

1) Create a requirements.txt file with similar content (Note - these are the libraries you wish to download):

Flask==0.12
requests>=2.7.0
scikit-learn==0.19.1
numpy==1.14.3
pandas==0.22.0

One option for creating the requirements file is to use pip freeze > requirements.txt. This will list all libraries in your environment. Then you can go in to requirements.txt and remove un-needed ones.

2) Execute command mkdir wheelhouse && pip download -r requirements.txt -d wheelhouse to download libs and their dependencies to directory wheelhouse

3) Copy requirements.txt into wheelhouse directory

4) Archive wheelhouse into wheelhouse.tar.gz with tar -zcf wheelhouse.tar.gz wheelhouse

Then upload wheelhouse.tar.gz to your target machine:

1) Execute tar -zxf wheelhouse.tar.gz to extract the files

2) Execute pip install -r wheelhouse/requirements.txt --no-index --find-links wheelhouse to install the libs and their dependencies

Google.com and clients1.google.com/generate_204

Like Snukker said, clients1.google.com is where the search suggestions come from. My guess is that they make a request to force clients1.google.com into your DNS cache before you need it, so you will have less latency on the first "real" request.

Google Chrome already does that for any links on a page, and (I think) when you type an address in the location bar. This seems like a way to get all browsers to do the same thing.

How to format a DateTime in PowerShell

A simple and nice way is:

$time = (Get-Date).ToString("yyyy:MM:dd")

php.ini: which one?

It really depends on the situation, for me its in fpm as I'm using PHP5-FPM. A solution to your problem could be a universal php.ini and then using a symbolic link created like:

ln -s /etc/php5/php.ini php.ini

Then any modifications you make will be in one general .ini file. This is probably not really the best solution though, you might want to look into modifying some configuration so that you literally use one file, on one location. Not multiple locations hacked together.

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

Put in other words, this error is telling you that SQL Server does not know which B to select from the group.

Either you want to select one specific value (e.g. the MIN, SUM, or AVG) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B in the GROUP BY field list).


Consider the following data:

ID  A   B
1   1  13
1   1  79
1   2  13
1   2  13
1   2  42

The query

SELECT A, COUNT(B) AS T1 
FROM T2 
GROUP BY A

would return:

A  T1
1  2
2  3

which is all well and good.

However consider the following (illegal) query, which would produce this error:

SELECT A, COUNT(B) AS T1, B 
FROM T2 
GROUP BY A

And its returned data set illustrating the problem:

A  T1  B
1  2   13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...?
2  3   13? 42? ...?

However, the following two queries make this clear, and will not cause the error:

  1. Using an aggregate

    SELECT A, COUNT(B) AS T1, SUM(B) AS B
    FROM T2
    GROUP BY A
    

    would return:

    A  T1  B
    1  2   92
    2  3   68
    
  2. Adding the column to the GROUP BY list

    SELECT A, COUNT(B) AS T1, B
    FROM T2
    GROUP BY A, B
    

    would return:

    A  T1  B
    1  1   13
    1  1   79
    2  2   13
    2  1   42
    

OPTION (RECOMPILE) is Always Faster; Why?

Necroing this question but there's an explanation that no-one seems to have considered.

STATISTICS - Statistics are not available or misleading

If all of the following are true:

  1. The columns feedid and feedDate are likely to be highly correlated (e.g. a feed id is more specific than a feed date and the date parameter is redundant information).
  2. There is no index with both columns as sequential columns.
  3. There are no manually created statistics covering both these columns.

Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.

Direct casting vs 'as' operator?

The as keyword is good in asp.net when you use the FindControl method.

Hyperlink link = this.FindControl("linkid") as Hyperlink;
if (link != null)
{
     ...
}

This means you can operate on the typed variable rather then having to then cast it from object like you would with a direct cast:

object linkObj = this.FindControl("linkid");
if (link != null)
{
     Hyperlink link = (Hyperlink)linkObj;
}

It's not a huge thing, but it saves lines of code and variable assignment, plus it's more readable

Is there a way to create and run javascript in Chrome?

Try this:
1. Install Node.js from https://nodejs.org/
2. Place your JavaScript code into a .js file (e.g. someCode.js)
3. Open a cmd shell (or Terminal on Mac) and use Node's Read-Eval-Print-Loop (REPL) to execute someCode.js like this:
> node someCode.js

Hope this helps!

Check if Cookie Exists

Sorry, not enough rep to add a comment, but from zmbq's answer:

Anyway, to see if a cookie exists, you can check Cookies.Get(string), this will not modify the cookie collection.

is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like:

bool cookieExists = HttpContext.Current.Request.Cookies["cookie_name"] != null;

Cannot open include file with Visual Studio

Go to your Project properties (Project -> Properties -> Configuration Properties -> C/C++ -> General) and in the field Additional Include Directories add the path to your .h file.

And be sure that your Configuration and Platform are the active ones. Example: Configuration: Active(Debug) Platform: Active(Win32).

Changing factor levels with dplyr mutate

Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be

df <- iris %>%
  mutate(Species = recode(Species, 
     setosa = "SETOSA",
     versicolor = "VERSICOLOR",
     virginica = "VIRGINICA")
  )

Custom Date/Time formatting in SQL Server

in MS SQL Server you can do:

SET DATEFORMAT ymd

year, month, day,

UINavigationBar Hide back Button Text

Swift version, works perfectly globally:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Normal)
        UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Highlighted)

        return true
    }

Reverse a comparator in Java 8

You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:

Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
        .thenComparingInt(SomeEntity::getProperty2)
        .thenComparing(SomeEntity::getProperty3, reverseOrder());

How can you determine a point is between two other points on a line segment?

Here's how I did it at school. I forgot why it is not a good idea.

EDIT:

@Darius Bacon: cites a "Beautiful Code" book which contains an explanation why the belowed code is not a good idea.

#!/usr/bin/env python
from __future__ import division

epsilon = 1e-6

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

class LineSegment:
    """
    >>> ls = LineSegment(Point(0,0), Point(2,4))
    >>> Point(1, 2) in ls
    True
    >>> Point(.5, 1) in ls
    True
    >>> Point(.5, 1.1) in ls
    False
    >>> Point(-1, -2) in ls
    False
    >>> Point(.1, 0.20000001) in ls
    True
    >>> Point(.1, 0.2001) in ls
    False
    >>> ls = LineSegment(Point(1, 1), Point(3, 5))
    >>> Point(2, 3) in ls
    True
    >>> Point(1.5, 2) in ls
    True
    >>> Point(0, -1) in ls
    False
    >>> ls = LineSegment(Point(1, 2), Point(1, 10))
    >>> Point(1, 6) in ls
    True
    >>> Point(1, 1) in ls
    False
    >>> Point(2, 6) in ls 
    False
    >>> ls = LineSegment(Point(-1, 10), Point(5, 10))
    >>> Point(3, 10) in ls
    True
    >>> Point(6, 10) in ls
    False
    >>> Point(5, 10) in ls
    True
    >>> Point(3, 11) in ls
    False
    """
    def __init__(self, a, b):
        if a.x > b.x:
            a, b = b, a
        (self.x0, self.y0, self.x1, self.y1) = (a.x, a.y, b.x, b.y)
        self.slope = (self.y1 - self.y0) / (self.x1 - self.x0) if self.x1 != self.x0 else None

    def __contains__(self, c):
        return (self.x0 <= c.x <= self.x1 and
                min(self.y0, self.y1) <= c.y <= max(self.y0, self.y1) and
                (not self.slope or -epsilon < (c.y - self.y(c.x)) < epsilon))

    def y(self, x):        
        return self.slope * (x - self.x0) + self.y0

if __name__ == '__main__':
    import  doctest
    doctest.testmod()

How to listen for 'props' changes

if myProp is an object, it may not be changed in usual. so, watch will never be triggered. the reason of why myProp not be changed is that you just set some keys of myProp in most cases. the myProp itself is still the one. try to watch props of myProp, like "myProp.a",it should work.

iOS Swift - Get the Current Local Time and Date Timestamp

in Swift 5

extension Date {
    static var currentTimeStamp: Int64{
        return Int64(Date().timeIntervalSince1970 * 1000)
    }
}

call like this:

let timeStamp = Date.currentTimeStamp
print(timeStamp)

Thanks @lenooh

Python send POST with header

To make POST request instead of GET request using urllib2, you need to specify empty data, for example:

import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)

Easy way to turn JavaScript array into comma-separated list?

The Array.prototype.join() method:

_x000D_
_x000D_
var arr = ["Zero", "One", "Two"];_x000D_
_x000D_
document.write(arr.join(", "));
_x000D_
_x000D_
_x000D_

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch

_x000D_
_x000D_
var data = { "results":[  _x000D_
  [  _x000D_
     {  _x000D_
        "b":"0.110547334",_x000D_
        "cost":"0.000000",_x000D_
        "w":"1.998889"_x000D_
     }_x000D_
  ],_x000D_
  [  _x000D_
     {  _x000D_
        "x":0,_x000D_
        "y":0_x000D_
     },_x000D_
     {  _x000D_
        "x":1,_x000D_
        "y":2_x000D_
     },_x000D_
     {  _x000D_
        "x":2,_x000D_
        "y":4_x000D_
     },_x000D_
     {  _x000D_
        "x":3,_x000D_
        "y":6_x000D_
     },_x000D_
     {  _x000D_
        "x":4,_x000D_
        "y":8_x000D_
     },_x000D_
     {  _x000D_
        "x":5,_x000D_
        "y":10_x000D_
     },_x000D_
     {  _x000D_
        "x":6,_x000D_
        "y":12_x000D_
     },_x000D_
     {  _x000D_
        "x":7,_x000D_
        "y":14_x000D_
     },_x000D_
     {  _x000D_
        "x":8,_x000D_
        "y":16_x000D_
     },_x000D_
     {  _x000D_
        "x":9,_x000D_
        "y":18_x000D_
     },_x000D_
     {  _x000D_
        "x":10,_x000D_
        "y":20_x000D_
     },_x000D_
     {  _x000D_
        "x":11,_x000D_
        "y":22_x000D_
     },_x000D_
     {  _x000D_
        "x":12,_x000D_
        "y":24_x000D_
     },_x000D_
     {  _x000D_
        "x":13,_x000D_
        "y":26_x000D_
     },_x000D_
     {  _x000D_
        "x":14,_x000D_
        "y":28_x000D_
     },_x000D_
     {  _x000D_
        "x":15,_x000D_
        "y":30_x000D_
     },_x000D_
     {  _x000D_
        "x":16,_x000D_
        "y":32_x000D_
     },_x000D_
     {  _x000D_
        "x":17,_x000D_
        "y":34_x000D_
     },_x000D_
     {  _x000D_
        "x":18,_x000D_
        "y":36_x000D_
     },_x000D_
     {  _x000D_
        "x":19,_x000D_
        "y":38_x000D_
     },_x000D_
     {  _x000D_
        "x":20,_x000D_
        "y":40_x000D_
     },_x000D_
     {  _x000D_
        "x":21,_x000D_
        "y":42_x000D_
     },_x000D_
     {  _x000D_
        "x":22,_x000D_
        "y":44_x000D_
     },_x000D_
     {  _x000D_
        "x":23,_x000D_
        "y":46_x000D_
     },_x000D_
     {  _x000D_
        "x":24,_x000D_
        "y":48_x000D_
     },_x000D_
     {  _x000D_
        "x":25,_x000D_
        "y":50_x000D_
     },_x000D_
     {  _x000D_
        "x":26,_x000D_
        "y":52_x000D_
     },_x000D_
     {  _x000D_
        "x":27,_x000D_
        "y":54_x000D_
     },_x000D_
     {  _x000D_
        "x":28,_x000D_
        "y":56_x000D_
     },_x000D_
     {  _x000D_
        "x":29,_x000D_
        "y":58_x000D_
     },_x000D_
     {  _x000D_
        "x":30,_x000D_
        "y":60_x000D_
     },_x000D_
     {  _x000D_
        "x":31,_x000D_
        "y":62_x000D_
     },_x000D_
     {  _x000D_
        "x":32,_x000D_
        "y":64_x000D_
     },_x000D_
     {  _x000D_
        "x":33,_x000D_
        "y":66_x000D_
     },_x000D_
     {  _x000D_
        "x":34,_x000D_
        "y":68_x000D_
     },_x000D_
     {  _x000D_
        "x":35,_x000D_
        "y":70_x000D_
     },_x000D_
     {  _x000D_
        "x":36,_x000D_
        "y":72_x000D_
     },_x000D_
     {  _x000D_
        "x":37,_x000D_
        "y":74_x000D_
     },_x000D_
     {  _x000D_
        "x":38,_x000D_
        "y":76_x000D_
     },_x000D_
     {  _x000D_
        "x":39,_x000D_
        "y":78_x000D_
     },_x000D_
     {  _x000D_
        "x":40,_x000D_
        "y":80_x000D_
     },_x000D_
     {  _x000D_
        "x":41,_x000D_
        "y":82_x000D_
     },_x000D_
     {  _x000D_
        "x":42,_x000D_
        "y":84_x000D_
     },_x000D_
     {  _x000D_
        "x":43,_x000D_
        "y":86_x000D_
     },_x000D_
     {  _x000D_
        "x":44,_x000D_
        "y":88_x000D_
     },_x000D_
     {  _x000D_
        "x":45,_x000D_
        "y":90_x000D_
     },_x000D_
     {  _x000D_
        "x":46,_x000D_
        "y":92_x000D_
     },_x000D_
     {  _x000D_
        "x":47,_x000D_
        "y":94_x000D_
     },_x000D_
     {  _x000D_
        "x":48,_x000D_
        "y":96_x000D_
     },_x000D_
     {  _x000D_
        "x":49,_x000D_
        "y":98_x000D_
     },_x000D_
     {  _x000D_
        "x":50,_x000D_
        "y":100_x000D_
     },_x000D_
     {  _x000D_
        "x":51,_x000D_
        "y":102_x000D_
     },_x000D_
     {  _x000D_
        "x":52,_x000D_
        "y":104_x000D_
     },_x000D_
     {  _x000D_
        "x":53,_x000D_
        "y":106_x000D_
     },_x000D_
     {  _x000D_
        "x":54,_x000D_
        "y":108_x000D_
     },_x000D_
     {  _x000D_
        "x":55,_x000D_
        "y":110_x000D_
     },_x000D_
     {  _x000D_
        "x":56,_x000D_
        "y":112_x000D_
     },_x000D_
     {  _x000D_
        "x":57,_x000D_
        "y":114_x000D_
     },_x000D_
     {  _x000D_
        "x":58,_x000D_
        "y":116_x000D_
     },_x000D_
     {  _x000D_
        "x":59,_x000D_
        "y":118_x000D_
     },_x000D_
     {  _x000D_
        "x":60,_x000D_
        "y":120_x000D_
     },_x000D_
     {  _x000D_
        "x":61,_x000D_
        "y":122_x000D_
     },_x000D_
     {  _x000D_
        "x":62,_x000D_
        "y":124_x000D_
     },_x000D_
     {  _x000D_
        "x":63,_x000D_
        "y":126_x000D_
     },_x000D_
     {  _x000D_
        "x":64,_x000D_
        "y":128_x000D_
     },_x000D_
     {  _x000D_
        "x":65,_x000D_
        "y":130_x000D_
     },_x000D_
     {  _x000D_
        "x":66,_x000D_
        "y":132_x000D_
     },_x000D_
     {  _x000D_
        "x":67,_x000D_
        "y":134_x000D_
     },_x000D_
     {  _x000D_
        "x":68,_x000D_
        "y":136_x000D_
     },_x000D_
     {  _x000D_
        "x":69,_x000D_
        "y":138_x000D_
     },_x000D_
     {  _x000D_
        "x":70,_x000D_
        "y":140_x000D_
     },_x000D_
     {  _x000D_
        "x":71,_x000D_
        "y":142_x000D_
     },_x000D_
     {  _x000D_
        "x":72,_x000D_
        "y":144_x000D_
     },_x000D_
     {  _x000D_
        "x":73,_x000D_
        "y":146_x000D_
     },_x000D_
     {  _x000D_
        "x":74,_x000D_
        "y":148_x000D_
     },_x000D_
     {  _x000D_
        "x":75,_x000D_
        "y":150_x000D_
     },_x000D_
     {  _x000D_
        "x":76,_x000D_
        "y":152_x000D_
     },_x000D_
     {  _x000D_
        "x":77,_x000D_
        "y":154_x000D_
     },_x000D_
     {  _x000D_
        "x":78,_x000D_
        "y":156_x000D_
     },_x000D_
     {  _x000D_
        "x":79,_x000D_
        "y":158_x000D_
     },_x000D_
     {  _x000D_
        "x":80,_x000D_
        "y":160_x000D_
     },_x000D_
     {  _x000D_
        "x":81,_x000D_
        "y":162_x000D_
     },_x000D_
     {  _x000D_
        "x":82,_x000D_
        "y":164_x000D_
     },_x000D_
     {  _x000D_
        "x":83,_x000D_
        "y":166_x000D_
     },_x000D_
     {  _x000D_
        "x":84,_x000D_
        "y":168_x000D_
     },_x000D_
     {  _x000D_
        "x":85,_x000D_
        "y":170_x000D_
     },_x000D_
     {  _x000D_
        "x":86,_x000D_
        "y":172_x000D_
     },_x000D_
     {  _x000D_
        "x":87,_x000D_
        "y":174_x000D_
     },_x000D_
     {  _x000D_
        "x":88,_x000D_
        "y":176_x000D_
     },_x000D_
     {  _x000D_
        "x":89,_x000D_
        "y":178_x000D_
     },_x000D_
     {  _x000D_
        "x":90,_x000D_
        "y":180_x000D_
     },_x000D_
     {  _x000D_
        "x":91,_x000D_
        "y":182_x000D_
     },_x000D_
     {  _x000D_
        "x":92,_x000D_
        "y":184_x000D_
     },_x000D_
     {  _x000D_
        "x":93,_x000D_
        "y":186_x000D_
     },_x000D_
     {  _x000D_
        "x":94,_x000D_
        "y":188_x000D_
     },_x000D_
     {  _x000D_
        "x":95,_x000D_
        "y":190_x000D_
     },_x000D_
     {  _x000D_
        "x":96,_x000D_
        "y":192_x000D_
     },_x000D_
     {  _x000D_
        "x":97,_x000D_
        "y":194_x000D_
     },_x000D_
     {  _x000D_
        "x":98,_x000D_
        "y":196_x000D_
     },_x000D_
     {  _x000D_
        "x":99,_x000D_
        "y":198_x000D_
     }_x000D_
  ]]};_x000D_
_x000D_
var scatterSeries = []; _x000D_
_x000D_
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';_x000D_
               console.info(ch);_x000D_
               _x000D_
               scatterSeries.push(JSON.parse(ch));_x000D_
console.info(scatterSeries);
_x000D_
_x000D_
_x000D_

code sample - https://codepen.io/nagasai/pen/GGzZVB

How do I escape the wildcard/asterisk character in bash?

It may be worth getting into the habit of using printf rather then echo on the command line.

In this example it doesn't give much benefit but it can be more useful with more complex output.

FOO="BAR * BAR"
printf %s "$FOO"

PHP cURL GET request and request's body

CURLOPT_POSTFIELDS as the name suggests, is for the body (payload) of a POST request. For GET requests, the payload is part of the URL in the form of a query string.

In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.

curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);

//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

(WAMP/XAMP) send Mail using SMTP localhost

I prefer using PHPMailer script to send emails from localhost as it lets me use my Gmail account as SMTP. You can find the PHPMailer from http://phpmailer.worxware.com/ . Help regarding how to use gmail as SMTP or any other SMTP can be found at http://www.mittalpatel.co.in/php_send_mail_from_localhost_using_gmail_smtp . Hope this helps!

How to Decrease Image Brightness in CSS

The feature you're looking for is filter. It is capable of doing a range of image effects, including brightness:

#myimage {
    filter: brightness(50%);
}

You can find a helpful article about it here: http://www.html5rocks.com/en/tutorials/filters/understanding-css/

An another: http://davidwalsh.name/css-filters

And most importantly, the W3C specs: https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html

Note this is something that's only very recently coming into CSS as a feature. It is available, but a large number of browsers out there won't support it yet, and those that do support it will require a vendor prefix (ie -webkit-filter:, -moz-filter, etc).

It is also possible to do filter effects like this using SVG. SVG support for these effects is well established and widely supported (the CSS filter specs have been taken from the existing SVG specs)

Also note that this is not to be confused with the proprietary filter style available in old versions of IE (although I can predict a problem with the namespace clash when the new style drops its vendor prefix).

If none of that works for you, you could still use the existing opacity feature, but not the way you're thinking: simply create a new element with a solid dark colour, place it on top of your image, and fade it out using opacity. The effect will be of the image behind being darkened.

Finally you can check the browser support of filter here.

how to copy only the columns in a DataTable to another DataTable?

If only the columns are required then DataTable.Clone() can be used. With Clone function only the schema will be copied. But DataTable.Copy() copies both the structure and data

E.g.

DataTable dt = new DataTable();
dt.Columns.Add("Column Name");
dt.Rows.Add("Column Data");
DataTable dt1 = dt.Clone();
DataTable dt2 = dt.Copy();

dt1 will have only the one column but dt2 will have one column with one row.

Is there a numpy builtin to reject outliers from a list

Consider that all the above methods fail when your standard deviation gets very large due to huge outliers.

(Simalar as the average caluclation fails and should rather caluclate the median. Though, the average is "more prone to such an error as the stdDv".)

You could try to iteratively apply your algorithm or you filter using the interquartile range: (here "factor" relates to a n*sigma range, yet only when your data follows a Gaussian distribution)

import numpy as np

def sortoutOutliers(dataIn,factor):
    quant3, quant1 = np.percentile(dataIn, [75 ,25])
    iqr = quant3 - quant1
    iqrSigma = iqr/1.34896
    medData = np.median(dataIn)
    dataOut = [ x for x in dataIn if ( (x > medData - factor* iqrSigma) and (x < medData + factor* iqrSigma) ) ] 
    return(dataOut)

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

ASP.NET MVC - Extract parameter of an URL

I'm not familiar with ASP.NET but I guess you could use a split function to split it in an array using the / as delimiter, then grab the last element in the array (usually the array length -1) to get the extract you want.

Ok this does not seem to work for all the examples.

What about a regex?

.*(/|[a-zA-Z]+\?)(.*)

then get that last subexpression (.*), I believe it's $+ in .Net, I'm not sure

Ignore Duplicates and Create New List of Unique Values in Excel

I have a list of color names in range A2:A8, in column B I want to extract a distinct list of color names.

Follow the below given steps:

  • Select the Cell B2; write the formula to retrieve the unique values from a list.
  • =IF(COUNTIF(A$2:A2,A2)=1,A2,””)
  • Press Enter on your keyboard.
  • The function will return the name of the first color.
  • To return the value for the rest of cells, copy the same formula down. To copy formula in range B3:B8, copy the formula in cell B2 by pressing the key CTRL+C on your keyboard and paste in the range B3:B8 by pressing the key CTRL+V.
  • Here you can see the output where we have the unique list of color names.

How to filter in NaN (pandas)?

Simplest of all solutions:

filtered_df = df[df['var2'].isnull()]

This filters and gives you rows which has only NaN values in 'var2' column.

IIS Request Timeout on long ASP.NET operation

Great and exhaustive answerby @Kev!

Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location> tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.

Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut is in minutes, while the request executionTimeout is in seconds!

And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).

<configuration>
    ... 
    <compilation debug="false" ...>
    ... other stuff ..

    <location path="~/Admin/SomePage.aspx">
        <system.web>
            <sessionState timeout="240" />
            <httpRuntime executionTimeout="14400" />
        </system.web>
    </location>
    ...
</configuration>

Simple dynamic breadcrumb

Here is a great simple dynamic breadcrumb (tweak as needed):

    <?php 
    $docroot = "/zen/index5.php";
    $path =($_SERVER['REQUEST_URI']);
    $names = explode("/", $path); 
    $trimnames = array_slice($names, 1, -1);
    $length = count($trimnames)-1;
    $fixme = array(".php","-","myname");
    $fixes = array(""," ","My<strong>Name</strong>");
    echo '<div id="breadwrap"><ol id="breadcrumb">';
    $url = "";
    for ($i = 0; $i <= $length;$i++){
    $url .= $trimnames[$i]."/";
        if($i>0 && $i!=$length){
            echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>';
    }
    elseif ($i == $length){
        echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>';       
    }
    else{
        echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span>&nbsp;</span></a></li>';
    }
}
echo '</ol>';
?>

How do I set the figure title and axes labels font size in Matplotlib?

To only modify the title's font (and not the font of the axis) I used this:

import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})

The fontdict accepts all kwargs from matplotlib.text.Text.

Throw keyword in function's signature

Well, while googling about this throw specification, I had a look at this article :- (http://blogs.msdn.com/b/larryosterman/archive/2006/03/22/558390.aspx)

I am reproducing a part of it here also, so that it can be used in future irrespective of the fact that the above link works or not.

   class MyClass
   {
    size_t CalculateFoo()
    {
        :
        :
    };
    size_t MethodThatCannotThrow() throw()
    {
        return 100;
    };
    void ExampleMethod()
    {
        size_t foo, bar;
        try
        {
            foo = CalculateFoo();
            bar = foo * 100;
            MethodThatCannotThrow();
            printf("bar is %d", bar);
        }
        catch (...)
        {
        }
    }
};

When the compiler sees this, with the "throw()" attribute, the compiler can completely optimize the "bar" variable away, because it knows that there is no way for an exception to be thrown from MethodThatCannotThrow(). Without the throw() attribute, the compiler has to create the "bar" variable, because if MethodThatCannotThrow throws an exception, the exception handler may/will depend on the value of the bar variable.

In addition, source code analysis tools like prefast can (and will) use the throw() annotation to improve their error detection capabilities - for example, if you have a try/catch and all the functions you call are marked as throw(), you don't need the try/catch (yes, this has a problem if you later call a function that could throw).

Concatenate multiple result rows of one column into one, group by another column

You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

MOVIE ACTOR
A 1,2,3
B 4

See this SQLFiddle

For more See 9.18. Aggregate Functions

How to ignore a property in class if null, using json.net

With System.Text.Json and .NET Core 3.0 this worked for me:

var jsonSerializerOptions = new JsonSerializerOptions()
{
    IgnoreNullValues = true
};
var myJson = JsonSerializer.Serialize(myObject, jsonSerializerOptions );

Does :before not work on img elements?

Due to the nature of <img> being a replaced element, document styling doesn’t affected it.

To reference it anyway, <picture> provides an ideal, native wrapper that can have pseudo-elements attached to it, like so:

_x000D_
_x000D_
img:after, picture:after{_x000D_
    content:"\1F63B";_x000D_
    font-size:larger;_x000D_
    margin:-1em;_x000D_
}
_x000D_
<img src="//placekitten.com/110/80">_x000D_
_x000D_
<picture>_x000D_
    <img src="//placekitten.com/110/80">_x000D_
</picture>
_x000D_
_x000D_
_x000D_

How to get the clicked link's href with jquery?

this in your callback function refers to the clicked element.

   $(".addressClick").click(function () {
        var addressValue = $(this).attr("href");
        alert(addressValue );
    });

What is the Eclipse shortcut for "public static void main(String args[])"?

Alternately, you can start a program containing the line with one click.

Just select the method stub for it when creating the new Java class, where the code says,

Which method stubs would you like to create?

[check-box] public static void main(String[]args) <---- Select this one.

[check-box] Constructors from superclass

[check-box] Inherited abstract methods

List append() in for loop

You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = []
for i in range(5):    
    a.append(i)
print(a)

is all you need. This works because lists are mutable.

Also see the docs on data structures.

How to access elements of a JArray (or iterate over them)

There is a much simpler solution for that.
Actually treating the items of JArray as JObject works.
Here is an example:
Let's say we have such array of JSON objects:

JArray jArray = JArray.Parse(@"[
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              }]");

To get access each item we just do the following:

foreach (JObject item in jArray)
{
    string name = item.GetValue("name").ToString();
    string url = item.GetValue("url").ToString();
    // ...
}

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

you just use the following code

var response= $(result);

$(response).find("#id/.class").html(); [or] $($(result)).find("#id/.class").html();

SQL- Ignore case while searching for a string

Like this.

SELECT DISTINCT COL_NAME FROM myTable WHERE COL_NAME iLIKE '%Priceorder%'

In postgresql.

How to select a node of treeview programmatically in c#?

Apologies for my previously mixed up answer.

Here is how to do:

myTreeView.SelectedNode = myTreeNode;

(Update)

I have tested the code below and it works:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        treeView1.Nodes.Add("1", "1");
        treeView1.Nodes.Add("2", "2");
        treeView1.Nodes[0].Nodes.Add("1-1", "1-1");
        TreeNode treeNode = treeView1.Nodes[0].Nodes.Add("1-2", "1-3");
        treeView1.SelectedNode = treeNode;
        MessageBox.Show(treeNode.IsSelected.ToString());
    }


}

How do I tell if .NET 3.5 SP1 is installed?

Look at HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\. One of these must be true:

  • The Version value in that key should be 3.5.30729.01
  • Or the SP value in the same key should be 1

In C# (taken from the first comment), you could do something along these lines:

const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);
var version = subKey.GetValue("Version").ToString();
var servicePack = subKey.GetValue("SP").ToString();

Error - Unable to access the IIS metabase

I'm using Win 8 Pro and VS 2013. After trying everything in this page... I simply reinstalled IIS Express 8 and everything works fine now (even without running as an admin).

My conclusion is that this is a rather generic error and there are multiple root causes.

Remove characters from a string

ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,) from telephone number:

var str = "+(48) 123-456-789".replace(/[-+()\s]/g, '');  // result: "48123456789"

We use regular expression [-+()\s] where we put unwanted characters between [ and ]

(the "\s" is 'space' character escape - for more info google 'character escapes in in regexp')

List of all unique characters in a string?

Use an OrderedDict. This will ensure that the order is preserved

>>> ''.join(OrderedDict.fromkeys( "aaabcabccd").keys())
'abcd'

PS: I just timed both the OrderedDict and Set solution, and the later is faster. If order does not matter, set should be the natural solution, if Order Matter;s this is how you should do.

>>> from timeit import Timer
>>> t1 = Timer(stmt=stmt1, setup="from __main__ import data, OrderedDict")
>>> t2 = Timer(stmt=stmt2, setup="from __main__ import data")
>>> t1.timeit(number=1000)
1.2893918431815337
>>> t2.timeit(number=1000)
0.0632140599081196

OnClickListener in Android Studio

Button button= (Button) findViewById(R.id.standingsButton);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        startActivity(new Intent(MainActivity.this,StandingsActivity.class));
    }
});

This code is not in any method. If you want to use it, it must be within a method like OnCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button= (Button) findViewById(R.id.standingsButton);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
        }
    });
}

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

In Wordpress just replace

$(function(){...});

with

jQuery(function(){...});