Programs & Examples On #Add on

Add-on, a.k.a. Plug-in is a set of components that enhances the existing, or adds new capabilities to a software application.

Recommended add-ons/plugins for Microsoft Visual Studio

For C# development I use:

  • ReSharper, heavily customized and with a couple dozen custom actions I wrote (not to mention weird but wonderful Live Templates)
  • GhostDoc - very useful for postprocessing of generated code
  • Source Code Outliner
  • P/factor (a set of internally developed code gen tools for VS) - see example here
  • CodeGenUtils - another internal dev for code generation, available on CodePlex
  • SharpWizard - a VS add-in for rapid prototyping. Supports advanced generation of interface support, operators, patterns, metadata.
  • Dependency Analyser - a really nifty tool (another internal dev.) for identifying dependencies between CLR properties. Useful for autogenerating change notifications based on dependency graphs.

In addition to these, I also have a couple of DSL graphical designers for the particularly difficult scenarios - for example, I have a DSL for complex multithreaded operations that are implemented using Pulse & Wait.

How to pull specific directory with git

It's not possible. You need pull all repository or nothing.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

There is an other weird reason this happens. If you have a file called pandas.py or a directory called pandas in the same or nested levels, that library is used instead and fails to work. Rename the folder and restart the env and it started working. Faced this

Difference between Convert.ToString() and .ToString()

  • Convert.Tostring() basically just calls the following value == null ? String.Empty: value.ToString()

  • (string)variable will only cast when there is an implicit or explicit operator on what you are casting

  • ToString() can be overriden by the type (it has control over what it does), if not it results in the name of the type

Obviously if an object is null, you can't access the instance member ToString(), it will cause an exception

Extract file basename without path and extension in bash

If you want to play nice with Windows file paths (under Cygwin) you can also try this:

fname=${fullfile##*[/|\\]}

This will account for backslash separators when using BaSH on Windows.

jquery find element by specific class when element has multiple classes

An element can have any number of classNames, however, it can only have one class attribute; only the first one will be read by jQuery.

Using the code you posted, $(".alert-box.warn") will work but $(".alert-box.dead") will not.

How to get cookie's expire time

To get cookies expire time, use this simple method.

<?php

//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;

//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);

//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){

    return ($sec / 60 / 60 / 24);

}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){

    echo "Cookie is set<br />";
    if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
        echo "Cookie will expire today.";
    }else{
        echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
    }

}else{
    echo "not set...";
}

?>

You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

The problem lays here:

--This result set has 3 columns
select LOC_id,LOC_locatie,LOC_deelVan_LOC_id from tblLocatie t
where t.LOC_id = 1 -- 1 represents an example

union all

--This result set has 1 columns   
select t.LOC_locatie + '>' from tblLocatie t
inner join q parent on parent.LOC_id = t.LOC_deelVan_LOC_id

In order to use union or union all number of columns and their types should be identical cross all result sets.

I guess you should just add the column LOC_deelVan_LOC_id to your second result set

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

Try this may will help you.Go to "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.

Please add a @Pipe/@Directive/@Component annotation. Error

If you are exporting another class in that module, make sure that it is not in between @Component and your ClassComponent. For example:

@Component({ ... })

export class ExampleClass{}

export class ComponentClass{}  --> this will give this error.

FIX:

export class ExampleClass{}

@Component ({ ... })

export class ComponentClass{}

Windows Application has stopped working :: Event Name CLR20r3

Some times this problem arise when Application is build in one PC and try to run another PC. And also build the application with Visual Studio 2010.I have the following problem

Problem Description
    Stop Working
Problem Signature
  Problem Event Name:   CLR20r3
  Problem Signature 01: diagnosticcentermngr.exe
  Problem Signature 02: 1.0.0.0
  Problem Signature 03: 4f8c1772
  Problem Signature 04: System.Drawing
  Problem Signature 05: 2.0.0.0
  Problem Signature 06: 4a275e83
  Problem Signature 07: 7af
  Problem Signature 08: 6c
  Problem Signature 09: System.ArgumentException
  OS Version:   6.1.7600.2.0.0.256.1
  Locale ID:    1033

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

Dont worry, Please check out following link and install .net framework 4.Although my application .net properties was .net framework 2.

http://www.microsoft.com/download/en/details.aspx?id=17718

restart your PC and try again.

Cut off text in string after/before separator in powershell

This does work for a specific delimiter for a specific amount of characters between the delimiter. I had many issues attempting to use this in a for each loop where the position changed but the delimiter was the same. For example I was using the backslash as the delimiter and wanted to only use everything to the right of the backslash. The issue was that once the position was defined (71 characters from the beginning) it would use $pos as 71 every time regardless of where the delimiter actually was in the script. I found another method of using a delimiter and .split to break things up then used the split variable to call the sections For instance the first section was $variable[0] and the second section was $variable[1].

How to redirect to action from JavaScript method?

Use the @Url.Action method. This will work and determines the correct route regardless of what IIS server you deploy to.

Example- window.location.href="@Url.Action("Action", "Controller")";

so in the case of the Index action on the Home controller - window.location.href="@Url.Action("Index", "Home")";

How to send a "multipart/form-data" with requests in python?

Here is the python snippet you need to upload one large single file as multipart formdata. With NodeJs Multer middleware running on the server side.

import requests
latest_file = 'path/to/file'
url = "http://httpbin.org/apiToUpload"
files = {'fieldName': open(latest_file, 'rb')}
r = requests.put(url, files=files)

For the server side please check the multer documentation at: https://github.com/expressjs/multer here the field single('fieldName') is used to accept one single file, as in:

var upload = multer().single('fieldName');

How to make a phone call using intent in Android?

For making a call activity using intents, you should request the proper permissions.

For that you include uses permissions in AndroidManifest.xml file.

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

Then include the following code in your activity

if (ActivityCompat.checkSelfPermission(mActivity,
        Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
    //Creating intents for making a call
    Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:123456789"));
    mActivity.startActivity(callIntent);

}else{
    Toast.makeText(mActivity, "You don't assign permission.", Toast.LENGTH_SHORT).show();
}

How do I trim leading/trailing whitespace in a standard way?

Late to the trim party

Features:
1. Trim the beginning quickly, as in a number of other answers.
2. After going to the end, trimming the right with only 1 test per loop. Like @jfm3, but works for an all white-space string)
3. To avoid undefined behavior when char is a signed char, cast *s to unsigned char.

Character handling "In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined." C11 §7.4 1

#include <ctype.h>

// Return a pointer to the trimmed string
char *string_trim_inplace(char *s) {
  while (isspace((unsigned char) *s)) s++;
  if (*s) {
    char *p = s;
    while (*p) p++;
    while (isspace((unsigned char) *(--p)));
    p[1] = '\0';
  }

  // If desired, shift the trimmed string

  return s;
}

@chqrlie commented the above does not shift the trimmed string. To do so....

// Return a pointer to the (shifted) trimmed string
char *string_trim_inplace(char *s) {
  char *original = s;
  size_t len = 0;

  while (isspace((unsigned char) *s)) {
    s++;
  } 
  if (*s) {
    char *p = s;
    while (*p) p++;
    while (isspace((unsigned char) *(--p)));
    p[1] = '\0';
    // len = (size_t) (p - s);   // older errant code
    len = (size_t) (p - s + 1);  // Thanks to @theriver
  }

  return (s == original) ? s : memmove(original, s, len + 1);
}

Uninstalling an MSI file from the command line without using msiexec

wmic product get name

Just gets the cmd stuck... still flashing _ after a couple minutes

in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, if you can find the folder with the software name you are trying to install (not the one named with ProductCode), the UninstallString points to the application's own uninstaller C:\Program Files\Zune\ZuneSetup.exe /x

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

With CMake it would just be

add_compile_definitions(_USE_MATH_DEFINES)

in CMakeLists.txt.

Post-increment and Pre-increment concept?

The difference between the postfix increment, x++, and the prefix increment, ++x, is precisely in how the two operators evaluate their operands. The postfix increment conceptually copies the operand in memory, increments the original operand and finally yields the value of the copy. I think this is best illustrated by implementing the operator in code:

int operator ++ (int& n)  // postfix increment
{
    int tmp = n;
    n = n + 1;
    return tmp;
}

The above code will not compile because you can't re-define operators for primitive types. The compiler also can't tell here we're defining a postfix operator rather than prefix, but let's pretend this is correct and valid C++. You can see that the postfix operator indeed acts on its operand, but it returns the old value prior to the increment, so the result of the expression x++ is the value prior to the increment. x, however, is incremented.

The prefix increment increments its operand as well, but it yields the value of the operand after the increment:

int& operator ++ (int& n)
{
    n = n + 1;
    return n;
}

This means that the expression ++x evaluates to the value of x after the increment.

It's easy to think that the expression ++x is therefore equivalent to the assignmnet (x=x+1). This is not precisely so, however, because an increment is an operation that can mean different things in different contexts. In the case of a simple primitive integer, indeed ++x is substitutable for (x=x+1). But in the case of a class-type, such as an iterator of a linked list, a prefix increment of the iterator most definitely does not mean "adding one to the object".

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

Validating parameters to a Bash script

#!/bin/sh
die () {
    echo >&2 "$@"
    exit 1
}

[ "$#" -eq 1 ] || die "1 argument required, $# provided"
echo $1 | grep -E -q '^[0-9]+$' || die "Numeric argument required, $1 provided"

while read dir 
do
    [ -d "$dir" ] || die "Directory $dir does not exist"
    rm -rf "$dir"
done <<EOF
~/myfolder1/$1/anotherfolder 
~/myfolder2/$1/yetanotherfolder 
~/myfolder3/$1/thisisafolder
EOF

edit: I missed the part about checking if the directories exist at first, so I added that in, completing the script. Also, have addressed issues raised in comments; fixed the regular expression, switched from == to eq.

This should be a portable, POSIX compliant script as far as I can tell; it doesn't use any bashisms, which is actually important because /bin/sh on Ubuntu is actually dash these days, not bash.

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

Have a look at Determine and count unique values of an array.

Or, to count the number of occurrences of 5, simply do

sum(your_matrix == 5)

Parsing xml using powershell

If you want to start with a file you can do this

[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName

Use PowerShell to Parse an XML File

Chart.js canvas resize

I was having the same problem. I was able to solve it by setting option:

_x000D_
_x000D_
responsive: false,_x000D_
maintainAspectRatio: true,_x000D_
showScale: false,
_x000D_
_x000D_
_x000D_

And in css, set the width of the container div the same as the canvas:

_x000D_
_x000D_
    #canvasContainer { _x000D_
      width: 300px;_x000D_
    }_x000D_
    _x000D_
    canvas {_x000D_
      width: 300px;_x000D_
    }
_x000D_
_x000D_
_x000D_

Checking if a worksheet-based checkbox is checked

Building on the previous answers, you can leverage the fact that True is -1 and False is 0 and shorten your code like this:

Sub Button167_Click()
  Range("Y12").Value = _
    Abs(Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0)
End Sub

If the checkbox is checked, .Value = 1.

Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0 returns True.

Applying the Abs function converts True to 1.

If the checkbox is unchecked, .Value = -4146.

Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0 returns False.

Applying the Abs function converts False to 0.

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

To make it work you have to replace a run this line of code serviceMetadata httpGetEnabled="true"/> http instead of https and security mode="None" />

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

How to dynamically add elements to String array?

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

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

I have been suffering of this issue for very long time. I was unable to open websites like GitHub. I almost tried all the answer on web and not anyone worked. Tried to reinstall chrome also. I found the solution for this from our network guy and it worked. There is a fix in registry which will resolve this error for permanent basis.

  1. Press Windows+R key to open run dialogue box
  2. type : regeditand press enter to open registry
  3. In the tree view at left click through following path HKEY_LOCAL_MACHINE > SOFTWARE > POLICIES > Microsoft > SystemCertificate > Authroot
  4. Now double click on DisableRootAutoUpdate on the right and set it to 0(zero) in the dialogue box appearing
  5. Restart your PC to apply registry changes and you will not get this error anymore

The solution above is for Windows 8. It is almost identical in later versions but i’m not sure for earlier versions like XP and vista. So that needs to be checked.

NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

  • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
  • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
  • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
  • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
  • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
  • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
  • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

Angular 2 Show and Hide an element

When you don't care about removing the Html Dom-Element, use *ngIf.

Otherwise, use this:

<div [style.visibility]="(numberOfUnreadAlerts == 0) ? 'hidden' : 'visible' ">
   COUNTER: {{numberOfUnreadAlerts}} 
</div>

How to set the width of a RaisedButton in Flutter?

Use Media Query to use width wisely for your solution which will run the same for small and large screen

  Container(
            width: MediaQuery.of(context).size.width * 0.5, // Will take 50% of screen space
            child: RaisedButton(
              child: Text('Go to screen two'),
              onPressed: () => null
            ),
          )

You can apply similar solution to SizeBox also.

When to use Interface and Model in TypeScript / Angular

Use Class instead of Interface that is what I discovered after all my research.

Why? A class alone is less code than a class-plus-interface. (anyway you may require a Class for data model)

Why? A class can act as an interface (use implements instead of extends).

Why? An interface-class can be a provider lookup token in Angular dependency injection.

from Angular Style Guide

Basically a Class can do all, what an Interface will do. So may never need to use an Interface.

How to initialize struct?

Structure types should, whenever practical, either have all of their state encapsulated in public fields which may independently be set to any values which are valid for their respective type, or else behave as a single unified value which can only bet set via constructor, factory, method, or else by passing an instance of the struct as an explicit ref parameter to one of its public methods. Contrary to what some people claim, that there's nothing wrong with a struct having public fields, if it is supposed to represent a set of values which may sensibly be either manipulated individually or passed around as a group (e.g. the coordinates of a point). Historically, there have been problems with structures that had public property setters, and a desire to avoid public fields (implying that setters should be used instead) has led some people to suggest that mutable structures should be avoided altogether, but fields do not have the problems that properties had. Indeed, an exposed-field struct is the ideal representation for a loose collection of independent variables, since it is just a loose collection of variables.

In your particular example, however, it appears that the two fields of your struct are probably not supposed to be independent. There are three ways your struct could sensibly be designed:

  • You could have the only public field be the string, and then have a read-only "helper" property called length which would report its length if the string is non-null, or return zero if the string is null.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have the contents of the only field--a private string--be specified in the object's constructor. As above, length would be a property that would report the length of the stored string.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have two private fields: one for the string and one for the length, both of which would be set in a constructor that takes a string, stores it, measures its length, and stores that. Determining the length of a string is sufficiently fast that it probably wouldn't be worthwhile to compute and cache it, but it might be useful to have a structure that combined a string and its GetHashCode value.

It's important to be aware of a detail with regard to the third design, however: if non-threadsafe code causes one instance of the structure to be read while another thread is writing to it, that may cause the accidental creation of a struct instance whose field values are inconsistent. The resulting behaviors may be a little different from those that occur when classes are used in non-threadsafe fashion. Any code having anything to do with security must be careful not to assume that structure fields will be in a consistent state, since malicious code--even in a "full trust" enviroment--can easily generate structs whose state is inconsistent if that's what it wants to do.

PS -- If you wish to allow your structure to be initialized using an assignment from a string, I would suggest using an implicit conversion operator and making Length be a read-only property that returns the length of the underlying string if non-null, or zero if the string is null.

Using JQuery to open a popup window and print

You should put the print function in your view-details.php file and call it once the file is loaded, by either using

<body onload="window.print()"> 

or

$(document).ready(function () { 
  window.print(); 
});

How to avoid precompiled headers

You can always disable the use of pre-compiled headers in the project settings.

Instructions for VS 2010 (should be similar for other versions of VS):

Select your project, use the "Project -> Properties" menu and go to the "Configuration Properties -> C/C++ -> Precompiled Headers" section, then change the "Precompiled Header" setting to "Not Using Precompiled Headers" option.


If you are only trying to setup a minimal Visual Studio project for simple C++ command-line programs (such as those developed in introductory C++ programming classes), you can create an empty C++ project.

Java - Get a list of all Classes loaded in the JVM

From Oracle doc you can use -Xlog option that has a possibility to write into file.

java -Xlog:class+load=info:classloaded.txt

Is Secure.ANDROID_ID unique for each device?

I've read a few things about this and unfortunately the ANDROID_ID should not be relied on for uniquely identifying an individual device.

It doesn't seem to be enforced in Android compliance requirements and so manufacturers seem to implement it the way they choose including some using it more as a 'model' ID etc.

Also, be aware that even if a manufacturer has written a generator to make it a UUID (for example), it's not guaranteed to survive a factory reset.

Pass a local file in to URL in Java

new URL("file:///your/file/here")

How to build a RESTful API?

In 2013, you should use something like Silex or Slim

Silex example:

require_once __DIR__.'/../vendor/autoload.php'; 

$app = new Silex\Application(); 

$app->get('/hello/{name}', function($name) use($app) { 
    return 'Hello '.$app->escape($name); 
}); 

$app->run(); 

Slim example:

$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
    echo "Hello, $name";
});
$app->run();

Getting all request parameters in Symfony 2

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

static constructors in C++? I need to initialize private static objects

Wow, I can't believe no one mentioned the most obvious answer, and one that most closely mimics C#'s static-constructor behavior, i.e. it doesn't get called until the first object of that type is created.

std::call_once() is available in C++11; if you can't use that, it can be done with a static boolean class-variable, and a compare-and-exchange atomic-operation. In your constructor, see if you can atomically change the class-static flag from false to true, and if so, you can run the static-construction code.

For extra credit, make it a 3-way flag instead of a boolean, i.e. not run, running, and done running. Then all other instances of that class can spin-lock until the instance running the static-constructor has finished (i.e. issue a memory-fence, then set the state to "done running"). Your spin-lock should execute the processor's "pause" instruction, double the wait each time up until a threshold, etc. — pretty standard spin-locking technique.

In the absence of C++11, this should get you started.

Here's some pseudocode to guide you. Put this in your class definition:

enum EStaticConstructor { kNotRun, kRunning, kDone };
static volatile EStaticConstructor sm_eClass = kNotRun;

And this in your constructor:

while (sm_eClass == kNotRun)
{
    if (atomic_compare_exchange_weak(&sm_eClass, kNotRun, kRunning))
    {
        /* Perform static initialization here. */

        atomic_thread_fence(memory_order_release);
        sm_eClass = kDone;
    }
}
while (sm_eClass != kDone)
    atomic_pause();

How to have Java method return generic list of any type?

private Object actuallyT;

public <T> List<T> magicalListGetter(Class<T> klazz) {
    List<T> list = new ArrayList<>();
    list.add(klazz.cast(actuallyT));
    try {
        list.add(klazz.getConstructor().newInstance()); // If default constructor
    } ...
    return list;
}

One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (klazz.getConstructor().newInstance()).

Check if int is between two numbers

It's just the syntax. '<' is a binary operation, and most languages don't make it transitive. They could have made it like the way you say, but then somebody would be asking why you can't do other operations in trinary as well. "if (12 < x != 5)"?

Syntax is always a trade-off between complexity, expressiveness and readability. Different language designers make different choices. For instance, SQL has "x BETWEEN y AND z", where x, y, and z can individually or all be columns, constants, or bound variables. And I'm happy to use it in SQL, and I'm equally happy not to worry about why it's not in Java.

HTTP URL Address Encoding in Java

Maybe can try UriUtils in org.springframework.web.util

UriUtils.encodeUri(input, "UTF-8")

Concatenating bits in VHDL

You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:

process(b0,b1,b2,b3)
   variable bcat : std_logic_vector(0 to 3);
begin
   bcat := b0 & b1 & b2 & b3;
   case bcat is
      when "0000" => x <= 1;
      when others => x <= 2;
   end case;
end process;

Adding placeholder text to textbox

Attached properties to the rescue:

public static class TextboxExtensions
{
    public static readonly DependencyProperty PlaceholderProperty = 
        DependencyProperty.RegisterAttached(
            "Placeholder", 
            typeof(string), 
            typeof(TextboxExtensions), 
            new PropertyMetadata(default(string), propertyChangedCallback: PlaceholderChanged)
            );

    private static void PlaceholderChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        var tb = dependencyObject as TextBox;

        if (tb == null)
            return;

        tb.LostFocus -= OnLostFocus;
        tb.GotFocus -= OnGotFocus;

        if (args.NewValue != null)
        {
            tb.GotFocus += OnGotFocus;
            tb.LostFocus += OnLostFocus;
        }

        SetPlaceholder(dependencyObject, args.NewValue as string);

        if (!tb.IsFocused)
            ShowPlaceholder(tb);
    }

    private static void OnLostFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        ShowPlaceholder(sender as TextBox);
    }

    private static void OnGotFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        HidePlaceholder(sender as TextBox);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static void SetPlaceholder(DependencyObject element, string value)
    {
        element.SetValue(PlaceholderProperty, value);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static string GetPlaceholder(DependencyObject element)
    {
        return (string)element.GetValue(PlaceholderProperty);
    }

    private static void ShowPlaceholder(TextBox textBox)
    {
        if (string.IsNullOrWhiteSpace(textBox.Text))
        {
            textBox.Text = GetPlaceholder(textBox);
        }
    }

    private static void HidePlaceholder(TextBox textBox)
    {
        string placeholderText = GetPlaceholder(textBox);

        if (textBox.Text == placeholderText)
            textBox.Text = string.Empty;
    }
}

Usage:

<TextBox Text="hi" local:TextboxExtensions.Placeholder="Hello there"></TextBox>

Inserting a Python datetime.datetime object into MySQL

Use Python method datetime.strftime(format), where format = '%Y-%m-%d %H:%M:%S'.

import datetime

now = datetime.datetime.utcnow()

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, %s)",
               ("name", 4, now.strftime('%Y-%m-%d %H:%M:%S')))

Timezones

If timezones are a concern, the MySQL timezone can be set for UTC as follows:

cursor.execute("SET time_zone = '+00:00'")

And the timezone can be set in Python:

now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)

MySQL Documentation

MySQL recognizes DATETIME and TIMESTAMP values in these formats:

As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012@12@31 11^30^45' are equivalent.

The only delimiter recognized between a date and time part and a fractional seconds part is the decimal point.

The date and time parts can be separated by T rather than a space. For example, '2012-12-31 11:30:45' '2012-12-31T11:30:45' are equivalent.

As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date. For example, '20070523091528' and '070523091528' are interpreted as '2007-05-23 09:15:28', but '071122129015' is illegal (it has a nonsensical minute part) and becomes '0000-00-00 00:00:00'.

As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.

ApiNotActivatedMapError for simple html page using google-places-api

To enable Api do this

  1. Go to API Manager
  2. Click on Overview
  3. Search for Google Maps JavaScript API(Under Google Maps APIs). Click on that
  4. You will find Enable button there. Click to enable API.

OR You can try this url: Maps JavaScript API

Hope this will solve the problem of enabling API.

Getting URL hash location, and using it in jQuery

I would suggest better cek first if the current page has a hash. Otherwise it will be undefined.

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});

Why do we use web.xml?

Generally speaking, this is the configuration file of web applications in java. It instructs the servlet container (tomcat for ex.) which classes to load, what parameters to set in the context, and how to intercept requests coming from browsers.

There you specify:

  • what servlets (and filters) you want to use and what URLs you want to map them to
  • listeners - classes that are notified when some events happen (context starts, session created, etc)
  • configuration parameters (context-params)
  • error pages, welcome files
  • security constraints

In servlet 3.0 many of the web.xml parts are optional. These configurations can be done via annotations (@WebServlet, @WebListener)

NoClassDefFoundError on Maven dependency

This is due to Morphia jar not being part of your output war/jar. Eclipse or local build includes them as part of classpath, but remote builds or auto/scheduled build don't consider them part of classpath.

You can include dependent jars using plugin.

Add below snippet into your pom's plugins section

    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>

How to configure socket connect timeout

I worked with Unity and had some problem with the BeginConnect and other async methods from socket.

There is something than I don't understand but the code samples before doesn't work for me.

So I wrote this piece of code to make it work. I test it on an adhoc network with android and pc, also in local on my computer. Hope it can help.

using System.Net.Sockets;
using System.Threading;
using System.Net;
using System;
using System.Diagnostics;

class ConnexionParameter : Guardian
{
    public TcpClient client;
    public string address;
    public int port;
    public Thread principale;
    public Thread thisthread = null;
    public int timeout;

    private EventWaitHandle wh = new AutoResetEvent(false);

    public ConnexionParameter(TcpClient client, string address, int port, int timeout, Thread principale)
    {
        this.client = client;
        this.address = address;
        this.port = port;
        this.principale = principale;
        this.timeout = timeout;
        thisthread = new Thread(Connect);
    }


    public void Connect()
    {
        WatchDog.Start(timeout, this);
        try
        {
            client.Connect(IPAddress.Parse(address), port);

        }
        catch (Exception)
        {
            UnityEngine.Debug.LogWarning("Unable to connect service (Training mode? Or not running?)");
        }
        OnTimeOver();
        //principale.Resume();
    }

    public bool IsConnected = true;
    public void OnTimeOver()
    {
        try
        {
            if (!client.Connected)
            {
                    /*there is the trick. The abort method from thread doesn't
 make the connection stop immediately(I think it's because it rise an exception
 that make time to stop). Instead I close the socket while it's trying to
 connect , that make the connection method return faster*/
                IsConnected = false;

                client.Close();
            }
            wh.Set();

        }
        catch(Exception)
        {
            UnityEngine.Debug.LogWarning("Connexion already closed, or forcing connexion thread to end. Ignore.");
        }
    }


    public void Start()
    {

        thisthread.Start();
        wh.WaitOne();
        //principale.Suspend();
    }

    public bool Get()
    {
        Start();
        return IsConnected;
    }
}


public static class Connexion
{


    public static bool Connect(this TcpClient client, string address, int port, int timeout)
    {
        ConnexionParameter cp = new ConnexionParameter(client, address, port, timeout, Thread.CurrentThread);
        return cp.Get();
    }

//http://stackoverflow.com/questions/19653588/timeout-at-acceptsocket
    public static Socket AcceptSocket(this TcpListener tcpListener, int timeoutms, int pollInterval = 10)
    {
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutms);
        var stopWatch = new Stopwatch();
        stopWatch.Start();
        while (stopWatch.Elapsed < timeout)
        {
            if (tcpListener.Pending())
                return tcpListener.AcceptSocket();

            Thread.Sleep(pollInterval);
        }
        return null;
    }


}

and there a very simple watchdog on C# to make it work:

using System.Threading;

public interface Guardian
{
    void OnTimeOver();
}

public class WatchDog {

    int m_iMs;
    Guardian m_guardian;

    public WatchDog(int a_iMs, Guardian a_guardian)
    {
        m_iMs = a_iMs;
        m_guardian = a_guardian;
        Thread thread = new Thread(body);
        thread.Start(this);
    }


    private void body(object o)
    {
        WatchDog watchdog = (WatchDog)o;
        Thread.Sleep(watchdog.m_iMs);
        watchdog.m_guardian.OnTimeOver();
    }

    public static void Start(int a_iMs, Guardian a_guardian)
    {
        new WatchDog(a_iMs, a_guardian);
    }
}

Android ADB stop application command like "force-stop" for non rooted device

If you want to kill the Sticky Service,the following command NOT WORKING:

adb shell am force-stop <PACKAGE>
adb shell kill <PID>

The following command is WORKING:

adb shell pm disable <PACKAGE>

If you want to restart the app,you must run command below first:

adb shell pm enable <PACKAGE>

jQuery: Slide left and slide right

If you don't want something bloated like jQuery UI, try my custom animations: https://github.com/yckart/jquery-custom-animations

For you, blindLeftToggle and blindRightToggle is the appropriate choice.

http://jsfiddle.net/ARTsinn/65QsU/

Difference between maven scope compile and provided for JAR packaging

If jar file is like executable spring boot jar file then scope of all dependencies must be compile to include all jar files.

But if jar file used in other packages or applications then it does not need to include all dependencies in jar file because these packages or applications can provide other dependencies themselves.

Call removeView() on the child's parent first

In onCreate with activity or in onCreateView with fragment.

 if (view != null) {
    ViewGroup parent = (ViewGroup) view.getParent();
    if (parent != null) {
        parent.removeView(view);
    }
}
try {
    view = inflater.inflate(R.layout.fragment_main, container, false);
} catch (InflateException e) {

}

Why extend the Android Application class?

I think you can use the Application class for many things, but they are all tied to your need to do some stuff BEFORE any of your Activities or Services are started. For instance, in my application I use custom fonts. Instead of calling

Typeface.createFromAsset()

from every Activity to get references for my fonts from the Assets folder (this is bad because it will result in memory leak as you are keeping a reference to assets every time you call that method), I do this from the onCreate() method in my Application class:

private App appInstance;
Typeface quickSandRegular;
...
public void onCreate() {
    super.onCreate();

    appInstance = this;
    quicksandRegular = Typeface.createFromAsset(getApplicationContext().getAssets(),
                       "fonts/Quicksand-Regular.otf");
   ...
   }

Now, I also have a method defined like this:

public static App getAppInstance() {
    return appInstance;
}

and this:

public Typeface getQuickSandRegular() {
    return quicksandRegular;
}

So, from anywhere in my application, all I have to do is:

App.getAppInstance().getQuickSandRegular()

Another use for the Application class for me is to check if the device is connected to the Internet BEFORE activities and services that require a connection actually start and take necessary action.

Python 3 turn range to a list

Python 3:

my_list = [*range(1001)]

Entity Framework Core add unique constraint code-first

Also if you want to create Unique constrains on multiple columns you can simply do this (following @Sampath's link)

class MyContext : DbContext
{
    public DbSet<Person> People { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .HasIndex(p => new { p.FirstName, p.LastName })
            .IsUnique(true);
    }
}

public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

How to concat string + i?

Try the following:

for i = 1:4
    result = strcat('f',int2str(i));
end

If you use this for naming several files that your code generates, you are able to concatenate more parts to the name. For example, with the extension at the end and address at the beginning:

filename = strcat('c:\...\name',int2str(i),'.png'); 

Search for a string in Enum and return the Enum

As mentioned in previous answers, you can cast directly to the underlying datatype (int -> enum type) or parse (string -> enum type).

but beware - there is no .TryParse for enums, so you WILL need a try/catch block around the parse to catch failures.

How to use a wildcard in the classpath to add multiple jars?

If you mean that you have an environment variable named CLASSPATH, I'd say that's your mistake. I don't have such a thing on any machine with which I develop Java. CLASSPATH is so tied to a particular project that it's impossible to have a single, correct CLASSPATH that works for all.

I set CLASSPATH for each project using either an IDE or Ant. I do a lot of web development, so each WAR and EAR uses their own CLASSPATH.

It's ignored by IDEs and app servers. Why do you have it? I'd recommend deleting it.

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

Number of days between two dates in Joda-Time

The accepted answer builds two LocalDate objects, which are quite expensive if you are reading lot of data. I use this:

  public static int getDaysBetween(DateTime earlier, DateTime later)
  {
    return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
  }

By calling getMillis() you use already existing variables.
MILLISECONDS.toDays() then, uses a simple arithmetic calculation, does not create any object.

how to change listen port from default 7001 to something different?

As my experience, you can add another domain which listens different port than 7001, and use this domain in to deploy app.

Here's an example: http://st-curriculum.oracle.com/obe/fmw/wls/10g/r3/installconfig/install_wls/install_wls.htm

HTH.

Scraping data from website using vba

I modified some thing that were poping up error for me and end up with this which worked great to extract the data as I needed:

Sub get_data_web()

Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")

With appIE
    .navigate "https://finance.yahoo.com/quote/NQ%3DF/futures?p=NQ%3DF"
    .Visible = True
End With

Do While appIE.Busy
    DoEvents
Loop

Set allRowofData = appIE.document.getElementsByClassName("Ta(end) BdT Bdc($c-fuji-grey-c) H(36px)")

Dim i As Long
Dim myValue As String

Count = 1

    For Each itm In allRowofData

        For i = 0 To 4

        myValue = itm.Cells(i).innerText
        ActiveSheet.Cells(Count, i + 1).Value = myValue

        Next

        Count = Count + 1

    Next

appIE.Quit
Set appIE = Nothing


End Sub

SASS - use variables across multiple files

Create an index.scss and there you can import all file structure you have. I will paste you my index from an enterprise project, maybe it will help other how to structure files in css:

@import 'base/_reset';

@import 'helpers/_variables';
@import 'helpers/_mixins';
@import 'helpers/_functions';
@import 'helpers/_helpers';
@import 'helpers/_placeholders';

@import 'base/_typography';

@import 'pages/_versions';
@import 'pages/_recording';
@import 'pages/_lists';
@import 'pages/_global';

@import 'forms/_buttons';
@import 'forms/_inputs';
@import 'forms/_validators';
@import 'forms/_fieldsets';

@import 'sections/_header';
@import 'sections/_navigation';
@import 'sections/_sidebar-a';
@import 'sections/_sidebar-b';
@import 'sections/_footer';

@import 'vendors/_ui-grid';

@import 'components/_modals';
@import 'components/_tooltip';
@import 'components/_tables';
@import 'components/_datepickers';

And you can watch them with gulp/grunt/webpack etc, like:

gulpfile.js

// SASS Task

var gulp = require('gulp');
var sass = require('gulp-sass');
//var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', function(){
    return gulp
            .src('sass/**/*.scss')
            .pipe(sourcemaps.init())
            .pipe(sass().on('error', sass.logError))
            .pipe(concat('styles.css'))
            .pipe(uglifycss({
                "maxLineLen": 80,
                "uglyComments": true
            }))
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest('./build/css/'));
});

gulp.task('watch', function () {
    gulp.watch('sass/**/*.scss', ['styles']);
});

gulp.task('default', ['watch']);

jQuery AJAX file upload PHP

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running in the browser) sends the form data to the server, then a script on the server handles the upload. Here's an example using PHP.

Your HTML is fine, but update your JS jQuery script to look like this:

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
        url: 'upload.php', // point to server-side PHP script 
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // display response from the PHP script, if any
        }
     });
});

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that runs on the server and directs the file to the uploads directory:

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }

?>

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(

    // this is where the file is temporarily stored on the server when uploaded
    // do not change this
    $_FILES['file']['tmp_name'],

    // this is where you want to put the file and what you want to name it
    // in this case we are putting in a directory called "uploads"
    // and giving it the original filename
    'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(
    $_FILES['file']['tmp_name'],
    'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

Dropdown using javascript onchange

It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).

One way around this is to bind your event handler in javascript (where it should be):

document.getElementById('optionID').onchange = function () {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:

window.changeMessage() {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

?

mvn command not found in OSX Mavrerick

Solutions above are good but they require ~/.bash_profile. /usr/local/bin is already in the $PATH and it can be confirmed by doing echo $PATH. Download maven and run the following commands -

$ cd ~/Downloads
$ tar xvf apache-maven-3.5.3-bin.tar.gz
$ mv apache-maven-3.5.3 /usr/local/
$ cd /usr/local/bin
$ sudo ln -s ../apache-maven-3.5.3/bin/mvn mvn
$ mvn -version
$ which mvn

Note: The version of apache maven would be the one you will download.

Using OR in SQLAlchemy

SQLAlchemy overloads the bitwise operators &, | and ~ so instead of the ugly and hard-to-read prefix syntax with or_() and and_() (like in Bastien's answer) you can use these operators:

.filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))

Note that the parentheses are not optional due to the precedence of the bitwise operators.

So your whole query could look like this:

addr = session.query(AddressBook) \
    .filter(AddressBook.city == "boston") \
    .filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))

Disable Proximity Sensor during call

After trying a whole bunch of fixes including:

  • Phone app's menu option (my phone did not have a option to disable)
  • Proximity Screen Off Lite (did not work)
  • Xposed Framework with sensor disabler (works till phone is rebooted or app updates)
  • Macrodroid macro (Macrodroid does not run on my phone for some reason)
  • put some tin foil in front of it?(i don't know what i was thinking)

Here is My fix: I figured you cannot break it more so I opened up my phone and removed the proximity sensor all together from the motherboard. The sensor tester app now shows "no_value" where it use to give "Distance: 0" and my screen no longer goes black after dialing. Please note I can only confirm this working on a Samsung I8190 Galaxy S III mini with CM MOD 5.1.1. Here is a picture of the device i removed: prox sensor I have removed it using a SMD solder station's heat gun at 400 degrees, some tweezers and flux.But a sharp hobby knife might work too.

Undo a particular commit in Git that's been pushed to remote repos

Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

How to negate the whole regex?

Use negative lookaround: (?!pattern)

Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.

Links to regular-expressions.info

See also

More examples

These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):

Python loop counter in a for loop

Use enumerate() like so:

def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option    

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

Total Number of Row Resultset getRow Method

The best way to get number of rows from resultset is using count function query for database access and then rs.getInt(1) method to get number of rows. from my code look it:

    String query = "SELECT COUNT() FROM table";
ResultSet rs = new DatabaseConnection().selectData(query);
rs.getInt(1);

this will return int value number of rows fetched from database. Here DatabaseConnection().selectData() is my code for accessing database. I was also stuck here but then solved...

Send XML data to webservice using php curl

Check this one. It will work.

function fetch($i1,$i2,$i3,$i4)
{
$input_data = '<I> 
                <i1>'.$i1.'</i1> 
                <i2>'.$i2.'</i2> 
                <i3>'.$i2.'</i3> 
                <i4>'.$i3.'</i4> 
              </I>';
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "8080",
  CURLOPT_URL => "http://192.168.1.100:8080/avaliablity",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input_data,
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Content-Type: application/xml"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
}

fetch('i1','i2','i3','i4');

python - checking odd/even numbers and changing outputs on number size

Here's my solution:

def is_even(n):
    r=n/2.0
    return True if r==int(r) else False

Thread Safe C# Singleton Pattern

Performing a lock: Quite cheap (still more expensive than a null test).

Performing a lock when another thread has it: You get the cost of whatever they've still to do while locking, added to your own time.

Performing a lock when another thread has it, and dozens of other threads are also waiting on it: Crippling.

For performance reasons, you always want to have locks that another thread wants, for the shortest period of time at all possible.

Of course it's easier to reason about "broad" locks than narrow, so it's worth starting with them broad and optimising as needed, but there are some cases that we learn from experience and familiarity where a narrower fits the pattern.

(Incidentally, if you can possibly just use private static volatile Singleton instance = new Singleton() or if you can possibly just not use singletons but use a static class instead, both are better in regards to these concerns).

Removing carriage return and new-line from the end of a string in c#

If there's always a single CRLF, then:

myString = myString.Substring(0, myString.Length - 2);

If it may or may not have it, then:

Regex re = new Regex("\r\n$");
re.Replace(myString, "");

Both of these (by design), will remove at most a single CRLF. Cache the regex for performance.

Java Enum Methods - return opposite direction enum

Yes we do it all the time. You return a static instance rather than a new Object

 static Direction getOppositeDirection(Direction d){
       Direction result = null;
       if (d != null){
           int newCode = -d.getCode();
           for (Direction direction : Direction.values()){
               if (d.getCode() == newCode){
                   result = direction;
               }
           }
       }
       return result;
 }

How to insert default values in SQL table?

CREATE PROC SP_EMPLOYEE                             --By Using TYPE parameter and CASE  in Stored procedure
(@TYPE INT)
AS
BEGIN
IF @TYPE=1
BEGIN
SELECT DESIGID,DESIGNAME FROM GP_DESIGNATION
END
IF @TYPE=2
BEGIN
SELECT ID,NAME,DESIGNAME,
case D.ISACTIVE when 'Y' then 'ISACTIVE' when 'N' then 'INACTIVE' else 'not' end as ACTIVE
 FROM GP_EMPLOYEEDETAILS ED 
  JOIN  GP_DESIGNATION D ON ED.DESIGNATION=D.DESIGID
END
END

How does Java import work?

Java's import statement is pure syntactical sugar. import is only evaluated at compile time to indicate to the compiler where to find the names in the code.

You may live without any import statement when you always specify the full qualified name of classes. Like this line needs no import statement at all:

javax.swing.JButton but = new  javax.swing.JButton();

The import statement will make your code more readable like this:

import javax.swing.*;

JButton but = new JButton();

Compare cell contents against string in Excel

You can use the EXACT Function for exact string comparisons.

=IF(EXACT(A1, "ENG"), 1, 0)

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

You can match those three groups separately, and make sure that they all present. Also, [^\w] seems a bit too broad, but if that's what you want you might want to replace it with \W.

Finding element's position relative to the document

You can traverse the offsetParent up to the top level of the DOM.

function getOffsetLeft( elem )
{
    var offsetLeft = 0;
    do {
      if ( !isNaN( elem.offsetLeft ) )
      {
          offsetLeft += elem.offsetLeft;
      }
    } while( elem = elem.offsetParent );
    return offsetLeft;
}

How to display raw html code in PRE or something like it but without escaping it

Cheap and cheerful answer:

<textarea>Some raw content</textarea>

The textarea will handle tabs, multiple spaces, newlines, line wrapping all verbatim. It copies and pastes nicely and its valid HTML all the way. It also allows the user to resize the code box. You don't need any CSS, JS, escaping, encoding.

You can alter the appearance and behaviour as well. Here's a monospace font, editing disabled, smaller font, no border:

<textarea
    style="width:100%; font-family: Monospace; font-size:10px; border:0;"
    rows="30" disabled
>Some raw content</textarea>

This solution is probably not semantically correct. So if you need that, it might be best to choose a more sophisticated answer.

Get a particular cell value from HTML table using JavaScript

<td class="virtualTd" onclick="putThis(this)">my td value </td>

function putThis(control) { 
    alert(control.innerText);
}

Automatically start forever (node) on system restart

This case is valid for Debian.

Add the following to /etc/rc.local

/usr/bin/sudo -u {{user}} /usr/local/bin/forever start {{app path}}

  • {{user}} replaces your username.
  • {{app path}} replaces your app path. For example, /var/www/test/app.js

Convert java.time.LocalDate into java.util.Date type

Kotlin Solution:

1) Paste this extension function somewhere.

fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())

2) Use it, and never google this again.

val myDate = myLocalDate.toDate()

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

UPDATE:

onActivityCreated() is deprecated from API Level 28.


onCreate():

The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().
In this method, you can assign variables, get Intent extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity's onCreate() is not finished, and so trying to access the View hierarchy here may result in a crash.

onCreateView():

After the onCreate() is called (in the Fragment), the Fragment's onCreateView() is called. You can assign your View variables and do any graphical initialisations. You are expected to return a View from this method, and this is the main UI view, but if your Fragment does not use any layouts or graphics, you can return null (happens by default if you don't override).

onActivityCreated():

As the name states, this is called after the Activity's onCreate() has completed. It is called after onCreateView(), and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.


To sum up...
... they are all called in the Fragment but are called at different times.
The onCreate() is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View variables you want to use in onCreateView(). Afterwards, use onActivityCreated() to do any final initialisations you want to do once everything has completed.


If you want to view the official Android documentation, it can be found here:

There are also some slightly different, but less developed questions/answers here on Stack Overflow:

Equivalent of .bat in mac os

I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:

  • Make a bash (shell) script version of your .bat file (like other
    answers, with \ changed to / in file paths). For example:

    # File "example.command":
    #!/bin/bash
    java -cp  ".;./supportlibraries/Framework_Core.jar; ...etc.
    
  • Then rename it to have the Mac OS file extension .command.
    That should make the script run using the Terminal app.

  • If the app user is going to use a bash script version of the file on Linux
    or run it from the command line, they need to add executable rights
    (change mode bits) using this command, in the folder that has the file:

    chmod +rx [filename].sh
    #or:# chmod +rx [filename].command
    

The forum page question:

Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.

Info from some answers after the question:

Write a shell script, and give it the extension ".command". For example:

#!/bin/bash 
printf "Hello World\n" 

- Mar 23, 2010, Tony T1.

The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.

However, OS X adds the feature that if you give the file the suffix .command, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).

Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]

#!/bin/sh
echo Hello World

- Mar 23, 2010, J D McIninch.

Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:

On mac, there is a specific extension for executing shell
scripts by double clicking them: this is .command.

VB.Net: Dynamically Select Image from My.Resources

Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")

Remove scrollbars from textarea

Hide scroll bar, but while still being able to scroll using CSS

To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:

    -webkit- (Chrome, Safari, newer versions of Opera):
    .element::-webkit-scrollbar { width: 0 !important }
    -moz- (Firefox):
    .element { overflow: -moz-scrollbars-none; }
    -ms- (Internet Explorer +10):
    .element { -ms-overflow-style: none; }

ref: https://www.geeksforgeeks.org/hide-scroll-bar-but-while-still-being-able-to-scroll-using-css/

Reading Excel files from C#

Forgive me if I am off-base here, but isn't this what the Office PIA's are for?

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

Checking if a collection is null or empty in Groovy

FYI this kind of code works (you can find it ugly, it is your right :) ) :

def list = null
list.each { println it }
soSomething()

In other words, this code has null/empty checks both useless:

if (members && !members.empty) {
    members.each { doAnotherThing it }
}

def doAnotherThing(def member) {
  // Some work
}

Android studio, gradle and NDK

This is the code i use to build using android-ndk from gradle. For this add ndk directory path in gradle.properties ie . add ndkdir=/home/user/android-ndk-r9d and put all jni files in a folder native in src/main/ as you can see from code posted below. It will create jar with native libs which you can use normally as in System.loadLibrary("libraryname");

dependencies {
    compile fileTree(dir: "$buildDir/native-libs", include: '*.jar')
}

task ndkBuild(type: Exec) {
    commandLine "$ndkdir/ndk-build", "--directory", "$projectDir/src/main/native", '-j', Runtime.runtime.availableProcessors(),
            "APP_PLATFORM=android-8",
            "APP_BUILD_SCRIPT=$projectDir/src/main/native/Android.mk",
            "NDK_OUT=$buildDir/native/obj",
            "NDK_APP_DST_DIR=$buildDir/native/libs/\$(TARGET_ARCH_ABI)"
}

task nativeLibsToJar(type: Jar, description: 'create a jar with native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    from fileTree(dir: "$buildDir/native/libs", include: '**/*.so')
    into 'lib/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn nativeLibsToJar
}

nativeLibsToJar.dependsOn 'ndkBuild'

How to check a string against null in java?

Well, the last time someone asked this silly question, the answer was:

someString.equals("null")

This "fix" only hides the bigger problem of how null becomes "null" in the first place, though.

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

It is not always about the compilation flags, I have the same error on gentoo when using distcc.

The reason is that on distcc server is using a not-hardened profile and on client the profile is hardened. Check this discussion: https://forums.gentoo.org/viewtopic-p-7463994.html

Assign one struct to another in C

Yes, you can assign one instance of a struct to another using a simple assignment statement.

  • In the case of non-pointer or non pointer containing struct members, assignment means copy.

  • In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

Let us see this first hand:

#include <stdio.h>

struct Test{
    int foo;
    char *bar;
};

int main(){
    struct Test t1;
    struct Test t2;
    t1.foo = 1;
    t1.bar = malloc(100 * sizeof(char));
    strcpy(t1.bar, "t1 bar value");
    t2.foo = 2;
    t2.bar = malloc(100 * sizeof(char));
    strcpy(t2.bar, "t2 bar value");
    printf("t2 foo and bar before copy: %d %s\n", t2.foo, t2.bar);
    t2 = t1;// <---- ASSIGNMENT
    printf("t2 foo and bar after copy: %d %s\n", t2.foo, t2.bar);
    //The following 3 lines of code demonstrate that foo is deep copied and bar is shallow copied
    strcpy(t1.bar, "t1 bar value changed");
    t1.foo = 3;
    printf("t2 foo and bar after t1 is altered: %d %s\n", t2.foo, t2.bar);
    return 0;
}

How do you use youtube-dl to download live streams (that are live)?

I have Written a small script to download the live youtube video, you may use as single command as well. script it can be invoked simply as,

~/ytdl_lv.sh <URL> <output file name>

e.g.

~/ytdl_lv.sh https://www.youtube.com/watch?v=BLIGxsYLyjc myfile.mp4

script is as simple as below,

#!/bin/bash 

# ytdl_lv.sh
# Author Prashant
# 

URL=$1 
OUTNAME=$2
streamlink --hls-live-restart -o ${OUTNAME} ${URL} best

here the best is the stream quality, it also can be 144p (worst), 240p, 360p, 480p, 720p (best)

Parse strings to double with comma and point

try this... it works for me.

double vdouble = 0;
string sparam = "2,1";

if ( !Double.TryParse( sparam, NumberStyles.Float, CultureInfo.InvariantCulture, out vdouble ) )
{
    if ( sparam.IndexOf( '.' ) != -1 )
    {
        sparam = sparam.Replace( '.', ',' );
    }
    else
    {
        sparam = sparam.Replace( ',', '.' );
    }

    if ( !Double.TryParse( sparam, NumberStyles.Float, CultureInfo.InvariantCulture, out vdouble ) )
    {
        vdouble = 0;
    }
}

How to set a default value for an existing column

This will work in SQL Server:

ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;

Count work days between two dates

My version of the accepted answer as a function using DATEPART, so I don't have to do a string comparison on the line with

DATENAME(dw, @StartDate) = 'Sunday'

Anyway, here's my business datediff function

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION BDATEDIFF
(
    @startdate as DATETIME,
    @enddate as DATETIME
)
RETURNS INT
AS
BEGIN
    DECLARE @res int

SET @res = (DATEDIFF(dd, @startdate, @enddate) + 1)
    -(DATEDIFF(wk, @startdate, @enddate) * 2)
    -(CASE WHEN DATEPART(dw, @startdate) = 1 THEN 1 ELSE 0 END)
    -(CASE WHEN DATEPART(dw, @enddate) = 7 THEN 1 ELSE 0 END)

    RETURN @res
END
GO

How do I install Python OpenCV through Conda?

conda install -c https://conda.anaconda.org/menpo opencv

Try this

Parsing jQuery AJAX response

Since you are using $.ajax, and not $.getJSON, your return type is plain text. you need to now convert data into a JSON object.

you can either do this by changing your $.ajax to $.getJSON (which is a shorthand for $.ajax, only preconfigured to fetch json).

Or you can parse the data string into JSON after you receive it, like so:

    success: function (data) {
         var obj = $.parseJSON(data);
         console.log(obj);
    },

"Cannot GET /" with Connect on Node.js

Had the same issue. It was resolved as described above.

In my index.js

var port = 1338,
express = require('express'),
app = express().use(express.static(__dirname + '/')),
http = require('http').Server(app),
io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
    console.log('a user connected');
});

http.listen(port, function(){
    console.log("Node server listening on port " + port);
});

and in my index.html

<!doctype html>
<html>
    <head>
        <title>
            My page
        </title>
    </head>
    <body>
        <script src = "lib/socket.io.js"></script>
        <script src = "lib/three.js"></script>
        <script>
            var socket = io();
        </script>
    </body>
</html>

the three.js was just in there for path testing. This will set all child files to start at the root directory of your app. Also socket.io.js can be called automatically using <script src = "/socket.io/socket.io.js"> through some dark magic (since there is physically a node_modules and lib directory in between) .

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

When you created the WebForm, did you select the Master page it is attached to in the "Add New Item" dialog itself ? Or did you attach it manually using the MasterPageFile attribute of the @Page directive ? If it was the latter, it might explain the error message you receive.

VS automatically inserts certain markup in each kind of page. If you select the MasterPage at the time of page creation itself, it does not generate any markup except the @Page declaration and the top level Content control.

How do I check if I'm running on Windows in Python?

in sys too:

import sys
# its win32, maybe there is win64 too?
is_windows = sys.platform.startswith('win')

How can I strip HTML tags from a string in ASP.NET?

protected string StripHtml(string Txt)
{
    return Regex.Replace(Txt, "<(.|\\n)*?>", string.Empty);
}    

Protected Function StripHtml(Txt as String) as String
    Return Regex.Replace(Txt, "<(.|\n)*?>", String.Empty)
End Function

Mongoose and multiple database in single node.js project

One thing you can do is, you might have subfolders for each projects. So, install mongoose in that subfolders and require() mongoose from own folders in each sub applications. Not from the project root or from global. So one sub project, one mongoose installation and one mongoose instance.

-app_root/
--foo_app/
---db_access.js
---foo_db_connect.js
---node_modules/
----mongoose/
--bar_app/
---db_access.js
---bar_db_connect.js
---node_modules/
----mongoose/

In foo_db_connect.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foo_db');
module.exports = exports = mongoose;

In bar_db_connect.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bar_db');
module.exports = exports = mongoose;

In db_access.js files

var mongoose = require("./foo_db_connect.js"); // bar_db_connect.js for bar app

Now, you can access multiple databases with mongoose.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

If you're going to use a Control from another thread before showing or doing other things with the Control, consider forcing the creation of its handle within the constructor. This is done using the CreateHandle function.

In a multi-threaded project, where the "controller" logic isn't in a WinForm, this function is instrumental in Control constructors for avoiding this error.

Detect click inside/outside of element with single event handler

Using jQuery, and assuming that you have <div id="foo">:

jQuery(function($){
  $('#foo').click(function(e){
    console.log( 'clicked on div' );
    e.stopPropagation(); // Prevent bubbling
  });
  $('body').click(function(e){
    console.log( 'clicked outside of div' );
  });
});

Edit: For a single handler:

jQuery(function($){
  $('body').click(function(e){
    var clickedOn = $(e.target);
    if (clickedOn.parents().andSelf().is('#foo')){
      console.log( "Clicked on", clickedOn[0], "inside the div" );
    }else{
      console.log( "Clicked outside the div" );
  });
});

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

IF...ELSE... is pretty much what we've got in T-SQL. There is nothing like structured programming's CASE statement. If you have an extended set of ...ELSE IF...s to deal with, be sure to include BEGIN...END for each block to keep things clear, and always remember, consistent indentation is your friend!

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change event.

You can handle the blur event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.

wp-admin shows blank page, how to fix it?

I just had this and it was a file / directory ownership issue. Fixed via SSH and changing the ownership recursively (-R):

chown -R ownerID:groupID /home/mydirectory/website

Change ownerID, groupID and filepath to be relevant to your own situation.

div inside table

You can't put a div directly inside a table, like this:

<!-- INVALID -->
<table>
  <div>
    Hello World
  </div>
</table>

Putting a div inside a td or th element is fine, however:

<!-- VALID -->
<table>
  <tr>
    <td>
      <div>
        Hello World
      </div>
    </td>
  </tr>
</table>

git checkout master error: the following untracked working tree files would be overwritten by checkout

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

How do I rename a Git repository?

The main name change is here (img 1), but also change readme.md (img 2)

enter image description here

enter image description here

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

multiple criteria can also be implemented through lambda function

sorted_list = sorted(list_to_sort, key=lambda x: (x[1], x[0]))

Capture HTML Canvas as gif/jpg/png/pdf?

I thought I'd extend the scope of this question a bit, with some useful tidbits on the matter.

In order to get the canvas as an image, you should do the following:

var canvas = document.getElementById("mycanvas");
var image = canvas.toDataURL("image/png");

You can use this to write the image to the page:

document.write('<img src="'+image+'"/>');

Where "image/png" is a mime type (png is the only one that must be supported). If you would like an array of the supported types you can do something along the lines of this:

var imageMimes = ['image/png', 'image/bmp', 'image/gif', 'image/jpeg', 'image/tiff']; //Extend as necessary 
var acceptedMimes = new Array();
for(i = 0; i < imageMimes.length; i++) {
    if(canvas.toDataURL(imageMimes[i]).search(imageMimes[i])>=0) {
        acceptedMimes[acceptedMimes.length] = imageMimes[i];
    }
}

You only need to run this once per page - it should never change through a page's lifecycle.

If you wish to make the user download the file as it is saved you can do the following:

var canvas = document.getElementById("mycanvas");
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); //Convert image to 'octet-stream' (Just a download, really)
window.location.href = image;

If you're using that with different mime types, be sure to change both instances of image/png, but not the image/octet-stream. It is also worth mentioning that if you use any cross-domain resources in rendering your canvas, you will encounter a security error when you try to use the toDataUrl method.

Add Insecure Registry to Docker

Anyone looking to add insecure registry on amazon linux 2: You will have to change the setting under /etc/sysconfig/docker and then restart docker daemon: here's how my /etc/sysconfig/docker looks like

# The max number of open files for the daemon itself, and all
# running containers.  The default value of 1048576 mirrors the value
# used by the systemd service unit.
DAEMON_MAXFILES=1048576

# Additional startup options for the Docker daemon, for example:
# OPTIONS="--ip-forward=true --iptables=true"
# By default we limit the number of open files per container
OPTIONS="--default-ulimit nofile=1024:4096 --insecure-registry yourinsecureregistryhostname:port"

# How many seconds the sysvinit script waits for the pidfile to appear
# when starting the daemon.
DAEMON_PIDFILE_TIMEOUT=10

eclipse won't start - no java virtual machine was found

After setting Java Path, if you are not able to open your eclipse do below steps:

  1. Go to your Eclipse Folder where you have extracted your eclipse.

enter image description here

  1. Open Eclipse file in notepad (by default it will open on notepad)

Enter two lines

-vm
C:/Program Files/Java/jdk-11.0.2/bin/javaw.exe

jdk-11.0.2 ,It should be your Java Version, which you will get by the above location.

enter image description here

How can I perform a short delay in C# without using sleep?

By adding using System.Timers; to your program you can use this function:

private static void delay(int Time_delay)
{
   int i=0;
  //  ameTir = new System.Timers.Timer();
    _delayTimer = new System.Timers.Timer();
    _delayTimer.Interval = Time_delay;
    _delayTimer.AutoReset = false; //so that it only calls the method once
    _delayTimer.Elapsed += (s, args) => i = 1;
    _delayTimer.Start();
    while (i == 0) { };
}

Delay is a function and can be used like:

delay(5000);

How to rename a file using svn?

It can be if you created new directory at the disk BEFORE create/commit it in the SVN. All that you need is just create it in SVN and do move after:

$ svn mv etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/
svn: E155010: Path '/home/dyr/svn/nagioscore/etc/nagios/hosts/us0101/ccs' is not a directory

$ svn status
?       etc/nagios/hosts/us0101/ccs

$ rm -rvf etc/nagios/hosts/us0101/ccs
removed directory 'etc/nagios/hosts/us0101/ccs'

$ svn mkdir etc/nagios/hosts/us0101/ccs
A         etc/nagios/hosts/us0101/ccs

$ svn move etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
A         etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
D         etc/nagios/hosts/us0101/cs/us0101ccs001.cfg

$ svn status
A       etc/nagios/hosts/us0101/ccs
A  +    etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
        > moved from etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
D       etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
        > moved to etc/nagios/hosts/us0101/ccs/us0101accs001.cfg

How to enable external request in IIS Express?

Another way to access external requests is to use IIS instead of IIS Express. In my visual studio, I can just switch easily.

enter image description here

How does the Python's range function work?

for i in range(5):

is the same as

for i in [0,1,2,3,4]:

Forbidden You don't have permission to access / on this server

This works for me on Mac OS Mojave:

<Directory "/Users/{USERNAME}/Sites/project">
    Options +Indexes +FollowSymLinks +MultiViews
    AllowOverride All
    require all granted
</Directory>

How do I remove a single breakpoint with GDB?

You can list breakpoints with:

info break

This will list all breakpoints. Then a breakpoint can be deleted by its corresponding number:

del 3

For example:

 (gdb) info b
 Num     Type           Disp Enb Address    What
  3      breakpoint     keep y   0x004018c3 in timeCorrect at my3.c:215
  4      breakpoint     keep y   0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
 (gdb) del 3
 (gdb) info b
 Num     Type           Disp Enb Address    What
  4      breakpoint     keep y   0x004295b0 in avi_write_packet atlibavformat/avienc.c:513

javascript code to check special characters

Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.

function isValid(str) {
    var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";

    for (var i = 0; i < str.length; i++) {
       if (iChars.indexOf(str.charAt(i)) != -1) {
           alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
           return false;
       }
    }
    return true;
}

I tried this in my chrome console and it worked well.

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

The best practice is selecting the most appropriate one.

.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string.

The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters*.

Reference : Here

For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.

Reference : Here

Check the source code (Reference Source .NET Framework 4.6.2)

IsNullorEmpty

[Pure]
public static bool IsNullOrEmpty(String value) {
    return (value == null || value.Length == 0);
}

IsNullOrWhiteSpace

[Pure]
public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true;

    for(int i = 0; i < value.Length; i++) {
        if(!Char.IsWhiteSpace(value[i])) return false;
    }

    return true;
}

Examples

string nullString = null;
string emptyString = "";
string whitespaceString = "    ";
string nonEmptyString = "abc123";

bool result;

result = String.IsNullOrEmpty(nullString);            // true
result = String.IsNullOrEmpty(emptyString);           // true
result = String.IsNullOrEmpty(whitespaceString);      // false
result = String.IsNullOrEmpty(nonEmptyString);        // false

result = String.IsNullOrWhiteSpace(nullString);       // true
result = String.IsNullOrWhiteSpace(emptyString);      // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString);   // false

How to get request URL in Spring Boot RestController

Add a parameter of type UriComponentsBuilder to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo to point at a different controller using the same prefix).

C++: Converting Hexadecimal to Decimal

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    int x, y;
    std::stringstream stream;

    std::cin >> x;
    stream << x;
    stream >> std::hex >> y;
    std::cout << y;

    return 0;
}

How do I decode a URL parameter using C#?

Server.UrlDecode(xxxxxxxx)

Styling Password Fields in CSS

I found I could improve the situation a little with CSS dedicated to Webkit (Safari, Chrome). However, I had to set a fixed width and height on the field because the font change will resize the field.

@media screen and (-webkit-min-device-pixel-ratio:0){ /* START WEBKIT */
  INPUT[type="password"]{
  font-family:Verdana,sans-serif;
  height:28px;
  font-size:19px;
  width:223px;
  padding:5px;
  }
} /* END WEBKIT */

MongoDB: update every document on one field

Regardless of the version, for your example, the <update> is:

{  $set: { lastLookedAt: Date.now() / 1000 }  }

However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB client:

$version >= 3.2:

db.foo.updateMany( {}, <update> )
  • {} is the condition (the empty condition matches any document)

3.2 > $version >= 2.2:

db.foo.update( {}, <update>, { multi: true } )
  • {} is the condition (the empty condition matches any document)
  • {multi: true} is the "update multiple documents" option

$version < 2.2:

db.foo.update( {}, <update>, false, true )
  • {} is the condition (the empty condition matches any document)
  • false is for the "upsert" parameter
  • true is for the "multi" parameter (update multiple records)

What does the term "Tuple" Mean in Relational Databases?

Tuples are known values which is used to relate the table in relational DB.

Sort a single String in Java

Question: sort a string in java

public class SortAStringInJava {
    public static void main(String[] args) {

        String str = "Protijayi";
// Method 1
        str = str.chars() // IntStream
                .sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();

        System.out.println(str);
        // Method 2
        str = Stream.of(str.split(" ")).sorted().collect(Collectors.joining());
        System.out.println(str);
    }
}

Python class returning value

class MyClass():
    def __init__(self, a, b):
        self.value1 = a
        self.value2 = b

    def __call__(self):
        return [self.value1, self.value2]

Testing:

>>> x = MyClass('foo','bar')
>>> x()
['foo', 'bar']

How to resize Twitter Bootstrap modal dynamically based on the content

This worked for me, none of the above worked.

.modal-dialog{
    position: relative;
    display: table; /* This is important */ 
    overflow-y: auto;    
    overflow-x: auto;
    width: auto;
    min-width: 300px;   
}

No more data to read from socket error

I got this error then restarted my GlassFish server that held connection pools between my client app and the database, and the error went away. So, try restarting your application server if applicable.

How do I set the focus to the first input element in an HTML form independent from the id?

I needed to solve this problem for a form that is being displayed dynamically in a modal div on my page, and unfortunately autofocus isn't honored when the containing div is shown by changing the display property (at least not in Chrome). I don't like any of the solutions that require my code to infer which control I should set the focus to, because of the complications of hidden or zero-sized inputs, etc. My solution was to set the autofocus attribute on my input anyway, then set the focus in my code when I show the div:

form.querySelector('*[autofocus]').focus();

Multiple distinct pages in one HTML file

This is kind of overriding the thing of one page, but... You could use iframes in HTML.

<html>
<body>
<iframe src="page1.html" border="0"></iframe>
</body>
</html>

And page1.html would be your base page. Your still making multiple pages, but your browser just doesn't move. So lets say thats your index.html. You have tabs, you click page 2, your url wont change, but the page will. All in iframes. The only thing different, is that you can view the frame source as well.

Variable length (Dynamic) Arrays in Java

  1. It is recommend to use List to deal with small scale size.

  2. If you have a huge number of numbers, NEVER use List and autoboxing,

    List< Integer> list

For every single int, a new Integer is auto created. You will find it getting slow when the size of the list increase. These Integers are unnecessary objects. In this case, to use a estimated size would be better,

int[] array = new int[ESTIMATED_SIZE];

How to print a groupby object

Another simple alternative:

for name_of_the_group, group in grouped_dataframe:
   print (name_of_the_group)
   print (group)

TypeScript for ... of with index / key?

Or another old school solution:

var someArray = [9, 2, 5];
let i = 0;
for (var item of someArray) {
    console.log(item); // 9,2,5
    i++;
}

Delete all files in directory (but not directory) - one liner solution

Or to use this in Java 8:

try {
  Files.newDirectoryStream( directory ).forEach( file -> {
    try { Files.delete( file ); }
    catch ( IOException e ) { throw new UncheckedIOException(e); }
  } );
}
catch ( IOException e ) {
  e.printStackTrace();
}

It's a pity the exception handling is so bulky, otherwise it would be a one-liner ...

How to select all rows which have same value in some column

SELECT * FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Update : for better performance and faster query its good to add e1 before *

SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Illegal string offset Warning PHP

I solved this problem by using trim() function. the issue was with space.

so lets try

$unit_size = []; //please declare the variable type 
$unit_size = exolode("x", $unit_size);
$width  = trim ($unit_size[1] );
$height = trim ($unit_size[2] );

I hope this will help you.

Should I use SVN or Git?

I have used SVN for a long time, but whenever I used Git, I felt that Git is much powerful, lightweight, and although a little bit of learning curve involved but is better than SVN.

What I have noted is that each SVN project, as it grows, becomes a very big size project unless it is exported. Where as, GIT project (along with Git data) is very light weight in size.

In SVN, I've dealt with developers from novice to experts, and the novices and intermediates seem to introduce File conflicts if they copy one folder from another SVN project in order to re-use it. Whereas, I think in Git, you just copy the folder and it works, because Git doesn't introduce .git folders in all its subfolders (as SVN does).

After dealing alot with SVN since long time, I'm finally thinking to move my developers and me to Git, since it is easy to collaborate and merge work, as well as one great advantage is that a local copy's changes can be committed as much desired, and then finally pushed to the branch on server in one go, unlike SVN (where we have to commit the changes from time to time in the repository on server).

Anyone who can help me decide if I should really go with Git?

Maven: How to change path to target directory from command line?

Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:

    <profile>
        <id>alternateBuildDir</id>
        <activation>
            <property>
                <name>alt.build.dir</name>
            </property>
        </activation>
        <build>
            <directory>${alt.build.dir}</directory>
        </build>
    </profile>

Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.

How do I get the name of the current executable in C#?

When uncertain or in doubt, run in circles, scream and shout.

class Ourself
{
    public static string OurFileName() {
        System.Reflection.Assembly _objParentAssembly;

        if (System.Reflection.Assembly.GetEntryAssembly() == null)
            _objParentAssembly = System.Reflection.Assembly.GetCallingAssembly();
        else
            _objParentAssembly = System.Reflection.Assembly.GetEntryAssembly();

        if (_objParentAssembly.CodeBase.StartsWith("http://"))
            throw new System.IO.IOException("Deployed from URL");

        if (System.IO.File.Exists(_objParentAssembly.Location))
            return _objParentAssembly.Location;
        if (System.IO.File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName))
            return System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName;
        if (System.IO.File.Exists(System.Reflection.Assembly.GetExecutingAssembly().Location))
            return System.Reflection.Assembly.GetExecutingAssembly().Location;

        throw new System.IO.IOException("Assembly not found");
    }
}

I can't claim to have tested each option, but it doesn't do anything stupid like returning the vhost during debugging sessions.

Maven: Command to update repository after adding dependency to POM

I know it is an old question now, but for users who are using Maven plugin with Eclipse under Windows, you have two options:

  1. If you got Maven installed as a standalone application:

    You can use the following command in the CMD under your project path:

    mvn eclipse:eclipse
    

    It will update your repository with all the missing jars, according to your dependencies in your pom.xml file.

  2. If you haven't got Maven installed as a standalone application you can follow these steps on your eclipse:

    Right click on the project ->Run As -- >Run configurations.

    Then select mavenBuild.

    Then click new button to create a configuration of the selected type .Click on Browse workspace then select your project and in goals specify eclipse:eclipse

You can refer to how to run the command mvn eclipse:eclipse for further details.

When does System.getProperty("java.io.tmpdir") return "c:\temp"

Value of %TEMP% environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM, LOCALSYSTEM or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP% variable explicitly, Windows may use c:\temp or even c:\windows\temp folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!

How to test if a string is JSON or not?

There are probably tests you can do, for instance if you know that the JSON returned is always going to be surrounded by { and } then you could test for those characters, or some other hacky method. Or you could use the json.org JS library to try and parse it and test if it succeeds.

I would however suggest a different approach. Your PHP script currently returns JSON if the call is successful, but something else if it is not. Why not always return JSON?

E.g.

Successful call:

{ "status": "success", "data": [ <your data here> ] }

Erroneous call:

{ "status": "error", "error": "Database not found" }

This would make writing your client side JS much easier - all you have to do is check the "status" member and the act accordingly.

Switch statement: must default be the last case?

It's valid, but rather nasty. I would suggest it's generally bad to allow fall-throughs as it can lead to some very messy spaghetti code.

It's almost certainly better to break these cases up into several switch statements or smaller functions.

[edit] @Tristopia: Your example:

Example from UCS-2 to UTF-8 conversion 

r is the destination array, 
wc is the input wchar_t  

switch(utf8_length) 
{ 
    /* Note: code falls through cases! */ 
    case 3: r[2] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x800; 
    case 2: r[1] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x0c0; 
    case 1: r[0] = wc;
}

would be clearer as to it's intention (I think) if it were written like this:

if( utf8_length >= 1 )
{
    r[0] = wc;

    if( utf8_length >= 2 )
    {
        r[1] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x0c0; 

        if( utf8_length == 3 )
        {
            r[2] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x800; 
        }
    }
}   

[edit2] @Tristopia: Your second example is probably the cleanest example of a good use for follow-through:

for(i=0; s[i]; i++)
{
    switch(s[i])
    {
    case '"': 
    case '\'': 
    case '\\': 
        d[dlen++] = '\\'; 
        /* fall through */ 
    default: 
        d[dlen++] = s[i]; 
    } 
}

..but personally I would split the comment recognition into it's own function:

bool isComment(char charInQuestion)
{   
    bool charIsComment = false;
    switch(charInQuestion)
    {
    case '"': 
    case '\'': 
    case '\\': 
        charIsComment = true; 
    default: 
        charIsComment = false; 
    } 
    return charIsComment;
}

for(i=0; s[i]; i++)
{
    if( isComment(s[i]) )
    {
        d[dlen++] = '\\'; 
    }
    d[dlen++] = s[i]; 
}

How to put spacing between floating divs?

A litte late answer.

If you want to use a grid like this, you should have a look at Bootstrap, It's relatively easy to install, and it gives you exactly what you are looking for, all wrapped in nice and simple html/css + it works easily for making websites responsive.

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.

GPS

A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.

AGPS

As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

Preventing SQL injection in Node.js

In regards to testing if a module you are utilizing is secure or not there are several routes you can take. I will touch on the pros/cons of each so you can make a more informed decision.

Currently, there aren't any vulnerabilities for the module you are utilizing, however, this can often lead to a false sense of security as there very well could be a vulnerability currently exploiting the module/software package you are using and you wouldn't be alerted to a problem until the vendor applies a fix/patch.

  1. To keep abreast of vulnerabilities you will need to follow mailing lists, forums, IRC & other hacking related discussions. PRO: You can often times you will become aware of potential problems within a library before a vendor has been alerted or has issued a fix/patch to remedy the potential avenue of attack on their software. CON: This can be very time consuming and resource intensive. If you do go this route a bot using RSS feeds, log parsing (IRC chat logs) and or a web scrapper using key phrases (in this case node-mysql-native) and notifications can help reduce time spent trolling these resources.

  2. Create a fuzzer, use a fuzzer or other vulnerability framework such as metasploit, sqlMap etc. to help test for problems that the vendor may not have looked for. PRO: This can prove to be a sure fire method of ensuring to an acceptable level whether or not the module/software you are implementing is safe for public access. CON: This also becomes time consuming and costly. The other problem will stem from false positives as well as uneducated review of the results where a problem resides but is not noticed.

Really security, and application security in general can be very time consuming and resource intensive. One thing managers will always use is a formula to determine the cost effectiveness (manpower, resources, time, pay etc) of performing the above two options.

Anyways, I realize this is not a 'yes' or 'no' answer that may have been hoping for but I don't think anyone can give that to you until they perform an analysis of the software in question.

MySQL COUNT DISTINCT

Overall

SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site

  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

There is an easy way without the need to use an external tool - it runs fine with Windows 7, 8, 8.1 and 10 and is backwards-compatible too (Windows XP doesn't have any UAC, thus elevation is not needed - in that case the script just proceeds).

Check out this code (I was inspired by the code by NIronwolf posted in the thread Batch File - "Access Denied" On Windows 7?), but I've improved it - in my version there isn't any directory created and removed to check for administrator privileges):

::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "https://stackoverflow.com/a/12264592/1016343" for description
::::::::::::::::::::::::::::::::::::::::::::
 @echo off
 CLS
 ECHO.
 ECHO =============================
 ECHO Running Admin shell
 ECHO =============================

:init
 setlocal DisableDelayedExpansion
 set cmdInvoke=1
 set winSysFolder=System32
 set "batchPath=%~0"
 for %%k in (%0) do set batchName=%%~nk
 set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
 setlocal EnableDelayedExpansion

:checkPrivileges
  NET FILE 1>NUL 2>NUL
  if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges
  if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
  ECHO.
  ECHO **************************************
  ECHO Invoking UAC for Privilege Escalation
  ECHO **************************************

  ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
  ECHO args = "ELEV " >> "%vbsGetPrivileges%"
  ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
  ECHO args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
  ECHO Next >> "%vbsGetPrivileges%"

  if '%cmdInvoke%'=='1' goto InvokeCmd 

  ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
  goto ExecElevation

:InvokeCmd
  ECHO args = "/c """ + "!batchPath!" + """ " + args >> "%vbsGetPrivileges%"
  ECHO UAC.ShellExecute "%SystemRoot%\%winSysFolder%\cmd.exe", args, "", "runas", 1 >> "%vbsGetPrivileges%"

:ExecElevation
 "%SystemRoot%\%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %*
 exit /B

:gotPrivileges
 setlocal & cd /d %~dp0
 if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul  &  shift /1)

 ::::::::::::::::::::::::::::
 ::START
 ::::::::::::::::::::::::::::
 REM Run shell as admin (example) - put here code as you like
 ECHO %batchName% Arguments: P1=%1 P2=%2 P3=%3 P4=%4 P5=%5 P6=%6 P7=%7 P8=%8 P9=%9
 cmd /k

The script takes advantage of the fact that NET FILE requires administrator privilege and returns errorlevel 1 if you don't have it. The elevation is achieved by creating a script which re-launches the batch file to obtain privileges. This causes Windows to present the UAC dialog and asks you for the administrator account and password.

I have tested it with Windows 7, 8, 8.1, 10 and with Windows XP - it works fine for all. The advantage is, after the start point you can place anything that requires system administrator privileges, for example, if you intend to re-install and re-run a Windows service for debugging purposes (assumed that mypackage.msi is a service installer package):

msiexec /passive /x mypackage.msi
msiexec /passive /i mypackage.msi
net start myservice

Without this privilege elevating script, UAC would ask you three times for your administrator user and password - now you're asked only once at the beginning, and only if required.


If your script just needs to show an error message and exit if there aren't any administrator privileges instead of auto-elevating, this is even simpler: You can achieve this by adding the following at the beginning of your script:

@ECHO OFF & CLS & ECHO.
NET FILE 1>NUL 2>NUL & IF ERRORLEVEL 1 (ECHO You must right-click and select &
  ECHO "RUN AS ADMINISTRATOR"  to run this batch. Exiting... & ECHO. &
  PAUSE & EXIT /D)
REM ... proceed here with admin rights ...

This way, the user has to right-click and select "Run as administrator". The script will proceed after the REM statement if it detects administrator rights, otherwise exit with an error. If you don't require the PAUSE, just remove it. Important: NET FILE [...] EXIT /D) must be on the same line. It is displayed here in multiple lines for better readability!


On some machines, I've encountered issues, which are solved in the new version above already. One was due to different double quote handling, and the other issue was due to the fact that UAC was disabled (set to lowest level) on a Windows 7 machine, hence the script calls itself again and again.

I have fixed this now by stripping the quotes in the path and re-adding them later, and I've added an extra parameter which is added when the script re-launches with elevated rights.

The double quotes are removed by the following (details are here):

setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion

You can then access the path by using !batchPath!. It doesn't contain any double quotes, so it is safe to say "!batchPath!" later in the script.

The line

if '%1'=='ELEV' (shift & goto gotPrivileges)

checks if the script has already been called by the VBScript script to elevate rights, hence avoiding endless recursions. It removes the parameter using shift.


Update:

  • To avoid having to register the .vbs extension in Windows 10, I have replaced the line
    "%temp%\OEgetPrivileges.vbs"
    by
    "%SystemRoot%\System32\WScript.exe" "%temp%\OEgetPrivileges.vbs"
    in the script above; also added cd /d %~dp0 as suggested by Stephen (separate answer) and by Tomáš Zato (comment) to set script directory as default.

  • Now the script honors command line parameters being passed to it. Thanks to jxmallet, TanisDLJ and Peter Mortensen for observations and inspirations.

  • According to Artjom B.'s hint, I analyzed it and have replaced SHIFT by SHIFT /1, which preserves the file name for the %0 parameter

  • Added del "%temp%\OEgetPrivileges_%batchName%.vbs" to the :gotPrivileges section to clean up (as mlt suggested). Added %batchName% to avoid impact if you run different batches in parallel. Note that you need to use for to be able to take advantage of the advanced string functions, such as %%~nk, which extracts just the filename.

  • Optimized script structure, improvements (added variable vbsGetPrivileges which is now referenced everywhere allowing to change the path or name of the file easily, only delete .vbs file if batch needed to be elevated)

  • In some cases, a different calling syntax was required for elevation. If the script does not work, check the following parameters:
    set cmdInvoke=0
    set winSysFolder=System32
    Either change the 1st parameter to set cmdInvoke=1 and check if that already fixes the issue. It will add cmd.exe to the script performing the elevation.
    Or try to change the 2nd parameter to winSysFolder=Sysnative, this might help (but is in most cases not required) on 64 bit systems. (ADBailey has reported this). "Sysnative" is only required for launching 64-bit applications from a 32-bit script host (e.g. a Visual Studio build process, or script invocation from another 32-bit application).

  • To make it more clear how the parameters are interpreted, I am displaying it now like P1=value1 P2=value2 ... P9=value9. This is especially useful if you need to enclose parameters like paths in double quotes, e.g. "C:\Program Files".

  • If you want to debug the VBS script, you can add the //X parameter to WScript.exe as first parameter, as suggested here (it is described for CScript.exe, but works for WScript.exe too).

Useful links:

Graphviz: How to go from .dot to a graph?

For window user, Please run complete command to convert *.dot file to png:

C:\Program Files (x86)\Graphviz2.38\bin\dot.exe" -Tpng sampleTest.dot > sampletest.png.....

I have found a bug in solgraph that it is utilizing older version of solidity-parser that does not seem to be intelligent enough to capture new enhancement done for solidity programming language itself e.g. emit keyword for Event

Python - How to cut a string in Python?

Well, to answer the immediate question:

>>> s = "http://www.domain.com/?s=some&two=20"

The rfind method returns the index of right-most substring:

>>> s.rfind("&")
29

You can take all elements up to a given index with the slicing operator:

>>> "foobar"[:4]
'foob'

Putting the two together:

>>> s[:s.rfind("&")]
'http://www.domain.com/?s=some'

If you are dealing with URLs in particular, you might want to use built-in libraries that deal with URLs. If, for example, you wanted to remove two from the above query string:

First, parse the URL as a whole:

>>> import urlparse, urllib
>>> parse_result = urlparse.urlsplit("http://www.domain.com/?s=some&two=20")
>>> parse_result
SplitResult(scheme='http', netloc='www.domain.com', path='/', query='s=some&two=20', fragment='')

Take out just the query string:

>>> query_s = parse_result.query
>>> query_s
's=some&two=20'

Turn it into a dict:

>>> query_d = urlparse.parse_qs(parse_result.query)
>>> query_d
{'s': ['some'], 'two': ['20']}
>>> query_d['s']
['some']
>>> query_d['two']
['20']

Remove the 'two' key from the dict:

>>> del query_d['two']
>>> query_d
{'s': ['some']}

Put it back into a query string:

>>> new_query_s = urllib.urlencode(query_d, True)
>>> new_query_s
's=some'

And now stitch the URL back together:

>>> result = urlparse.urlunsplit((
    parse_result.scheme, parse_result.netloc,
    parse_result.path, new_query_s, parse_result.fragment))
>>> result
'http://www.domain.com/?s=some'

The benefit of this is that you have more control over the URL. Like, if you always wanted to remove the two argument, even if it was put earlier in the query string ("two=20&s=some"), this would still do the right thing. It might be overkill depending on what you want to do.

Node.js create folder or use existing

I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :

LAST UPDATE :

In v10.12.0, NodeJS impletement recursive options :

// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });

UPDATE :

// Get modules node
const fs   = require('fs');
const path = require('path');

// Create 
function mkdirpath(dirPath)
{
    if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
    {
        try
        {
            fs.mkdirSync(dirPath);
        }
        catch(e)
        {
            mkdirpath(path.dirname(dirPath));
            mkdirpath(dirPath);
        }
    }
}

// Create folder path
mkdirpath('my/new/folder/create');

How to know if a DateTime is between a DateRange in C#

I’ve found the following library to be the most helpful when doing any kind of date math. I’m still amazed nothing like this is part of the .Net framework.

http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

How to check file MIME type with javascript before upload?

Short answer is no.

As you note the browsers derive type from the file extension. Mac preview also seems to run off the extension. I'm assuming its because its faster reading the file name contained in the pointer, rather than looking up and reading the file on disk.

I made a copy of a jpg renamed with png.

I was able to consistently get the following from both images in chrome (should work in modern browsers).

ÿØÿàJFIFÿþ;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90

Which you could hack out a String.indexOf('jpeg') check for image type.

Here is a fiddle to explore http://jsfiddle.net/bamboo/jkZ2v/1/

The ambigious line I forgot to comment in the example

console.log( /^(.*)$/m.exec(window.atob( image.src.split(',')[1] )) );

  • Splits the base64 encoded img data, leaving on the image
  • Base64 decodes the image
  • Matches only the first line of the image data

The fiddle code uses base64 decode which wont work in IE9, I did find a nice example using VB script that works in IE http://blog.nihilogic.dk/2008/08/imageinfo-reading-image-metadata-with.html

The code to load the image was taken from Joel Vardy, who is doing some cool image canvas resizing client side before uploading which may be of interest https://joelvardy.com/writing/javascript-image-upload

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

How to select records from last 24 hours using SQL?

SELECT * 
FROM table_name
WHERE table_name.the_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)

How to display errors for my MySQLi query?

Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

 mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));

As a side note I'd say you are at risk of mysql injection, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.

Created Button Click Event c#

    public MainWindow()
    {
        // This button needs to exist on your form.
        myButton.Click += myButton_Click;
    }

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Message here");
        this.Close();
    }

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

Thnaks for your answers, it help me alot. as i code in Vb.Net, this Bolt code for Vb.Net

Try
   Return MyBase.SaveChanges()
Catch dbEx As Validation.DbEntityValidationException
   For Each [error] In From validationErrors In dbEx.EntityValidationErrors
                       From validationError In validationErrors.ValidationErrors
                       Select New With { .PropertyName = validationError.PropertyName,
                                         .ErrorMessage = validationError.ErrorMessage,
                                         .ClassFullName = validationErrors.Entry.Entity
                                                                    .GetType().FullName}

        Diagnostics.Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                                           [error].ClassFullName,
                                           [error].PropertyName,
                                           [error].ErrorMessage)
   Next
   Throw
End Try

How to assign a heredoc value to a variable in Bash?

this is variation of Dennis method, looks more elegant in the scripts.

function definition:

define(){ IFS='\n' read -r -d '' ${1} || true; }

usage:

define VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF

echo "$VAR"

enjoy

p.s. made a 'read loop' version for shells that do not support read -d. should work with set -eu and unpaired backticks, but not tested very well:

define(){ o=; while IFS="\n" read -r a; do o="$o$a"'
'; done; eval "$1=\$o"; }

SQL Server 2005 Using DateAdd to add a day to a date

DECLARE @MyDate datetime

-- ... set your datetime's initial value ...'

DATEADD(d, 1, @MyDate)

Make a nav bar stick

I hope this can help someone. Determine the nav offset through js and then apply sticky position css to nav:

But first, we will define the styles in the stylesheet, like so.

.sticky {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 100;
    border-top: 0;
}

Then, we will apply that class to the navigation conditionally with jQuery.

$(document).ready(function() {
  var stickyNavTop = $('.nav').offset().top;

  var stickyNav = function(){
    var scrollTop = $(window).scrollTop();

    if (scrollTop > stickyNavTop) { 
      $('.nav').addClass('sticky');
    } else {
      $('.nav').removeClass('sticky'); 
    }
  };

  stickyNav();

  $(window).scroll(function() {
    stickyNav();
  });
});

Remove sensitive files and their commits from Git history

Use filter-branch:

git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch *file_path_relative_to_git_repo*' --prune-empty --tag-name-filter cat -- --all

git push origin *branch_name* -f

Concatenating elements in an array to a string

Do it java 8 way in just 1 line:

String.join("", arr);

Which variable size to use (db, dw, dd) with x86 assembly?

Quick review,

  • DB - Define Byte. 8 bits
  • DW - Define Word. Generally 2 bytes on a typical x86 32-bit system
  • DD - Define double word. Generally 4 bytes on a typical x86 32-bit system

From x86 assembly tutorial,

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.

Your num is 1 byte. Try declaring it with DD so that it becomes 4 bytes and matches with pop semantics.

How to align this span to the right of the div?

If you can modify the HTML: http://jsfiddle.net/8JwhZ/3/

<div class="title">
  <span class="name">Cumulative performance</span>
  <span class="date">20/02/2011</span>
</div>

.title .date { float:right }
.title .name { float:left }

How to hide keyboard in swift on pressing return key?

All in One Hide Keyboard and Move View on Keyboard Open: Swift 5

override func viewDidLoad() {
    super.viewDidLoad()
    let tap = UITapGestureRecognizer(target: self, action: #selector(taped))
    view.addGestureRecognizer(tap)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}


   override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
 @objc func taped(){

    self.view.endEditing(true)

}

@objc func KeyboardWillShow(sender: NSNotification){

    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y == 0{
        self.view.frame.origin.y -= keyboardSize.height
    }


}

@objc func KeyboardWillHide(sender : NSNotification){

    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y != 0{
        self.view.frame.origin.y += keyboardSize.height
    }

}

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

How can I create persistent cookies in ASP.NET?

Here's how you can do that.

Writing the persistent cookie.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

Reading the persistent cookie.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
    //No cookie found or cookie expired.
    //Handle the situation here, Redirect the user or simply return;
}

//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}

Reading JSON from a file?

Here is a copy of code which works fine for me

import json

with open("test.json") as json_file:
    json_data = json.load(json_file)
    print(json_data)

with the data

{
    "a": [1,3,"asdf",true],
    "b": {
        "Hello": "world"
    }
}

you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.

How can I set the PATH variable for javac so I can manually compile my .java works?

That would be:

set "PATH=%PATH%;C:\Program Files\Java\jdk1.6.0_18\bin"

You can also append ;C:\Program Files\Java\jdk1.6.0_18\bin to the PATH in the user environment dialog. That would allow you to use javac and other java tools directly form any cmd shell without setting the path first. The user environment dialog used to be somewhere in the system properties in XP, I have no idea where it is in Windows 7.

Best way to check function arguments?

This is not the solution to you, but if you want to restrict the function calls to some specific parameter types then you must use the PROATOR { The Python Function prototype validator }. you can refer the following link. https://github.com/mohit-thakur-721/proator

What does -Xmn jvm option stands for

-Xmn : the size of the heap for the young generation Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor" .

Good size is 33%

Source

What is the difference between `new Object()` and object literal notation?

I have found one difference, for ES6/ES2015. You cannot return an object using the shorthand arrow function syntax, unless you surround the object with new Object().

> [1, 2, 3].map(v => {n: v});
[ undefined, undefined, undefined ]
> [1, 2, 3].map(v => new Object({n: v}));
[ { n: 1 }, { n: 2 }, { n: 3 } ]

This is because the compiler is confused by the {} brackets and thinks n: i is a label: statement construct; the semicolon is optional so it doesn't complain about it.

If you add another property to the object it will finally throw an error.

$ node -e "[1, 2, 3].map(v => {n: v, m: v+1});"
[1, 2, 3].map(v => {n: v, m: v+1});
                           ^

SyntaxError: Unexpected token :

Is there a way to make Firefox ignore invalid ssl-certificates?

The MitM Me addon will do this - but I think self-signed certificates is probably a better solution.

In Java, can you modify a List while iterating through it?

Use CopyOnWriteArrayList
and if you want to remove it, do the following:

for (Iterator<String> it = userList.iterator(); it.hasNext() ;)
{
    if (wordsToRemove.contains(word))
    {
        it.remove();
    }
}

Finding current executable's path without /proc/self/exe

The whereami library by Gregory Pakosz implements this for a variety of platforms, using the APIs mentioned in mark4o's post. This is most interesting if you "just" need a solution that works for a portable project and are not interested in the peculiarities of the various platforms.

At the time of writing, supported platforms are:

  • Windows
  • Linux
  • Mac
  • iOS
  • Android
  • QNX Neutrino
  • FreeBSD
  • NetBSD
  • DragonFly BSD
  • SunOS

The library consists of whereami.c and whereami.h and is licensed under MIT and WTFPL2. Drop the files into your project, include the header and use it:

#include "whereami.h"

int main() {
  int length = wai_getExecutablePath(NULL, 0, NULL);
  char* path = (char*)malloc(length + 1);
  wai_getExecutablePath(path, length, &dirname_length);
  path[length] = '\0';

  printf("My path: %s", path);

  free(path);
  return 0;
}

Git: Cannot see new remote branch

First, double check that the branch has been actually pushed remotely, by using the command git ls-remote origin. If the new branch appears in the output, try and give the command git fetch: it should download the branch references from the remote repository.

If your remote branch still does not appear, double check (in the ls-remote output) what is the branch name on the remote and, specifically, if it begins with refs/heads/. This is because, by default, the value of remote.<name>.fetch is:

+refs/heads/*:refs/remotes/origin/*

so that only the remote references whose name starts with refs/heads/ will be mapped locally as remote-tracking references under refs/remotes/origin/ (i.e., they will become remote-tracking branches)

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571