Programs & Examples On #Hitcounter

A web counter or hit counter is a computer software program that indicates the number of visitors, or hits, a particular webpage has received. Once set up, these counters will be incremented by one every time the web page is accessed in a web browser.

How do I check if a number is positive or negative in C#?

Of course no-one's actually given the correct answer,

num != 0   // num is positive *or* negative!

Is Django for the frontend or backend?

(a) Django is a framework, not a language

(b) I'm not sure what you're missing - there is no reason why you can't have business logic in a web application. In Django, you would normally expect presentation logic to be separated from business logic. Just because it is hosted in the same application server, it doesn't follow that the two layers are entangled.

(c) Django does provide templating, but it doesn't provide rich libraries for generating client-side content.

Android Studio - How to increase Allocated Heap Size

This is how you change the heap size currently in Android Studio 3.6.1

On Windows in your Android Studio:

  1. Select File -> Settings (the popup below will be displayed)

Settings Dialog

  1. Select Appearance & Behavior
  2. Select System Settings
  3. Select Memory Settings

Then change the IDE Heap Size settings to your desired value

On Mac:

  1. Select Android Studio
  2. Select Preferences

The same pop up will appear. However, this time on the Mac its called Preferences.

Follow the same steps as the Windows version of Android Studio to adjust the heap size wants the Preferences dialog has been displayed

python variable NameError

Initialize tSize to

tSize = ""  

before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.

R: rJava package install failing

On Arch Linux, I needed to install openjdk-src to get a JNI path working.

In other words, these are the packages I needed to install before sudo R CMD javareconf ran successfully:

local/jdk-openjdk 14.0.2.u12-1
    OpenJDK Java 14 development kit
local/jre-openjdk 14.0.2.u12-1
    OpenJDK Java 14 full runtime environment
local/jre-openjdk-headless 14.0.2.u12-1
    OpenJDK Java 14 headless runtime environment
local/openjdk-src 14.0.2.u12-1
    OpenJDK Java 14 sources

How do I get the last day of a month?

If you want the date, given a month and a year, this seems about right:

public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
    return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}

How to Clear Console in Java?

If you are using windows and are interested in clearing the screen before running the program, you can compile the file call it from a .bat file. for example:


cls

java "what ever the name of the compiles class is"


Save as "etc".bat and then running by calling it in the command prompt or double clicking the file

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

About list

First a very important point, from which everything will follow (I hope).

In ordinary Python, list is not special in any way (except having cute syntax for constructing, which is mostly a historical accident). Once a list [3,2,6] is made, it is for all intents and purposes just an ordinary Python object, like a number 3, set {3,7}, or a function lambda x: x+5.

(Yes, it supports changing its elements, and it supports iteration, and many other things, but that's just what a type is: it supports some operations, while not supporting some others. int supports raising to a power, but that doesn't make it very special - it's just what an int is. lambda supports calling, but that doesn't make it very special - that's what lambda is for, after all:).

About and

and is not an operator (you can call it "operator", but you can call "for" an operator too:). Operators in Python are (implemented through) methods called on objects of some type, usually written as part of that type. There is no way for a method to hold an evaluation of some of its operands, but and can (and must) do that.

The consequence of that is that and cannot be overloaded, just like for cannot be overloaded. It is completely general, and communicates through a specified protocol. What you can do is customize your part of the protocol, but that doesn't mean you can alter the behavior of and completely. The protocol is:

Imagine Python interpreting "a and b" (this doesn't happen literally this way, but it helps understanding). When it comes to "and", it looks at the object it has just evaluated (a), and asks it: are you true? (NOT: are you True?) If you are an author of a's class, you can customize this answer. If a answers "no", and (skips b completely, it is not evaluated at all, and) says: a is my result (NOT: False is my result).

If a doesn't answer, and asks it: what is your length? (Again, you can customize this as an author of a's class). If a answers 0, and does the same as above - considers it false (NOT False), skips b, and gives a as result.

If a answers something other than 0 to the second question ("what is your length"), or it doesn't answer at all, or it answers "yes" to the first one ("are you true"), and evaluates b, and says: b is my result. Note that it does NOT ask b any questions.

The other way to say all of this is that a and b is almost the same as b if a else a, except a is evaluated only once.

Now sit for a few minutes with a pen and paper, and convince yourself that when {a,b} is a subset of {True,False}, it works exactly as you would expect of Boolean operators. But I hope I have convinced you it is much more general, and as you'll see, much more useful this way.

Putting those two together

Now I hope you understand your example 1. and doesn't care if mylist1 is a number, list, lambda or an object of a class Argmhbl. It just cares about mylist1's answer to the questions of the protocol. And of course, mylist1 answers 5 to the question about length, so and returns mylist2. And that's it. It has nothing to do with elements of mylist1 and mylist2 - they don't enter the picture anywhere.

Second example: & on list

On the other hand, & is an operator like any other, like + for example. It can be defined for a type by defining a special method on that class. int defines it as bitwise "and", and bool defines it as logical "and", but that's just one option: for example, sets and some other objects like dict keys views define it as a set intersection. list just doesn't define it, probably because Guido didn't think of any obvious way of defining it.

numpy

On the other leg:-D, numpy arrays are special, or at least they are trying to be. Of course, numpy.array is just a class, it cannot override and in any way, so it does the next best thing: when asked "are you true", numpy.array raises a ValueError, effectively saying "please rephrase the question, my view of truth doesn't fit into your model". (Note that the ValueError message doesn't speak about and - because numpy.array doesn't know who is asking it the question; it just speaks about truth.)

For &, it's completely different story. numpy.array can define it as it wishes, and it defines & consistently with other operators: pointwise. So you finally get what you want.

HTH,

SQL Select between dates

Or you can cast your string to Date format with date function. Even the date is stored as TEXT in the DB. Like this (the most workable variant):

SELECT * FROM test WHERE date(date) 
BETWEEN date('2011-01-11') AND date('2011-8-11')

JavaScript hard refresh of current page

window.location.href = window.location.href

How can I scale an image in a CSS sprite

Easy... Using two copies of same image with different scale on the sprite's sheet. Set the Coords and size on the app's logic.

Hunk #1 FAILED at 1. What's that mean?

I got the "hunks failed" message when I wasn't applying the patch in the top directory of the associated git project. I was applying the patch (where I created it) in a subdirectory.

It seems patches can be created from subdirectories within a git project, but not applied.

Inserting a tab character into text using C#

var text = "Ann@26"

var editedText = text.Replace("@", "\t");

How to add header data in XMLHttpRequest when using formdata?

Check to see if the key-value pair is actually showing up in the request:

In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers

Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like: F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.

But as other answers have said:

xhttp.setRequestHeader(key, value);

should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

maven error: package org.junit does not exist

I fixed this error by inserting these lines of code:

<dependency>
  <groupId>junit</groupId>     <!-- NOT org.junit here -->
  <artifactId>junit-dep</artifactId>
  <version>4.8.2</version>
  <scope>test</scope>
</dependency>

into <dependencies> node.

more details refer to: http://mvnrepository.com/artifact/junit/junit-dep/4.8.2

Convert Java string to Time, NOT Date

You might consider Joda Time or Java 8, which has a type called LocalTime specifically for a time of day without a date component.

Example code in Joda-Time 2.7/Java 8.

LocalTime t = LocalTime.parse( "17:40" ) ;

Set value of textarea in jQuery

textarea doesn't store values as

<textarea value="someString">

instead, it stores values in this format:

<textarea>someString</textarea>

So attr("value","someString") gets you this result:

<textarea value="someString">someOLDString</textarea>.

try $("#textareaid").val() or $("#textareaid").innerHTML instead.

How can I find all the subsets of a set, with exactly n elements?

Here's a function that gives you all subsets of the integers [0..n], not just the subsets of a given length:

from itertools import combinations, chain

def allsubsets(n):
    return list(chain(*[combinations(range(n), ni) for ni in range(n+1)]))

so e.g.

>>> allsubsets(3)
[(), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]

Python sys.argv lists and indexes

sys.argv is the list of arguments passed to the Python program. The first argument, sys.argv[0], is actually the name of the program as it was invoked. That's not a Python thing, but how most operating systems work. The reason sys.argv[0] exists is so you can change your program's behaviour depending on how it was invoked. sys.argv[1] is thus the first argument you actually pass to the program.

Because lists (like most sequences) in Python start indexing at 0, and because indexing past the end of the list is an error, you need to check if the list has length 2 or longer before you can access sys.argv[1].

How to install wkhtmltopdf on a linux based (shared hosting) web server

After trying, below command work for me

cd ~
yum install -y xorg-x11-fonts-75dpi xorg-x11-fonts-Type1 openssl git-core fontconfig
wget https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar xvf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
mv wkhtmltox/bin/wkhtmlto* /usr/bin

Where are static variables stored in C and C++?

Data declared in a compilation unit will go into the .BSS or the .Data of that files output. Initialised data in BSS, uninitalised in DATA.

The difference between static and global data comes in the inclusion of symbol information in the file. Compilers tend to include the symbol information but only mark the global information as such.

The linker respects this information. The symbol information for the static variables is either discarded or mangled so that static variables can still be referenced in some way (with debug or symbol options). In neither case can the compilation units gets affected as the linker resolves local references first.

Looping through all rows in a table column, Excel-VBA

You can find the last column of table and then fill the cell by looping throught it.

Sub test()
    Dim lastCol As Long, i As Integer
    lastCol = Range("AZ1").End(xlToLeft).Column
        For i = 1 To lastCol
            Cells(1, i).Value = "PHEV"
        Next
End Sub

How can I use jQuery to make an input readonly?

Given -

<input name="foo" type="text" value="foo" readonly />

this works - (jquery 1.7.1)

$('input[name="foo"]').prop('readonly', true);

tested with readonly and readOnly - both worked.

shuffling/permutating a DataFrame in pandas

Sampling randomizes, so just sample the entire data frame.

df.sample(frac=1)

VBScript How can I Format Date?

The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.

If you want your output to be "culture invariant", use myDateFormat() from stian.net's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use

Replace(FormatDateTime(d,2),"/","-")

How to validate an email address in PHP

Use below code:

// Variable to check
$email = "[email protected]";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo("Email is a valid email address");
} else {
  echo("Oppps! Email is not a valid email address");
}

Unable to use Intellij with a generated sources folder

Maybe you can add a step to the generate-sources phase that moves the folder?

Is there a naming convention for git repositories?

lowercase-with-hyphens is the style I most often see on GitHub.*

lowercase_with_underscores is probably the second most popular style I see.

The former is my preference because it saves keystrokes.

* Anecdotal; I haven't collected any data.

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

How to customize an end time for a YouTube video?

I tried the method of @mystic11 ( https://stackoverflow.com/a/11422551/506073 ) and got redirected around. Here is a working example URL:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3

If the version=3 parameter is omitted, the video starts at the correct place but runs all the way to the end. From the documentation for the end parameter I am guessing version=3 asks for the AS3 player to be used. See:

end (supported players: AS3, HTML5)

Additional Experiments

Autoplay

Autoplay of the clipped video portion works:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1

Looping

Adding looping as per the documentation unfortunately starts the second and subsequent iterations at the beginning of the video: http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&loop=1&playlist=WA8sLsM3McU

To do this properly, you probably need to set enablejsapi=1 and use the javascript API.

FYI, the above video looped: http://www.infinitelooper.com/?v=WA8sLsM3McU&p=n#/15;19

Remove Branding and Related Videos

To get rid of the Youtube logo and the list of videos to click on to at the end of playing the video you want to watch, add these (&modestBranding=1&rel=0) parameters:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1&modestBranding=1&rel=0

Remove the uploader info with showinfo=0:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1&modestBranding=1&rel=0&showinfo=0

This eliminates the thin strip with video title, up and down thumbs, and info icon at the top of the video. The final version produced is fairly clean and doesn't have the downside of giving your viewers an exit into unproductive clicking around Youtube at the end of watching the video portion that you wanted them to see.

What does MVW stand for?

It stands indeed for whatever, as in whatever works for you

MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.

For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.

Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Flutter- wrapping text

If it's a single text widget that you want to wrap, you can either use Flexible or Expanded widgets.

Expanded(
  child: Text('Some lengthy text for testing'),
)

or

Flexible(
  child: Text('Some lengthy text for testing'),
)

For multiple widgets, you may choose Wrap widget. For further details checkout this

Using scanner.nextLine()

It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". Primitive data types like int, double etc do not consume "end of line", therefore the "end of line" remains in buffer and When input.next() executes, it consumes the "end of line" from buffer from the first input. That's why, your String sentence = scanner.next() only consumes the "end of line" and does not wait to read from keyboard.

Tip: use scanner.nextLine() instead of scanner.next() because scanner.next() does not read white spaces from the keyboard. (Truncate the string after giving some space from keyboard, only show string before space.)

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

To use arrow functions with function.prototype.call, I made a helper function on the object prototype:

  // Using
  // @func = function() {use this here} or This => {use This here}
  using(func) {
    return func.call(this, this);
  }

usage

  var obj = {f:3, a:2}
  .using(This => This.f + This.a) // 5

Edit

You don't NEED a helper. You could do:

var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5

Detecting a mobile browser

How about:

if (typeof window.orientation !== 'undefined') { ... }

...since smartphones usually support this property and desktop browsers don't.

EDIT: As @Gajus pointed out, this solution is now deprecated and shouldn't be used (https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation)

How to remove selected commit log entries from a Git repository while keeping their changes?

git-rebase(1) does exactly that.

$ git rebase -i HEAD~5

git awsome-ness [git rebase --interactive] contains an example.

  1. Don't use git-rebase on public (remote) commits.
  2. Make sure your working directory is clean (commit or stash your current changes).
  3. Run the above command. It launches your $EDITOR.
  4. Replace pick before C and D by squash. It will meld C and D into B. If you want to delete a commit then just delete its line.

If you are lost, type:

$ git rebase --abort  

How to create a new branch from a tag?

An exemple of the only solution that works for me in the simple usecase where I am on a fork and I want to checkout a new branch from a tag that is on the main project repository ( here upstream )

git fetch upstream --tags

Give me

From https://github.com/keycloak/keycloak
   90b29b0e31..0ba9055d28  stage      -> upstream/stage
 * [new tag]    11.0.0     -> 11.0.0

Then I can create a new branch from this tag and checkout on it

git checkout -b tags/<name> <newbranch>

git checkout tags/11.0.0 -b v11.0.0

How to configure welcome file list in web.xml

This is my way to setup Servlet as welcome page.

I share for whom concern.

web.xml

  <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Demo</servlet-name>
        <servlet-class>servlet.Demo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Demo</servlet-name>
        <url-pattern></url-pattern>
    </servlet-mapping>

Servlet class

@WebServlet(name = "/demo")
public class Demo extends HttpServlet {
   public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException  {
       RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
   }
}

How to check if an excel cell is empty using Apache POI?

There is one other option also .

row=(Row) sheet.getRow(i);
        if (row == null || isEmptyRow(row)) {
            return;
        }
Iterator<Cell> cells = row.cellIterator();
    while (cells.hasNext())
     {}

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

How to Increase Import Size Limit in phpMyAdmin

Change these values in php.ini

post_max_size = 750M 
upload_max_filesize = 750M 
max_execution_time = 5000 
max_input_time = 5000 
memory_limit = 1000M 

Then restart Wamp for the changes to take effect. It will take some time. If you get following error:

Script timeout passed if you want to finish import please resubmit same zip file and import will resume.

Then update the phpMyAdmin configuration, at phpMyAdmin\libraries\config.default.php

/**
 * maximum execution time in seconds (0 for no limit)
 *
 * @global integer $cfg['ExecTimeLimit']
 */
$cfg['ExecTimeLimit'] = 0;

Get Cell Value from a DataTable in C#

To get cell column name as well as cell value :

List<JObject> dataList = new List<JObject>();

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    JObject eachRowObj = new JObject();

    for (int j = 0; j < dataTable.Columns.Count; j++)
    {
        string key = Convert.ToString(dataTable.Columns[j]);
        string value = Convert.ToString(dataTable.Rows[i].ItemArray[j]);

        eachRowObj.Add(key, value);

    }

    dataList.Add(eachRowObj);

}

Preferred method to store PHP arrays (json_encode vs serialize)

If to summ up what people say here, json_decode/encode seems faster than serialize/unserialize BUT If you do var_dump the type of the serialized object is changed. If for some reason you want to keep the type, go with serialize!

(try for example stdClass vs array)

serialize/unserialize:

Array cache:
array (size=2)
  'a' => string '1' (length=1)
  'b' => int 2
Object cache:
object(stdClass)[8]
  public 'field1' => int 123
This cache:
object(Controller\Test)[8]
  protected 'view' => 

json encode/decode

Array cache:
object(stdClass)[7]
  public 'a' => string '1' (length=1)
  public 'b' => int 2
Object cache:
object(stdClass)[8]
  public 'field1' => int 123
This cache:
object(stdClass)[8]

As you can see the json_encode/decode converts all to stdClass, which is not that good, object info lost... So decide based on needs, especially if it is not only arrays...

How to correctly use the ASP.NET FileUpload control

My solution in code behind was:

System.Web.UI.WebControls.FileUpload fileUpload;

I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.

Docker Error bind: address already in use

A variation of @DmitrySandalov's answer: I had tomcat/java running on 8080, which needed to keep going. Looked at the docker-compose.yml file and altered the entry for 8080 to another of my choosing.

nginx:
  build: nginx
  ports:
    #- '8080:80' <-- original entry
    - '8880:80'
    - '8443:443'

Worked perfectly. (The only wrinkle is the change will be wiped if I ever update the project, since it's coming from an external repo.)

Rotating a two-dimensional array in Python

There are three parts to this:

  1. original[::-1] reverses the original array. This notation is Python list slicing. This gives you a "sublist" of the original list described by [start:end:step], start is the first element, end is the last element to be used in the sublist. step says take every step'th element from first to last. Omitted start and end means the slice will be the entire list, and the negative step means that you'll get the elements in reverse. So, for example, if original was [x,y,z], the result would be [z,y,x]
  2. The * when preceding a list/tuple in the argument list of a function call means "expand" the list/tuple so that each of its elements becomes a separate argument to the function, rather than the list/tuple itself. So that if, say, args = [1,2,3], then zip(args) is the same as zip([1,2,3]), but zip(*args) is the same as zip(1,2,3).
  3. zip is a function that takes n arguments each of which is of length m and produces a list of length m, the elements of are of length n and contain the corresponding elements of each of the original lists. E.g., zip([1,2],[a,b],[x,y]) is [[1,a,x],[2,b,y]]. See also Python documentation.

AngularJS - Any way for $http.post to send request parameters instead of JSON?

I think the params config parameter won't work here since it adds the string to the url instead of the body but to add to what Infeligo suggested here is an example of the global override of a default transform (using jQuery param as an example to convert the data to param string).

Set up global transformRequest function:

var app = angular.module('myApp');

app.config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return $.param(data);
    }
});

That way all calls to $http.post will automatically transform the body to the same param format used by the jQuery $.post call.

Note you may also want to set the Content-Type header per call or globally like this:

$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

Sample non-global transformRequest per call:

    var transform = function(data){
        return $.param(data);
    }

    $http.post("/foo/bar", requestData, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        transformRequest: transform
    }).success(function(responseData) {
        //do stuff with response
    });

Selecting all text in HTML text input when clicked

The exact solution to what you asked is :

<input type="text" id="userid" name="userid" value="Please enter the user ID" onClick="this.setSelectionRange(0, this.value.length)"/>

But I suppose,you are trying to show "Please enter the user ID" as a placeholder or hint in the input. So,you can use the following as a more efficient solution:

<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />

How to check if a Unix .tar.gz file is a valid file without uncompressing?

you could probably use the gzip -t option to test the files integrity

http://linux.about.com/od/commands/l/blcmdl1_gzip.htm

from: http://unix.ittoolbox.com/groups/technical-functional/shellscript-l/how-to-test-file-integrity-of-targz-1138880

To test the gzip file is not corrupt:

gunzip -t file.tar.gz

To test the tar file inside is not corrupt:

gunzip -c file.tar.gz | tar -t > /dev/null

As part of the backup you could probably just run the latter command and check the value of $? afterwards for a 0 (success) value. If either the tar or the gzip has an issue, $? will have a non zero value.

Access Controller method from another controller in Laravel 5

//In Controller A
public static function function1(){

}

In Controller B, View or anywhere
A::function1();

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is unsigned 16-bit integer.

unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535). In practice, it usually is 16-bit, but you can't take that as guaranteed.

Note:

  1. If you want a portable unsigned 16-bit integer, use uint16_t.
  2. inttypes.h and stdint.h are both introduced in C99. If you are using C89, define your own type.
  3. uint16_t may not be provided in certain implementation(See reference below), but unsigned short int is always available.

Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types

For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).

Grouping switch statement cases together?

AFAIK all you can do is omit the returns to make things more compact in C++:

switch(Answer)
{
    case 1: case 2: case 3: case 4:
        cout << "You need more cars.";
        break;
    ...
}

(You could remove the other returns as well, of course.)

Adding ID's to google map markers

JavaScript is a dynamic language. You could just add it to the object itself.

var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};

Also, because all v3 objects extend MVCObject(). You can use:

marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");

OperationalError, no such column. Django

The most direct way of solving this type of problem is just the following 3 steps process:

  1. Delete all the migration related files from app's migrations folder/directory (these basically starts with 0001, 0002, 0003 etc).

  2. Delete/Rename the existing database file named db.sqlite3 from App directory.

  3. Now run the following command:

    python manage.py migrate

    Finally execute

    python manage.py createsuperuser

    to perform the administrative tasks (If you want).

How to add a delay for a 2 or 3 seconds

System.Threading.Thread.Sleep(
    (int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);

Or with using statements:

Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);

I prefer this to 1000 * numSeconds (or simply 3000) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep before. It better documents your intent.

Got a NumberFormatException while trying to parse a text file for objects

NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc" value to integer..

this is valid string is eg"123". in your case split by space..

split(" "); will split line by " " by space..

"The page you are requesting cannot be served because of the extension configuration." error message

In case this helps anyone, I was getting this error when attempting to run aspnet_regiis.exe:

Operation failed with 0x8007000B

An attempt was made to load a program with an incorrect format

As it turns out, the server was running 2008 64 bit and I was trying to run the 32 bit version of the utility. Running the version found in \Windows\Microsoft.NET\Framework64\v2.0.50727 fixed the issue.

c:\Windows\Microsoft.NET\Framework64\v2.0.50727>aspnet_regiis.exe -i

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Suppose you have text field and submit button,

<input type="text" id="text-field" />
<input type="submit" class="btn" value="Submit"/>

Disabling:

To disable any button, for example, submit button you just need to add disabled attribute as,

$('input[type="submit"]').attr('disabled','disabled');

After executing above line, your submit button html tag would look like this:

<input type="submit" class="btn" value="Submit" disabled/>

Notice the 'disabled' attribute has added.

Enabling:

For enabling button, such as when you have some text in text field. You will need to remove the disable attribute to enable button as,

 if ($('#text-field').val() != '') {
     $('input[type="submit"]').removeAttr('disabled');
 }

Now the above code will remove the 'disabled' attribute.

Execute and get the output of a shell command in node.js

If you're using node later than 7.6 and you don't like the callback style, you can also use node-util's promisify function with async / await to get shell commands which read cleanly. Here's an example of the accepted answer, using this technique:

const { promisify } = require('util');
const exec = promisify(require('child_process').exec)

module.exports.getGitUser = async function getGitUser () {
  const name = await exec('git config --global user.name')
  const email = await exec('git config --global user.email')
  return { name, email }
};

This also has the added benefit of returning a rejected promise on failed commands, which can be handled with try / catch inside the async code.

Can I change the scroll speed using css or jQuery?

I just made a pure Javascript function based on that code. Javascript only version demo: http://jsbin.com/copidifiji

That is the independent code from jQuery

if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false); 
window.onmousewheel = document.onmousewheel = wheel;}

function wheel(event) {
    var delta = 0;
    if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
    else if (event.detail) delta = -(event.detail)/3;

    handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}

function handle(sentido) {
    var inicial = document.body.scrollTop;
    var time = 1000;
    var distance = 200;
  animate({
    delay: 0,
    duration: time,
    delta: function(p) {return p;},
    step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);   
    }});}

function animate(opts) {
  var start = new Date();
  var id = setInterval(function() {
    var timePassed = new Date() - start;
    var progress = (timePassed / opts.duration);
    if (progress > 1) {progress = 1;}
    var delta = opts.delta(progress);
    opts.step(delta);
    if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}

Bootstrap change div order with pull-right, pull-left on 3 columns

Bootstrap 3

Using Bootstrap 3's grid system:

<div class="container">
  <div class="row">
    <div class="col-xs-4">Menu</div>
    <div class="col-xs-8">
      <div class="row">
        <div class="col-md-4 col-md-push-8">Right Content</div>
        <div class="col-md-8 col-md-pull-4">Content</div>
      </div>
    </div>
  </div>
</div>

Working example: http://bootply.com/93614

Explanation

First, we set two columns that will stay in place no matter the screen resolution (col-xs-*).

Next, we divide the larger, right hand column in to two columns that will collapse on top of each other on tablet sized devices and lower (col-md-*).

Finally, we shift the display order using the matching class (col-md-[push|pull]-*). You push the first column over by the amount of the second, and pull the second by the amount of the first.

AddTransient, AddScoped and AddSingleton Services Differences

TL;DR

Transient objects are always different; a new instance is provided to every controller and every service.

Scoped objects are the same within a request, but different across different requests.

Singleton objects are the same for every object and every request.

For more clarification, this example from .NET documentation shows the difference:

To demonstrate the difference between these lifetime and registration options, consider a simple interface that represents one or more tasks as an operation with a unique identifier, OperationId. Depending on how we configure the lifetime for this service, the container will provide either the same or different instances of the service to the requesting class. To make it clear which lifetime is being requested, we will create one type per lifetime option:

using System;

namespace DependencyInjectionSample.Interfaces
{
    public interface IOperation
    {
        Guid OperationId { get; }
    }

    public interface IOperationTransient : IOperation
    {
    }

    public interface IOperationScoped : IOperation
    {
    }

    public interface IOperationSingleton : IOperation
    {
    }

    public interface IOperationSingletonInstance : IOperation
    {
    }
}

We implement these interfaces using a single class, Operation, that accepts a GUID in its constructor, or uses a new GUID if none is provided:

using System;
using DependencyInjectionSample.Interfaces;
namespace DependencyInjectionSample.Classes
{
    public class Operation : IOperationTransient, IOperationScoped, IOperationSingleton, IOperationSingletonInstance
    {
        Guid _guid;
        public Operation() : this(Guid.NewGuid())
        {

        }

        public Operation(Guid guid)
        {
            _guid = guid;
        }

        public Guid OperationId => _guid;
    }
}

Next, in ConfigureServices, each type is added to the container according to its named lifetime:

services.AddTransient<IOperationTransient, Operation>();
services.AddScoped<IOperationScoped, Operation>();
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
services.AddTransient<OperationService, OperationService>();

Note that the IOperationSingletonInstance service is using a specific instance with a known ID of Guid.Empty, so it will be clear when this type is in use. We have also registered an OperationService that depends on each of the other Operation types, so that it will be clear within a request whether this service is getting the same instance as the controller, or a new one, for each operation type. All this service does is expose its dependencies as properties, so they can be displayed in the view.

using DependencyInjectionSample.Interfaces;

namespace DependencyInjectionSample.Services
{
    public class OperationService
    {
        public IOperationTransient TransientOperation { get; }
        public IOperationScoped ScopedOperation { get; }
        public IOperationSingleton SingletonOperation { get; }
        public IOperationSingletonInstance SingletonInstanceOperation { get; }

        public OperationService(IOperationTransient transientOperation,
            IOperationScoped scopedOperation,
            IOperationSingleton singletonOperation,
            IOperationSingletonInstance instanceOperation)
        {
            TransientOperation = transientOperation;
            ScopedOperation = scopedOperation;
            SingletonOperation = singletonOperation;
            SingletonInstanceOperation = instanceOperation;
        }
    }
}

To demonstrate the object lifetimes within and between separate individual requests to the application, the sample includes an OperationsController that requests each kind of IOperation type as well as an OperationService. The Index action then displays all of the controller’s and service’s OperationId values.

using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;
using Microsoft.AspNetCore.Mvc;

namespace DependencyInjectionSample.Controllers
{
    public class OperationsController : Controller
    {
        private readonly OperationService _operationService;
        private readonly IOperationTransient _transientOperation;
        private readonly IOperationScoped _scopedOperation;
        private readonly IOperationSingleton _singletonOperation;
        private readonly IOperationSingletonInstance _singletonInstanceOperation;

        public OperationsController(OperationService operationService,
            IOperationTransient transientOperation,
            IOperationScoped scopedOperation,
            IOperationSingleton singletonOperation,
            IOperationSingletonInstance singletonInstanceOperation)
        {
            _operationService = operationService;
            _transientOperation = transientOperation;
            _scopedOperation = scopedOperation;
            _singletonOperation = singletonOperation;
            _singletonInstanceOperation = singletonInstanceOperation;
        }

        public IActionResult Index()
        {
            // ViewBag contains controller-requested services
            ViewBag.Transient = _transientOperation;
            ViewBag.Scoped = _scopedOperation;
            ViewBag.Singleton = _singletonOperation;
            ViewBag.SingletonInstance = _singletonInstanceOperation;

            // Operation service has its own requested services
            ViewBag.Service = _operationService;
            return View();
        }
    }
}

Now two separate requests are made to this controller action:

First Request

Second Request

Observe which of the OperationId values varies within a request, and between requests.

  • Transient objects are always different; a new instance is provided to every controller and every service.

  • Scoped objects are the same within a request, but different across different requests

  • Singleton objects are the same for every object and every request (regardless of whether an instance is provided in ConfigureServices)

WCF, Service attribute value in the ServiceHost directive could not be found

Add reference of service in your service or copy dll.

'MOD' is not a recognized built-in function name

It can be done using % operator. i.e. SELECT 50 % 5

"unrecognized import path" with go get

I had exactly the same issue, after moving from old go version (installed from old PPA) to newer (1.2.1) default packages in ubuntu 14.04.

The first step was to purge existing go:

sudo apt-get purge golang*

Which outputs following warnings:

dpkg: warning: while removing golang-go, directory '/usr/lib/go/src' not empty so not removed
dpkg: warning: while removing golang-go.tools, directory '/usr/lib/go' not empty so not removed

It looks like removing go leaves some files behind, which in turn can confuse newer install. More precisely, installation itself will complete fine, but afterwards any go command, like "go get something" gives those "unrecognized import path" errors.

All I had to do was to remove those dirs first, reinstall golang, and all works like a charm (assuming you also set GOPATH)

# careful!
sudo rm -rf /usr/lib/go /usr/lib/go/src
sudo apt-get install golang-go golang-go.tools

How to import a Python class that is in a directory above?

Import module from a directory which is exactly one level above the current directory:

from .. import module

Min/Max-value validators in asp.net mvc

A complete example of how this could be done. To avoid having to write client-side validation scripts, the existing ValidationType = "range" has been used.

public class MinValueAttribute : ValidationAttribute, IClientValidatable
{
    private readonly double _minValue;

    public MinValueAttribute(double minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;  
    }

    public MinValueAttribute(int minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;
    }

    public override bool IsValid(object value)
    {
        return Convert.ToDouble(value) >= _minValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = ErrorMessage;
        rule.ValidationParameters.Add("min", _minValue);
        rule.ValidationParameters.Add("max", Double.MaxValue);
        rule.ValidationType = "range";
        yield return rule;
    }

}

CSS property to pad text inside of div

Just use div { padding: 20px; } and substract 40px from your original div width.

Like Philip Wills pointed out, you can also use box-sizing instead of substracting 40px:

div {
    padding: 20px;
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

The -moz-box-sizing is for Firefox.

How do I implement __getattribute__ without an infinite recursion error?

Python language reference:

In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

Meaning:

def __getattribute__(self,name):
    ...
        return self.__dict__[name]

You're calling for an attribute called __dict__. Because it's an attribute, __getattribute__ gets called in search for __dict__ which calls __getattribute__ which calls ... yada yada yada

return  object.__getattribute__(self, name)

Using the base classes __getattribute__ helps finding the real attribute.

MySql Error: 1364 Field 'display_name' doesn't have default value

MySQL is most likely in STRICT mode, which isn't necessarily a bad thing, as you'll identify bugs/issues early and not just blindly think everything is working as you intended.

Change the column to allow null:

ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NULL

or, give it a default value as empty string:

ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NOT NULL DEFAULT ''

Changing the page title with Jquery

using

$('title').html("new title");

A tool to convert MATLAB code to Python

There are several tools for converting Matlab to Python code.

The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

Other options include:

  • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
  • OMPC: Matlab to Python (a bit outdated).

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
  • Python-Matlab wormholes: both directions of interaction supported.
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
  • PyMat: Control Matlab session from Python.
  • pymat2: continuation of the seemingly abandoned PyMat.
  • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
  • oct2py: run GNU Octave commands from within Python.
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

UTF-8 output from PowerShell

This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.

When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.

As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.

Caching example:

102 [C:\Users\leeholm]
>> $r1 = [Console]::Out

103 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US



104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

105 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US

XPath to fetch SQL XML value

Update

My recomendation would be to shred the XML into relations and do searches and joins on the resulted relation, in a set oriented fashion, rather than the procedural fashion of searching specific nodes in the XML. Here is a simple XML query that shreds out the nodes and attributes of interest:

select x.value(N'../../../../@stepId', N'int') as StepID
  , x.value(N'../../@id', N'int') as ComponentID
  , x.value(N'@nom',N'nvarchar(100)') as Nom
  , x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)

However, if you must use an XPath that retrieves exactly the value of interest:

select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
       variables/variable[@nom="Enabled"]') t(x)

If the stepID and component ID are columns, not variables, the you should use sql:column() instead of sql:variable in the XPath filters. See Binding Relational Data Inside XML Data.

And finaly if all you need is to check for existance you can use the exist() XML method:

select @x.exist(
  N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
      variables/variable[@nom="Enabled" and @valeur="Yes"]') 

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

How to negate the whole regex?

\b(?=\w)(?!(ma|(t){1}))\b(\w*)

this is for the given regex.
the \b is to find word boundary.
the positive look ahead (?=\w) is here to avoid spaces.
the negative look ahead over the original regex is to prevent matches of it.
and finally the (\w*) is to catch all the words that are left.
the group that will hold the words is group 3.
the simple (?!pattern) will not work as any sub-string will match
the simple ^(?!(?:m{2}|t)$).*$ will not work as it's granularity is full lines

Convert blob to base64

var audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;

var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
     base64data = reader.result;
     console.log(base64data);
}

How to embed an autoplaying YouTube video in an iframe?

Multiple queries tip for those who don't know (past me and future me)

If you're making a single query with the url just ?autoplay=1 works as shown by mjhm's answer

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1"></iframe>

If you're making multiple queries remember the first one begins with a ? while the rest begin with a &

Say you want to turn off related videos but enable autoplay...

This works

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0&autoplay=1"></iframe>

and this works

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&rel=0"></iframe>

But these won't work..

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0?autoplay=1"></iframe>

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0&autoplay=1&rel=0"></iframe>

example comparisons

https://jsfiddle.net/Hastig/p4dpo5y4/

more info

Read NextLocal's reply below for more info about using multiple query strings

"NoClassDefFoundError: Could not initialize class" error

I recently ran into this error on Windows 10. It turned out that windows was looking for .dll files necessary for my project and couldn't find them because it looks for them in the system path, PATH, rather than the CLASSPATH or -Djava.library.path

Where could I buy a valid SSL certificate?

You are really asking a couple of questions here:

1) Why does the price of SSL certificates vary so much

2) Where can I get good, cheap SSL certificates?

The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).

You can read more on this subject here

For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.

How to download folder from putty using ssh client

You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.

Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html

No line-break after a hyphen

Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character &#8288; on either side of your hyphen, or em dash, or any character.

So, like so:

&#8288;—&#8288;

This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.

Use ffmpeg to add text subtitles

You are trying to mux subtitles as a subtitle stream. It is easy but different syntax is used for MP4 (or M4V) and MKV. In both cases you must specify video and audio codec, or just copy stream if you just want to add subtitle.

MP4:

ffmpeg -i input.mp4 -f srt -i input.srt \
-map 0:0 -map 0:1 -map 1:0 -c:v copy -c:a copy \
-c:s mov_text output.mp4

MKV:

ffmpeg -i input.mp4 -f srt -i input.srt \
-map 0:0 -map 0:1 -map 1:0 -c:v copy -c:a copy \
-c:s srt  output.mkv

Entity Framework 6 Code first Default value

Set the default value for the column in table in MSSQL Server, and in class code add attribute, like this:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

for the same property.

Javascript Src Path

The common practice is to put scripts in a discrete folder, typically at the root of the site. So, if clock.js lived here:

/js/clock.js

then you could add this code to the top of any page in your site and it would just work:

<script src="/js/clock.js" type="text/javascript"></script>

How can I get a resource "Folder" from inside my jar File?

Simple ... use OSGi. In OSGi you can iterate over your Bundle's entries with findEntries and findPaths.

Python list directory, subdirectory, and files

Here is a one-liner:

import os

[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text

The outer most val for sublist in ... loop flattens the list to be one dimensional. The j loop collects a list of every file basename and joins it to the current path. Finally, the i loop iterates over all directories and sub directories.

This example uses the hard-coded path ./ in the os.walk(...) call, you can supplement any path string you like.

Note: os.path.expanduser and/or os.path.expandvars can be used for paths strings like ~/

Extending this example:

Its easy to add in file basename tests and directoryname tests.

For Example, testing for *.jpg files:

... for j in i[2] if j.endswith('.jpg')] ...

Additionally, excluding the .git directory:

... for i in os.walk('./') if '.git' not in i[0].split('/')]

How to read integer value from the standard input in Java

Second answer above is the most simple one.

int n = Integer.parseInt(System.console().readLine());

The question is "How to read from standard input".

A console is a device typically associated to the keyboard and display from which a program is launched.

You may wish to test if no Java console device is available, e.g. Java VM not started from a command line or the standard input and output streams are redirected.

Console cons;
if ((cons = System.console()) == null) {
    System.err.println("Unable to obtain console");
    ...
}

Using console is a simple way to input numbers. Combined with parseInt()/Double() etc.

s = cons.readLine("Enter a int: ");
int i = Integer.parseInt(s);    

s = cons.readLine("Enter a double: ");
double d = Double.parseDouble(s);

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

PHP, getting variable from another php-file

You can, but the variable in your last include will overwrite the variable in your first one:

myfile.php

$var = 'test';

mysecondfile.php

$var = 'tester';

test.php

include 'myfile.php';
echo $var;

include 'mysecondfile.php';
echo $var;

Output:

test

tester

I suggest using different variable names.

How to export settings?

With the current version of Visual Studio Code as of this writing (1.22.1), you can find your settings in

  • ~/.config/Code/User on Linux (in my case, an, Ubuntu derivative)
  • C:\Users\username\AppData\Roaming\Code\User on Windows 10
  • ~/Library/Application Support/Code/User/ on Mac OS X (thank you, Christophe De Troyer)

The files are settings.json and keybindings.json. Simply copy them to the target machine.

Your extensions are in

  • ~/.vscode/extensions on Linux and Mac OS X
  • C:\Users\username\.vscode\extensions on Windows 10 (e.g., essentially the same place)

Alternately, just go to the Extensions, show installed extensions, and install those on your target installation. For me, copying the extensions worked just fine, but it may be extension-specific, particularly if moving between platforms, depending on what the extension does.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Use this to force IE to hide that annoying browser compatibility button in the address bar:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

Concatenate two NumPy arrays vertically

a = np.array([1,2,3])
b = np.array([4,5,6])
np.array((a,b))

works just as well as

np.array([[1,2,3], [4,5,6]])

Regardless of whether it is a list of lists or a list of 1d arrays, np.array tries to create a 2d array.

But it's also a good idea to understand how np.concatenate and its family of stack functions work. In this context concatenate needs a list of 2d arrays (or any anything that np.array will turn into a 2d array) as inputs.

np.vstack first loops though the inputs making sure they are at least 2d, then does concatenate. Functionally it's the same as expanding the dimensions of the arrays yourself.

np.stack is a new function that joins the arrays on a new dimension. Default behaves just like np.array.

Look at the code for these functions. If written in Python you can learn quite a bit. For vstack:

return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)

html select only one checkbox in a group

This snippet will:

  • Allow grouping like Radio buttons
  • Act like Radio
  • Allow unselecting all

_x000D_
_x000D_
// the selector will match all input controls of type :checkbox_x000D_
// and attach a click event handler _x000D_
$("input:checkbox").on('click', function() {_x000D_
  // in the handler, 'this' refers to the box clicked on_x000D_
  var $box = $(this);_x000D_
  if ($box.is(":checked")) {_x000D_
    // the name of the box is retrieved using the .attr() method_x000D_
    // as it is assumed and expected to be immutable_x000D_
    var group = "input:checkbox[name='" + $box.attr("name") + "']";_x000D_
    // the checked state of the group/box on the other hand will change_x000D_
    // and the current value is retrieved using .prop() method_x000D_
    $(group).prop("checked", false);_x000D_
    $box.prop("checked", true);_x000D_
  } else {_x000D_
    $box.prop("checked", false);_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<div>_x000D_
  <h3>Fruits</h3>_x000D_
  <label>_x000D_
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Kiwi</label>_x000D_
  <label>_x000D_
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Jackfruit</label>_x000D_
  <label>_x000D_
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango</label>_x000D_
</div>_x000D_
<div>_x000D_
  <h3>Animals</h3>_x000D_
  <label>_x000D_
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Tiger</label>_x000D_
  <label>_x000D_
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Sloth</label>_x000D_
  <label>_x000D_
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Cheetah</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> 
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

"Repository does not have a release file" error

I have been having this issue for a couple of weeks and finally decided to sit down and try and fix it. I have no interest in config file editing as I'm primarily a Windows user.

In a fit of "clickyness" I noticed that the ubuntu server location was set "for United kingdom". I switched this over to "Main Server" and hey presto... it all stared updating.

So, it seems like the regionalised server (for the UK at least) has a very limited support window so if you are an infrequent user it is likely it will not have a valid upgrade path from your current version to the latest.

Edit: I only just noticted the previous reply, after posting. 100% agree.

Converting Integers to Roman Numerals - Java

I think my solution is one of the more concise ones:

private static String convertToRoman(int mInt) {
    String[] rnChars = { "M",  "CM", "D", "C",  "XC", "L",  "X", "IX", "V", "I" };
    int[] rnVals = {  1000, 900, 500, 100, 90, 50, 10, 9, 5, 1 };
    String retVal = "";

    for (int i = 0; i < rnVals.length; i++) {
        int numberInPlace = mInt / rnVals[i];
        if (numberInPlace == 0) continue;
        retVal += numberInPlace == 4 && i > 0? rnChars[i] + rnChars[i - 1]:
            new String(new char[numberInPlace]).replace("\0",rnChars[i]);
        mInt = mInt % rnVals[i];
    }
    return retVal;
}

Alternate table row color using CSS?

You have the :nth-child() pseudo-class:

table tr:nth-child(odd) td{
    ...
}
table tr:nth-child(even) td{
    ...
}

In the early days of :nth-child() its browser support was kind of poor. That's why setting class="odd" became such a common technique. In late 2013 I'm glad to say that IE6 and IE7 are finally dead (or sick enough to stop caring) but IE8 is still around — thankfully, it's the only exception.

What's a "static method" in C#?

From another point of view: Consider that you want to make some changes on a single String. for example you want to make the letters Uppercase and so on. you make another class named "Tools" for these actions. there is no meaning of making instance of "Tools" class because there is not any kind of entity available inside that class (compare to "Person" or "Teacher" class). So we use static keyword in order to use "Tools" class without making any instance of that, and when you press dot after class name ("Tools") you can have access to the methods you want.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Tools.ToUpperCase("Behnoud Sherafati"));
        Console.ReadKey();
    }
}

public static class Tools
{
    public static string ToUpperCase(string str)
    {
        return str.ToUpper();

    }
}
}

How to create javascript delay function

Ah yes. Welcome to Asynchronous execution.

Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.

Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.

Find a file by name in Visual Studio Code

It's Ctrl+Shift+O / Cmd+Shift+O on mac. You can see it if you close all tabs

TSQL CASE with if comparison in SELECT statement

Should be:

SELECT registrationDate, 
       (SELECT CASE
        WHEN COUNT(*)< 2 THEN 'Ama'
        WHEN COUNT(*)< 5 THEN 'SemiAma' 
        WHEN COUNT(*)< 7 THEN 'Good'  
        WHEN COUNT(*)< 9 THEN 'Better' 
        WHEN COUNT(*)< 12 THEN 'Best'
        ELSE 'Outstanding'
        END as a FROM Articles 
        WHERE Articles.userId = Users.userId) as ranking,
        (SELECT COUNT(*) 
        FROM Articles 
        WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS

"fatal: Not a git repository (or any of the parent directories)" from git status

Simply, after you clone the repo you need to cd (change your current directory) to the new cloned folder

git clone https://[email protected]/Repo_Name.git

cd Repo_Name

Ruby String to Date Conversion

You can try https://rubygems.org/gems/dates_from_string:

Find date in structure:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]

C++ cout hex values?

Use std::uppercase and std::hex to format integer variable a to be displayed in hexadecimal format.

#include <iostream>
int main() {
   int a = 255;

   // Formatting Integer
   std::cout << std::uppercase << std::hex << a << std::endl; // Output: FF
   std::cout << std::showbase  << std::hex << a << std::endl; // Output: 0XFF
   std::cout << std::nouppercase << std::showbase  << std::hex << a << std::endl; // Output: 0xff

   return 0;
}

Chrome Fullscreen API

I made a simple wrapper for the Fullscreen API, called screenfull.js, to smooth out the prefix mess and fix some inconsistencies in the different implementations. Check out the demo to see how the Fullscreen API works.

Recommended reading:

Split code over multiple lines in an R script

I know this post is old, but I had a Situation like this and just want to share my solution. All the answers above work fine. But if you have a Code such as those in data.table chaining Syntax it becomes abit challenging. e.g. I had a Problem like this.

mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, Geom:=tstrsplit(files$file, "/")[1:4][[4]]][time_[s]<=12000]

I tried most of the suggestions above and they didn´t work. but I figured out that they can be split after the comma within []. Splitting at ][ doesn´t work.

mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, 
    Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, 
    Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, 
    Geom:=tstrsplit(files$file, "/")[1:4][[4]]][`time_[s]`<=12000]

What is the difference between logical data model and conceptual data model?

First of all, a data model is an abstraction tool and a database model (or scheme/diagramm) is a modeling result.

Conceptual data model is DBMS-independent and covers functional/domain design area. The most known conceptual data model is "Entity-Relationship". Normally, you can reuse the conceptual scheme to produce different logical schemes not only relational.

Logical data model is intended to be implemented by some DBMS and corresponds mostly to the conceptual level of ANSI/SPARC architecture (proposed in 1975); this point gives some collisions of terminology. Zachman Framework tried to resolve this kind of collision ten years later introducing conceptual, logical and physical models.

There are many logical data models, and the most known is relational one.

So main differences of conceptual data model are the focusing on the domain and DBMS-independence whereas logical data model is the most abstract level of concrete DBMS you plan to use. Note that contemporary DBMS support several logical models at the same time.

You can also have a look to my book and to the article for more details.

Access VBA | How to replace parts of a string with another string

I was reading this thread and would like to add information even though it is surely no longer timely for the OP.

BiggerDon above points out the difficulty of rote replacing "North" with "N". A similar problem exists with "Avenue" to "Ave" (e.g. "Avenue of the Americas" becomes "Ave of the Americas": still understandable, but probably not what the OP wants.

The replace() function is entirely context-free, but addresses are not. A complete solution needs to have additional logic to interpret the context correctly, and then apply replace() as needed.

Databases commonly contain addresses, and so I wanted to point out that the generalized version of the OP's problem as applied to addresses within the United States has been addressed (humor!) by the Coding Accuracy Support System (CASS). CASS is a database tool that accepts a U.S. address and completes or corrects it to meet a standard set by the U.S. Postal Service. The Wikipedia entry https://en.wikipedia.org/wiki/Postal_address_verification has the basics, and more information is available at the Post Office: https://ribbs.usps.gov/index.cfm?page=address_info_systems

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

How to ignore ansible SSH authenticity checking?

If you don't want to modify ansible.cfg or the playbook.yml then you can just set an environment variable:

export ANSIBLE_HOST_KEY_CHECKING=False

Why is it said that "HTTP is a stateless protocol"?

Modern HTTP is stateful. Old timey HTTP was stateless.

Before Netscape invented cookies and HTTPS in 1994 http could be considered stateless. As time progressed more and more stateful aspects were added for a myriad of reasons, including performance and security.

While HTTP 1 originally sought out to be stateless many HTTP/2 components are the very definition of stateful. HTTP/2 abandoned stateless goals.

No reasonable person can read the HTTP/2 RFC and think it is stateless. The errant "HTTP is stateless" old time dogma is false and far from the current reality of stateful HTTP.

Here's a limited, and not exhaustive list, of stateful HTTP/1 and HTTP/2 components:

  • Cookies, named "HTTP State Management Mechanism" by the RFC.
  • HTTPS, which stores keys thus state.
  • HTTP authentication requires state.
  • Web Storage.
  • HTTP caching is stateful.
  • The very purpose of the stream identifier is state. It's even in the name of the RFC section, "Stream States".
  • Header blocks, which establish stream identifiers, are stateful.
  • Frames which reference stream identifiers are stateful.
  • Header Compression, which the HTTP RFC explicitly says is stateful, is stateful.
  • Opportunistic encryption is stateful.

Section 5.1 of the HTTP/2 RFC is a great example of stateful mechanisms defined by the HTTP/2 standard.

Is it safe for web applications to consider HTTP/2 as a stateless protocol?

HTTP/2 is a stateful protocol, but that doesn't mean your HTTP/2 application can't be stateless. You can choose to not use certain stateful features for stateless HTTP/2 applications by using only a subset of HTTP/2 features.

Cookies and some other stateful mechanisms, or less obvious stateful mechanisms, are later HTTP additions. HTTP 1 is said to be stateless although in practice we use standardized stateful mechanisms, like cookies, TLS, and caching. Unlike HTTP/1, HTTP/2 defines stateful components in its standard from the very beginning. A particular HTTP/2 application can use a subset of HTTP/2 features to maintain statelessness, but the protocol itself anticipate state to be the norm, not the exception.

Existing applications, even HTTP 1 applications, needing state will break if trying to use them statelessly. It can be impossible to log into some HTTP/1.1 websites if cookies are disabled, thus breaking the application. It may not be safe to assume that a particular HTTP 1 application does not use state. This is no different for HTTP/2.

Say it with me one last time:

HTTP/2 is a stateful protocol.

Why functional languages?

Some thoughts:

  • The debate between FP and imperative programming (OO, structured, etc), has been raging since Lisp versus Fortran. I think you pose excellent questions but recognize that they are not especially new.
  • Part of the hoopla over FP is that we seem to be recognizing that concurrency is very difficult, and that locks and other mechanisms in OO (e.g. Java) are just one solution. FP offers a refreshing sea change with ideas such as Actors and the power of stateless computing. To those wrestling with OO, the landscape seems highly appealing.
  • Yes, schools teach FP. In fact, the University of Waterloo and others offer Scheme in first year classes (reference here).
  • Regarding the average programmer, I'm sure that the same arguments were given against C++ back in the early 1990s. And look what happened. If businesses can gain an advantage via a technology, you can bet that people will receive training.

This is not to say that it is a sure thing, or that there won't be a backlash in 3-5 years (as there always is). However, the trend towards FP has merit and is worth watching.

Javascript - sort array based on another array

_x000D_
_x000D_
function sortFunc(a, b) {
  var sortingArr = ["A", "B", "C"];
  return sortingArr.indexOf(a.type) - sortingArr.indexOf(b.type);
}

const itemsArray = [
  {
    type: "A",
  },
  {
    type: "C",
  },
  {
    type: "B",
  },
];
console.log(itemsArray);
itemsArray.sort(sortFunc);
console.log(itemsArray);
_x000D_
_x000D_
_x000D_

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Option: isoformat()

Python's datetime does not support the military timezone suffixes like 'Z' suffix for UTC. The following simple string replacement does the trick:

In [1]: import datetime

In [2]: d = datetime.datetime(2014, 12, 10, 12, 0, 0)

In [3]: str(d).replace('+00:00', 'Z')
Out[3]: '2014-12-10 12:00:00Z'

str(d) is essentially the same as d.isoformat(sep=' ')

See: Datetime, Python Standard Library

Option: strftime()

Or you could use strftime to achieve the same effect:

In [4]: d.strftime('%Y-%m-%dT%H:%M:%SZ')
Out[4]: '2014-12-10 12:00:00Z'

Note: This option works only when you know the date specified is in UTC.

See: datetime.strftime()


Additional: Human Readable Timezone

Going further, you may be interested in displaying human readable timezone information, pytz with strftime %Z timezone flag:

In [5]: import pytz

In [6]: d = datetime.datetime(2014, 12, 10, 12, 0, 0, tzinfo=pytz.utc)

In [7]: d
Out[7]: datetime.datetime(2014, 12, 10, 12, 0, tzinfo=<UTC>)

In [8]: d.strftime('%Y-%m-%d %H:%M:%S %Z')
Out[8]: '2014-12-10 12:00:00 UTC'

Aligning two divs side-by-side

It's also possible to to do this without the wrapper - div#main. You can center the #page-wrap using the margin: 0 auto; method and then use the left:-n; method to position the #sidebar and adding the width of #page-wrap.

body { background: black; }
#sidebar    {
    position: absolute;
    left: 50%;
    width: 200px;
    height: 400px;
    background: red;
    margin-left: -230px;
    }

#page-wrap  {
    width: 60px;
    background: #fff;
    height: 400px;
    margin: 0 auto;
    }

However, the sidebar would disappear beyond the browser viewport if the window was smaller than the content.

Nick's second answer is best though, because it's also more maintainable as you don't have to adjust #sidebar if you want to resize #page-wrap.

Sequelize, convert entity to plain object

If I get you right, you want to add the sensors collection to the node. If you have a mapping between both models you can either use the include functionality explained here or the values getter defined on every instance. You can find the docs for that here.

The latter can be used like this:

db.Sensors.findAll({
  where: {
    nodeid: node.nodeid
  }
}).success(function (sensors) {
  var nodedata = node.values;

  nodedata.sensors = sensors.map(function(sensor){ return sensor.values });
  // or
  nodedata.sensors = sensors.map(function(sensor){ return sensor.toJSON() });

  nodesensors.push(nodedata);
  response.json(nodesensors);
});

There is chance that nodedata.sensors = sensors could work as well.

Converting a character code to char (VB.NET)

You could use the Chr(int) function

How can I do DNS lookups in Python, including referring to /etc/hosts?

This code works well for returning all of the IP addresses that might belong to a particular URI. Since many systems are now in a hosted environment (AWS/Akamai/etc.), systems may return several IP addresses. The lambda was "borrowed" from @Peter Silva.

def get_ips_by_dns_lookup(target, port=None):
    '''
        this function takes the passed target and optional port and does a dns
        lookup. it returns the ips that it finds to the caller.

        :param target:  the URI that you'd like to get the ip address(es) for
        :type target:   string
        :param port:    which port do you want to do the lookup against?
        :type port:     integer
        :returns ips:   all of the discovered ips for the target
        :rtype ips:     list of strings

    '''
    import socket

    if not port:
        port = 443

    return list(map(lambda x: x[4][0], socket.getaddrinfo('{}.'.format(target),port,type=socket.SOCK_STREAM)))

ips = get_ips_by_dns_lookup(target='google.com')

How to read file using NPOI

Simple read example below:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

//.....

private void button1_Click(object sender, EventArgs e)
{
    HSSFWorkbook hssfwb;
    using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))
    {
        hssfwb= new HSSFWorkbook(file);
    }

    ISheet sheet = hssfwb.GetSheet("Arkusz1");
    for (int row = 0; row <= sheet.LastRowNum; row++)
    {
        if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
        {
            MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));
        }
    }
}  

By the way: on NPOI website here in Download section there is example package - a pack of C# examples. Try it, if you haven't yet. :)

How to clear jQuery validation error messages?

If you want just clear validation labels you can use code from jquery.validate.js resetForm()

var validator = $('#Form').validate();

validator.submitted = {};
validator.prepareForm();
validator.hideErrors();
validator.elements().removeClass(validatorObject.settings.errorClass);

Delete branches in Bitbucket

For deleting branch from Bitbucket,

  1. Go to Overview (Your repository > branches in the left sidebar)
  2. Click the number of branches (that should show you the list of branches)
  3. Click on the branch that you want to delete
  4. On top right corner, click the 3 dots (besides Merge button).
  5. There is the option of "Delete Branch" if you have rights.

Javascript select onchange='this.form.submit()'

If you're using jQuery, it's as simple as this:

 $('#mySelect').change(function()
 {
     $('#myForm').submit();
 });

How do I call a non-static method from a static method in C#?

Perhaps what you are looking for is the Singleton pattern?

public class Singleton
{
    private Singleton() {}

    public void DoWork()
    { 
        // do something
    }

    // You can call this static method which calls the singleton instance method.
    public static void DoSomeWork()
    { 
        Instance.DoWork();
    }

    public static Singleton Instance
    {
        get { return instance; } 
    }

    private static Singleton instance = new Singleton();
}

You still have to create an instance of the class but you ensure there is only one instance.

multiprocessing.Pool: When to use apply, apply_async or map?

Here is an overview in a table format in order to show the differences between Pool.apply, Pool.apply_async, Pool.map and Pool.map_async. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:

                  | Multi-args   Concurrence    Blocking     Ordered-results
---------------------------------------------------------------------
Pool.map          | no           yes            yes          yes
Pool.map_async    | no           yes            no           yes
Pool.apply        | yes          no             yes          no
Pool.apply_async  | yes          yes            no           no
Pool.starmap      | yes          yes            yes          yes
Pool.starmap_async| yes          yes            no           no

Notes:

  • Pool.imap and Pool.imap_async – lazier version of map and map_async.

  • Pool.starmap method, very much similar to map method besides it acceptance of multiple arguments.

  • Async methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.

  • Pool.map(or Pool.apply)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.

Examples:

map

Is called for a list of jobs in one time

results = pool.map(func, [1, 2, 3])

apply

Can only be called for one job

for x, y in [[1, 1], [2, 2]]:
    results.append(pool.apply(func, (x, y)))

def collect_result(result):
    results.append(result)

map_async

Is called for a list of jobs in one time

pool.map_async(func, jobs, callback=collect_result)

apply_async

Can only be called for one job and executes a job in the background in parallel

for x, y in [[1, 1], [2, 2]]:
    pool.apply_async(worker, (x, y), callback=collect_result)

starmap

Is a variant of pool.map which support multiple arguments

pool.starmap(func, [(1, 1), (2, 1), (3, 1)])

starmap_async

A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.

pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)

Reference:

Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html

Moment.js transform to date object

The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,

const moment=require('moment-timezone')//import from moment-timezone

Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,

var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/

Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,

newYork.toDate()//will give you the Greenwich ,UK, time.

newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()

In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.

How to parse freeform street/postal address out of text, and into components

No code? For shame!

Here is a simple JavaScript address parser. It's pretty awful for every single reason that Matt gives in his dissertation above (which I almost 100% agree with: addresses are complex types, and humans make mistakes; better to outsource and automate this - when you can afford to).

But rather than cry, I decided to try:

This code works OK for parsing most Esri results for findAddressCandidate and also with some other (reverse)geocoders that return single-line address where street/city/state are delimited by commas. You can extend if you want or write country-specific parsers. Or just use this as case study of how challenging this exercise can be or at how lousy I am at JavaScript. I admit I only spent about thirty mins on this (future iterations could add caches, zip validation, and state lookups as well as user location context), but it worked for my use case: End user sees form that parses geocode search response into 4 textboxes. If address parsing comes out wrong (which is rare unless source data was poor) it's no big deal - the user gets to verify and fix it! (But for automated solutions could either discard/ignore or flag as error so dev can either support the new format or fix source data.)

_x000D_
_x000D_
/* _x000D_
address assumptions:_x000D_
- US addresses only (probably want separate parser for different countries)_x000D_
- No country code expected._x000D_
- if last token is a number it is probably a postal code_x000D_
-- 5 digit number means more likely_x000D_
- if last token is a hyphenated string it might be a postal code_x000D_
-- if both sides are numeric, and in form #####-#### it is more likely_x000D_
- if city is supplied, state will also be supplied (city names not unique)_x000D_
- zip/postal code may be omitted even if has city & state_x000D_
- state may be two-char code or may be full state name._x000D_
- commas: _x000D_
-- last comma is usually city/state separator_x000D_
-- second-to-last comma is possibly street/city separator_x000D_
-- other commas are building-specific stuff that I don't care about right now._x000D_
- token count:_x000D_
-- because units, street names, and city names may contain spaces token count highly variable._x000D_
-- simplest address has at least two tokens: 714 OAK_x000D_
-- common simple address has at least four tokens: 714 S OAK ST_x000D_
-- common full (mailing) address has at least 5-7:_x000D_
--- 714 OAK, RUMTOWN, VA 59201_x000D_
--- 714 S OAK ST, RUMTOWN, VA 59201_x000D_
-- complex address may have a dozen or more:_x000D_
--- MAGICICIAN SUPPLY, LLC, UNIT 213A, MAGIC TOWN MALL, 13 MAGIC CIRCLE DRIVE, LAND OF MAGIC, MA 73122-3412_x000D_
*/_x000D_
_x000D_
var rawtext = $("textarea").val();_x000D_
var rawlist = rawtext.split("\n");_x000D_
_x000D_
function ParseAddressEsri(singleLineaddressString) {_x000D_
  var address = {_x000D_
    street: "",_x000D_
    city: "",_x000D_
    state: "",_x000D_
    postalCode: ""_x000D_
  };_x000D_
_x000D_
  // tokenize by space (retain commas in tokens)_x000D_
  var tokens = singleLineaddressString.split(/[\s]+/);_x000D_
  var tokenCount = tokens.length;_x000D_
  var lastToken = tokens.pop();_x000D_
  if (_x000D_
    // if numeric assume postal code (ignore length, for now)_x000D_
    !isNaN(lastToken) ||_x000D_
    // if hyphenated assume long zip code, ignore whether numeric, for now_x000D_
    lastToken.split("-").length - 1 === 1) {_x000D_
    address.postalCode = lastToken;_x000D_
    lastToken = tokens.pop();_x000D_
  }_x000D_
_x000D_
  if (lastToken && isNaN(lastToken)) {_x000D_
    if (address.postalCode.length && lastToken.length === 2) {_x000D_
      // assume state/province code ONLY if had postal code_x000D_
      // otherwise it could be a simple address like "714 S OAK ST"_x000D_
      // where "ST" for "street" looks like two-letter state code_x000D_
      // possibly this could be resolved with registry of known state codes, but meh. (and may collide anyway)_x000D_
      address.state = lastToken;_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
    if (address.state.length === 0) {_x000D_
      // check for special case: might have State name instead of State Code._x000D_
      var stateNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found separator, ignore stuff on left side_x000D_
          tokens.push(lastToken); // put it back_x000D_
          break;_x000D_
        } else {_x000D_
          stateNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.state = stateNameParts.join(' ');_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
  }_x000D_
_x000D_
  if (lastToken) {_x000D_
    // here is where it gets trickier:_x000D_
    if (address.state.length) {_x000D_
      // if there is a state, then assume there is also a city and street._x000D_
      // PROBLEM: city may be multiple words (spaces)_x000D_
      // but we can pretty safely assume next-from-last token is at least PART of the city name_x000D_
      // most cities are single-name. It would be very helpful if we knew more context, like_x000D_
      // the name of the city user is in. But ignore that for now._x000D_
      // ideally would have zip code service or lookup to give city name for the zip code._x000D_
      var cityNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // assumption / RULE: street and city must have comma delimiter_x000D_
      // addresses that do not follow this rule will be wrong only if city has space_x000D_
      // but don't care because Esri formats put comma before City_x000D_
      var streetNameParts = [];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found end of street address (may include building, etc. - don't care right now)_x000D_
          // add token back to end, but remove trailing comma (it did its job)_x000D_
          tokens.push(lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken);_x000D_
          streetNameParts = tokens;_x000D_
          break;_x000D_
        } else {_x000D_
          cityNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.city = cityNameParts.join(' ');_x000D_
      address.street = streetNameParts.join(' ');_x000D_
    } else {_x000D_
      // if there is NO state, then assume there is NO city also, just street! (easy)_x000D_
      // reasoning: city names are not very original (Portland, OR and Portland, ME) so if user wants city they need to store state also (but if you are only ever in Portlan, OR, you don't care about city/state)_x000D_
      // put last token back in list, then rejoin on space_x000D_
      tokens.push(lastToken);_x000D_
      address.street = tokens.join(' ');_x000D_
    }_x000D_
  }_x000D_
  // when parsing right-to-left hard to know if street only vs street + city/state_x000D_
  // hack fix for now is to shift stuff around._x000D_
  // assumption/requirement: will always have at least street part; you will never just get "city, state"  _x000D_
  // could possibly tweak this with options or more intelligent parsing&sniffing_x000D_
  if (!address.city && address.state) {_x000D_
    address.city = address.state;_x000D_
    address.state = '';_x000D_
  }_x000D_
  if (!address.street) {_x000D_
    address.street = address.city;_x000D_
    address.city = '';_x000D_
  }_x000D_
_x000D_
  return address;_x000D_
}_x000D_
_x000D_
// get list of objects with discrete address properties_x000D_
var addresses = rawlist_x000D_
  .filter(function(o) {_x000D_
    return o.length > 0_x000D_
  })_x000D_
  .map(ParseAddressEsri);_x000D_
$("#output").text(JSON.stringify(addresses));_x000D_
console.log(addresses);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
13212 E SPRAGUE AVE, FAIR VALLEY, MD 99201_x000D_
1005 N Gravenstein Highway, Sebastopol CA 95472_x000D_
A. P. Croll &amp; Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947_x000D_
11522 Shawnee Road, Greenwood, DE 19950_x000D_
144 Kings Highway, S.W. Dover, DE 19901_x000D_
Intergrated Const. Services 2 Penns Way Suite 405, New Castle, DE 19720_x000D_
Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958_x000D_
Nichols Excavation 2742 Pulaski Hwy, Newark, DE 19711_x000D_
2284 Bryn Zion Road, Smyrna, DE 19904_x000D_
VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21_x000D_
580 North Dupont Highway, Dover, DE 19901_x000D_
P.O. Box 778, Dover, DE 19903_x000D_
714 S OAK ST_x000D_
714 S OAK ST, RUM TOWN, VA, 99201_x000D_
3142 E SPRAGUE AVE, WHISKEY VALLEY, WA 99281_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
</textarea>_x000D_
<div id="output">_x000D_
</div>
_x000D_
_x000D_
_x000D_

href around input type submit

Place the link location in the action="" of a wrapping form tag.

Your first link would be:

<form action="1.html">
    <input type="submit" class="button_active" value="1">
</form>

What is Options +FollowSymLinks?

You might try searching the internet for ".htaccess Options not allowed here".

A suggestion I found (using google) is:

Check to make sure that your httpd.conf file has AllowOverride All.

A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):

# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html

# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
</IfModule>

# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.

Adding blur effect to background in swift

@AlvinGeorge should just use:

extension UIImageView{        
    func blurImage()
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.bounds

        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation
        self.addSubview(blurEffectView)
    }
}

usage:

 blurredBackground.frame = self.view.bounds
 blurredBackground.blurImage()
 self.view.addSubview(self.blurredBackground)

What is the difference between Set and List?

List :

  1. List is ordered grouping elements
  2. List provides positional access in the elements of the collections.
  3. We can store duplicate elements in the list.
  4. List implements ArrayList, LinkedList, Vector and Stack.
  5. List can store multiple null elements.

Set :

  1. Unorderd grouping elements.
  2. Set doesn’t provides positional access in the elements of the collections.
  3. We can’t store duplicate elements in the set.
  4. Set implement HashSet and LinkedHashSet interfaces.
  5. Set can store only one null elements.

Example of waitpid() in use?

Syntax of waitpid():

pid_t waitpid(pid_t pid, int *status, int options);

The value of pid can be:

  • < -1: Wait for any child process whose process group ID is equal to the absolute value of pid.
  • -1: Wait for any child process.
  • 0: Wait for any child process whose process group ID is equal to that of the calling process.
  • > 0: Wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

  • WNOHANG: Return immediately if no child has exited.
  • WUNTRACED: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED: Also return if a stopped child has been resumed by delivery of SIGCONT.

For more help, use man waitpid.

Java Reflection Performance

Yes - absolutely. Looking up a class via reflection is, by magnitude, more expensive.

Quoting Java's documentation on reflection:

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Here's a simple test I hacked up in 5 minutes on my machine, running Sun JRE 6u10:

public class Main {

    public static void main(String[] args) throws Exception
    {
        doRegular();
        doReflection();
    }

    public static void doRegular() throws Exception
    {
        long start = System.currentTimeMillis();
        for (int i=0; i<1000000; i++)
        {
            A a = new A();
            a.doSomeThing();
        }
        System.out.println(System.currentTimeMillis() - start);
    }

    public static void doReflection() throws Exception
    {
        long start = System.currentTimeMillis();
        for (int i=0; i<1000000; i++)
        {
            A a = (A) Class.forName("misc.A").newInstance();
            a.doSomeThing();
        }
        System.out.println(System.currentTimeMillis() - start);
    }
}

With these results:

35 // no reflection
465 // using reflection

Bear in mind the lookup and the instantiation are done together, and in some cases the lookup can be refactored away, but this is just a basic example.

Even if you just instantiate, you still get a performance hit:

30 // no reflection
47 // reflection using one lookup, only instantiating

Again, YMMV.

seek() function?

For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.

How to Solve Max Connection Pool Error

May be this is alltime multiple connection open issue, you are somewhere in your code opening connections and not closing them properly. use

 using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
         }

Refer this article: http://msdn.microsoft.com/en-us/library/ms254507(v=vs.80).aspx, The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

How do I uninstall nodejs installed from pkg (Mac OS X)?

If you installed Node from their website, try this:

sudo rm -rf /usr/local/{bin/{node,npm},lib/node_modules/npm,lib/node,share/man/*/node.*}

This worked for me, but if you have any questions, my GitHub is 'mnafricano'.

Getting the first character of a string with $str[0]

It'll vary depending on resources, but you could run the script bellow and see for yourself ;)

<?php
$tests = 100000;

for ($i = 0; $i < $tests; $i++)
{
    $string = md5(rand());
    $position = rand(0, 31);

    $start1 = microtime(true);
    $char1 = $string[$position];
    $end1 = microtime(true);
    $time1[$i] = $end1 - $start1;

    $start2 = microtime(true);
    $char2 = substr($string, $position, 1);
    $end2 = microtime(true);
    $time2[$i] = $end2 - $start2;

    $start3 = microtime(true);
    $char3 = $string{$position};
    $end3 = microtime(true);
    $time3[$i] = $end3 - $start3;
}

$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;

$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;

$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>

Some reference numbers (on an old CoreDuo machine)

$ php 1.php 
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6

$ php 1.php 
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6

$ php 1.php 
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6

It seems that using the [] or {} operators is more or less the same.

What do the return values of Comparable.compareTo mean in Java?

int x = thisObject.compareTo(anotherObject);

The compareTo() method returns an int with the following characteristics:

  • negative If thisObject < anotherObject
  • zero If thisObject == anotherObject
  • positive If thisObject > anotherObject

Eclipse internal error while initializing Java tooling

Delete your existing workspace and then recreate the workspace and add your projects.

Adding items to end of linked list

loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null

What is the difference between require() and library()?

My initial theory about the difference was that library loads the packages whether it is already loaded or not, i.e. it might reload an already loaded package, while require just checks that it is loaded, or loads it if it isn't (thus the use in functions that rely on a certain package). The documentation refutes this, however, and explicitly states that neither function will reload an already loaded package.

Install a Python package into a different directory using pip?

If you are using brew with python, unfortunately, pip/pip3 ships with very limited options. You do not have --install-option, --target, --user options as mentioned above.

Note on pip install --user
The normal pip install --user is disabled for brewed Python. This is because of a bug in distutils, because Homebrew writes a distutils.cfg which sets the package prefix. A possible workaround (which puts executable scripts in ~/Library/Python/./bin) is: python -m pip install --user --install-option="--prefix=" <package-name>

You might find this line very cumbersome. I suggest use pyenv for management. If you are using

brew upgrade python python3

Ironically you are actually downgrade pip functionality.

(I post this answer, simply because pip in my mac osx does not have --target option, and I have spent hours fixing it)

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

Disable scrolling in webview?

Just use android:focusableInTouchMode="false" on your webView.

How to make a local variable (inside a function) global

Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:

def foo():
    global bar
    bar = 32

I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.

How to remove leading and trailing whitespace in a MySQL field?

I needed to trim the values in a primary key column that had first and last names, so I did not want to trim all white space as that would remove the space between the first and last name, which I needed to keep. What worked for me was...

UPDATE `TABLE` SET `FIELD`= TRIM(FIELD);

or

UPDATE 'TABLE' SET 'FIELD' = RTRIM(FIELD);

or

UPDATE 'TABLE' SET 'FIELD' = LTRIM(FIELD);

Note that the first instance of FIELD is in single quotes but the second is not in quotes at all. I had to do it this way or it gave me a syntax error saying it was a duplicate primary key when I had both in quotes.

How to go up a level in the src path of a URL in HTML?

In Chrome when you load a website from some HTTP server both absolute paths (e.g. /images/sth.png) and relative paths to some upper level directory (e.g. ../images/sth.png) work.

But!

When you load (in Chrome!) a HTML document from local filesystem you cannot access directories above current directory. I.e. you cannot access ../something/something.sth and changing relative path to absolute or anything else won't help.

Reporting Services permissions on SQL Server R2 SSRS

This problem occurs because of UAC and only when you are running IE on the same computer SSRS is on.

To fix it, you have to add an AD group of the users with read priviledges to the actual SSRS website directories and push the security down. UAC is dumb in how if you are an admin on the box. It won't let you access the data unless you also have access to the data through other means such as a non-administrator AD group that is applied to the files.

How do I use $scope.$watch and $scope.$apply in AngularJS?

AngularJS extends this events-loop, creating something called AngularJS context.

$watch()

Every time you bind something in the UI you insert a $watch in a $watch list.

User: <input type="text" ng-model="user" />
Password: <input type="password" ng-model="pass" />

Here we have $scope.user, which is bound to the first input, and we have $scope.pass, which is bound to the second one. Doing this we add two $watches to the $watch list.

When our template is loaded, AKA in the linking phase, the compiler will look for every directive and creates all the $watches that are needed.

AngularJS provides $watch, $watchcollection and $watch(true). Below is a neat diagram explaining all the three taken from watchers in depth.

Enter image description here

angular.module('MY_APP', []).controller('MyCtrl', MyCtrl)
function MyCtrl($scope,$timeout) {
  $scope.users = [{"name": "vinoth"},{"name":"yusuf"},{"name":"rajini"}];

  $scope.$watch("users", function() {
    console.log("**** reference checkers $watch ****")
  });

  $scope.$watchCollection("users", function() {
    console.log("**** Collection  checkers $watchCollection ****")
  });

  $scope.$watch("users", function() {
    console.log("**** equality checkers with $watch(true) ****")
  }, true);

  $timeout(function(){
     console.log("Triggers All ")
     $scope.users = [];
     $scope.$digest();

     console.log("Triggers $watchCollection and $watch(true)")
     $scope.users.push({ name: 'Thalaivar'});
     $scope.$digest();

     console.log("Triggers $watch(true)")
     $scope.users[0].name = 'Superstar';
     $scope.$digest();
  });
}

http://jsfiddle.net/2Lyn0Lkb/

$digest loop

When the browser receives an event that can be managed by the AngularJS context the $digest loop will be fired. This loop is made from two smaller loops. One processes the $evalAsync queue, and the other one processes the $watch list. The $digest will loop through the list of $watch that we have

app.controller('MainCtrl', function() {
  $scope.name = "vinoth";

  $scope.changeFoo = function() {
      $scope.name = "Thalaivar";
  }
});

{{ name }}
<button ng-click="changeFoo()">Change the name</button>

Here we have only one $watch because ng-click doesn’t create any watches.

We press the button.

  1. The browser receives an event which will enter the AngularJS context
  2. The $digest loop will run and will ask every $watch for changes.
  3. Since the $watch which was watching for changes in $scope.name reports a change, it will force another $digest loop.
  4. The new loop reports nothing.
  5. The browser gets the control back and it will update the DOM reflecting the new value of $scope.name
  6. The important thing here is that EVERY event that enters the AngularJS context will run a $digest loop. That means that every time we write a letter in an input, the loop will run checking every $watch in this page.

$apply()

If you call $apply when an event is fired, it will go through the angular-context, but if you don’t call it, it will run outside it. It is as easy as that. $apply will call the $digest() loop internally and it will iterate over all the watches to ensure the DOM is updated with the newly updated value.

The $apply() method will trigger watchers on the entire $scope chain whereas the $digest() method will only trigger watchers on the current $scope and its children. When none of the higher-up $scope objects need to know about the local changes, you can use $digest().

How to print table using Javascript?

You can also use a jQuery plugin to do that

jQuery PrintPage plugin

Demo

port forwarding in windows

I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm

The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.

gson throws MalformedJsonException

I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing } character. What's the length of result1 versus result2? I'll note that result2 as you've quoted it has 169 characters.

GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t, \n, \r, and space count as whitespace. In particular, note that trailing NUL (\0) characters do not count as whitespace and will cause this error.

If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:

Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);

How to fix a collation conflict in a SQL Server query?

if the database is maintained by you then simply create a new database and import the data from the old one. the collation problem is solved!!!!!

PHP: How to get referrer URL?

If $_SERVER['HTTP_REFERER'] variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.

What is a Data Transfer Object (DTO)?

  1. To me the best answer to the question what is a DTO is that DTO's are simple objects that should not contain any business logic or methods implementation that would require testing.
  2. Normally your model (using the MVC pattern) are intelligent models, and they can contain a lot of/some methods that do some different operations for that model specifically (not business logic, this should be at the controllers). However, when you transfer data (eg. calling a REST (GET/POST/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.

How to install Java SDK on CentOS?

yum install java-1.8.0

and then:

alternatives --config java

and check:

java -version

Where is the user's Subversion config file stored on the major operating systems?

@Baxter's is mostly correct but it is missing one important Windows-specific detail.

Subversion's runtime configuration area is stored in the %APPDATA%\Subversion\ directory. The files are config and servers.

However, in addition to text-based configuration files, Subversion clients can use Windows Registry to store the client settings. It makes it possible to modify the settings with PowerShell in a convenient manner, and also distribute these settings to user workstations in Active Directory environment via AD Group Policy. See SVNBook | Configuration and the Windows Registry (you can find examples and a sample *.reg file there).

enter image description here

How to use Oracle ORDER BY and ROWNUM correctly?

Documented couple of design issues with this in a comment above. Short story, in Oracle, you need to limit the results manually when you have large tables and/or tables with same column names (and you don't want to explicit type them all out and rename them all). Easy solution is to figure out your breakpoint and limit that in your query. Or you could also do this in the inner query if you don't have the conflicting column names constraint. E.g.

WHERE m_api_log.created_date BETWEEN TO_DATE('10/23/2015 05:00', 'MM/DD/YYYY HH24:MI') 
                                 AND TO_DATE('10/30/2015 23:59', 'MM/DD/YYYY HH24:MI')  

will cut down the results substantially. Then you can ORDER BY or even do the outer query to limit rows.

Also, I think TOAD has a feature to limit rows; but, not sure that does limiting within the actual query on Oracle. Not sure.

What is the difference between 'protected' and 'protected internal'?

I have read out very clear definitions for these terms.

Protected : Access is limited to within the class definition and any class that inherits from the class. The type or member can be accessed only by code in the same class or struct or in a class that is derived from that class.

Internal : Access is limited to exclusively to classes defined within the current project assembly. The type or member can be accessed only by code in same class.

Protected-Internal : Access is limited to current assembly or types derived from containing class.

com.sun.jdi.InvocationException occurred invoking method

Removing hashCode() and equals() solved my issue. In my case, I used Apache's commons-lang hash code and equals builders for creating non-static classes manually, so the compiler didn't throw any exception. But at runtime it caused the invocation exception.

How to split a string to 2 strings in C

If you're open to changing the original string, you can simply replace the delimiter with \0. The original pointer will point to the first string and the pointer to the character after the delimiter will point to the second string. The good thing is you can use both pointers at the same time without allocating any new string buffers.

java: run a function after a specific number of seconds

All other unswers require to run your code inside a new thread. In some simple use cases you may just want to wait a bit and continue execution within the same thread/flow.

Code below demonstrates that technique. Keep in mind this is similar to what java.util.Timer does under the hood but more lightweight.

import java.util.concurrent.TimeUnit;
public class DelaySample {
    public static void main(String[] args) {
       DelayUtil d = new DelayUtil();
       System.out.println("started:"+ new Date());
       d.delay(500);
       System.out.println("half second after:"+ new Date());
       d.delay(1, TimeUnit.MINUTES); 
       System.out.println("1 minute after:"+ new Date());
    }
}

DelayUtil Implementation

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class DelayUtil {
    /** 
    *  Delays the current thread execution. 
    *  The thread loses ownership of any monitors. 
    *  Quits immediately if the thread is interrupted
    *  
    * @param duration the time duration in milliseconds
    */
   public void delay(final long durationInMillis) {
      delay(durationInMillis, TimeUnit.MILLISECONDS);
   }

   /** 
    * @param duration the time duration in the given {@code sourceUnit}
    * @param unit
    */
    public void delay(final long duration, final TimeUnit unit) {
        long currentTime = System.currentTimeMillis();
        long deadline = currentTime+unit.toMillis(duration);
        ReentrantLock lock = new ReentrantLock();
        Condition waitCondition = lock.newCondition();

        while ((deadline-currentTime)>0) {
            try {
                lock.lockInterruptibly();    
                waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            } finally {
                lock.unlock();
            }
            currentTime = System.currentTimeMillis();
        }
    }
}

Getting the names of all files in a directory with PHP

Use:

if ($handle = opendir("C:\wamp\www\yoursite/download/")) {

    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<b>" . preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry) . "</b>";
        }
    }
    closedir($handle);
}

Source: http://chandreshrana.blogspot.com/2016/08/how-to-fetch-all-files-name-from-folder.html

How do I create a folder in a GitHub repository?

Click on new file in github repo online. Then write file name as myfolder/myfilename then give file contents and commit. Then file will be created within that new folder.

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

My problem was a modified AuthorizedKeysFile, when the automation to populate /etc/ssh/authorized_keys had not yet been run.

$sudo grep AuthorizedKeysFile /etc/ssh/sshd_config
#AuthorizedKeysFile .ssh/authorized_keys
AuthorizedKeysFile  /etc/ssh/authorized_keys/%u

MySQL DISTINCT on a GROUP_CONCAT()

SELECT
  GROUP_CONCAT(DISTINCT (category))
FROM (
  SELECT
    SUBSTRING_INDEX(SUBSTRING_INDEX(tableName.categories, ' ', numbers.n), ' ', -1) category
  FROM
    numbers INNER JOIN tableName
    ON LENGTH(tableName.categories)>=LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1
  ) s;   

This will return distinct values like: test1,test2,test4,test3

How can I get Git to follow symlinks?

With Git 2.3.2+ (Q1 2015), there is one other case where Git will not follow symlink anymore: see commit e0d201b by Junio C Hamano (gitster) (main Git maintainer)

apply: do not touch a file beyond a symbolic link

Because Git tracks symbolic links as symbolic links, a path that has a symbolic link in its leading part (e.g. path/to/dir/file, where path/to/dir is a symbolic link to somewhere else, be it inside or outside the working tree) can never appear in a patch that validly applies, unless the same patch first removes the symbolic link to allow a directory to be created there.

Detect and reject such a patch.

Similarly, when an input creates a symbolic link path/to/dir and then creates a file path/to/dir/file, we need to flag it as an error without actually creating path/to/dir symbolic link in the filesystem.

Instead, for any patch in the input that leaves a path (i.e. a non deletion) in the result, we check all leading paths against the resulting tree that the patch would create by inspecting all the patches in the input and then the target of patch application (either the index or the working tree).

This way, we:

  • catch a mischief or a mistake to add a symbolic link path/to/dir and a file path/to/dir/file at the same time,
  • while allowing a valid patch that removes a symbolic link path/to/dir and then adds a file path/to/dir/file.

That means, in that case, the error message won't be a generic one like "%s: patch does not apply", but a more specific one:

affected file '%s' is beyond a symbolic link

Throughput and bandwidth difference?

Although there are already few answers to this questions but I think some people still may have doubt in actually visualising the differece b/w throughput and bandwidth just like I had ;) until I read this analogy on quora(full credits to that) which proved really helpful

Consider

A highway which has a capacity of moving ,say, 200 vehicles at a time

but

at a random time someone notices only , say, 150 vehicles moving through it..

say due to some traffic-jam in between...

i.e.

capacity is 200 but not all the time it is fully utilised, actual traffic is only 150 out of a max of 200.

i.e. the bandwidth is 200 per unit time but still actual throughput is 150 ...

I thought it might help someone...

How does Python's super() work with multiple inheritance?

Overall

Assuming everything descends from object (you are on your own if it doesn't), Python computes a method resolution order (MRO) based on your class inheritance tree. The MRO satisfies 3 properties:

  • Children of a class come before their parents
  • Left parents come before right parents
  • A class only appears once in the MRO

If no such ordering exists, Python errors. The inner workings of this is a C3 Linerization of the classes ancestry. Read all about it here: https://www.python.org/download/releases/2.3/mro/

Thus, in both of the examples below, it is:

  1. Child
  2. Left
  3. Right
  4. Parent

When a method is called, the first occurrence of that method in the MRO is the one that is called. Any class that doesn't implement that method is skipped. Any call to super within that method will call the next occurrence of that method in the MRO. Consequently, it matters both what order you place classes in inheritance, and where you put the calls to super in the methods.

With super first in each method

class Parent(object):
    def __init__(self):
        super(Parent, self).__init__()
        print "parent"

class Left(Parent):
    def __init__(self):
        super(Left, self).__init__()
        print "left"

class Right(Parent):
    def __init__(self):
        super(Right, self).__init__()
        print "right"

class Child(Left, Right):
    def __init__(self):
        super(Child, self).__init__()
        print "child"

Child() Outputs:

parent
right
left
child

With super last in each method

class Parent(object):
    def __init__(self):
        print "parent"
        super(Parent, self).__init__()

class Left(Parent):
    def __init__(self):
        print "left"
        super(Left, self).__init__()

class Right(Parent):
    def __init__(self):
        print "right"
        super(Right, self).__init__()

class Child(Left, Right):
    def __init__(self):
        print "child"
        super(Child, self).__init__()

Child() Outputs:

child
left
right
parent

What do these three dots in React do?

Its called spread operator. For eg let hello={name: '',msg:''} let hello1={...hello} Now hello object properties is copied to hello1.

Laravel Eloquent: How to get only certain columns from joined tables

You can supply an array of fields in the get parameter like so:

return Response::eloquent(Theme::with('user')->get(array('user.username'));

UPDATE (for Laravel 5.2) From the docs, you can do this:

$response = DB::table('themes')
    ->select('themes.*', 'users.username')
    ->join('users', 'users.id', '=', 'themes.user_id')
    ->get();

How to programmatically set the Image source

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

How to set maximum fullscreen in vmware?

From you main machine, start -> search -> "remote desktop connection" -> click on "remote desktop connection" -> Click "Options" Beside to "Connect Button" -> Display Tab - > Then increase Display Configuriton Size. If this will not work, try the same thing by closing remote desktop. But this will give you solution.

Nested JSON objects - do I have to use arrays for everything?

Every object has to be named inside the parent object:

{ "data": {
    "stuff": {
        "onetype": [
            { "id": 1, "name": "" },
            { "id": 2, "name": "" }
        ],
        "othertype": [
            { "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
        ]
    },
    "otherstuff": {
        "thing":
            [[1, 42], [2, 2]]
    }
}
}

So you cant declare an object like this:

var obj = {property1, property2};

It has to be

var obj = {property1: 'value', property2: 'value'};

Difference between filter and filter_by in SQLAlchemy

filter_by is used for simple queries on the column names using regular kwargs, like

db.users.filter_by(name='Joe')

The same can be accomplished with filter, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:

db.users.filter(db.users.name=='Joe')

You can also write more powerful queries using filter, such as expressions like:

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

How to delete a row from GridView?

Please try this code.....

DataRow dr = dtPrf_Mstr.NewRow();
dtPrf_Mstr.Rows.Add(dr);
GVGLCode.DataSource = dtPrf_Mstr;
GVGLCode.DataBind();
int iCount = GVGLCode.Rows.Count;
for (int i = 0; i < iCount; i++)
{
   GVGLCode.Rows.Remove(GVGLCode.Rows[i]);
}
GVGLCode.DataBind();

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

The brute force method of generating every single possible board and scoring it based on the boards it later produces further down the tree doesn't require much memory, especially once you recognize that 90 degree board rotations are redundant, as are flips about the vertical, horizontal, and diagonal axis.

Once you get to that point, there's something like less than 1k of data in a tree graph to describe the outcome, and thus the best move for the computer.

-Adam

Combining two Series into a DataFrame in pandas

I think concat is a nice way to do this. If they are present it uses the name attributes of the Series as the columns (otherwise it simply numbers them):

In [1]: s1 = pd.Series([1, 2], index=['A', 'B'], name='s1')

In [2]: s2 = pd.Series([3, 4], index=['A', 'B'], name='s2')

In [3]: pd.concat([s1, s2], axis=1)
Out[3]:
   s1  s2
A   1   3
B   2   4

In [4]: pd.concat([s1, s2], axis=1).reset_index()
Out[4]:
  index  s1  s2
0     A   1   3
1     B   2   4

Note: This extends to more than 2 Series.

Bootstrap Carousel : Remove auto slide

You can do this 2 ways, via js or html (easist)

  1. Via js
$('.carousel').carousel({
  interval: false,
});

That will make the auto sliding stop because there no Milliseconds added and will never slider next.

  1. Via Html By adding data-interval="false" and removing data-ride="carousel"
<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">

becomes:

<div id="carouselExampleCaptions" class="carousel slide" data-interval="false">

updated based on @webMan's comment

How do I add a new column to a Spark DataFrame (using PySpark)?

We can add additional columns to DataFrame directly with below steps:

from pyspark.sql.functions import when
df = spark.createDataFrame([["amit", 30], ["rohit", 45], ["sameer", 50]], ["name", "age"])
df = df.withColumn("profile", when(df.age >= 40, "Senior").otherwise("Executive"))
df.show()

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

You must write onActivityResult() in your FirstActivity.Java as follows

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
}

So this will call your fragment's onActivityResult()

Edit: the solution is to replace getActivity().startActivityForResult(i, 1); with startActivityForResult(i, 1);

Laravel Eloquent groupBy() AND also return count of each group

If you want to get collection, groupBy and count:

$collection = ModelName::groupBy('group_id')
->selectRaw('count(*) as total, group_id')
->get();

Cheers!

Number of times a particular character appears in a string

BEST

DECLARE @yourSpecialMark = '/';
select len(@yourString) - len(replace(@yourString,@yourSpecialMark,''))

It will count, how many times occours the special mark '/'

What is the difference between a hash join and a merge join (Oracle RDBMS )?

A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.

A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.

(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).

The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:

  1. The size of each hash table is reduced, hence reducing the maximum amount of memory required and potentially removing the need for the operation to require temporary disk space.
  2. For parallel query operations the amount of inter-process messaging is vastly reduced, reducing CPU usage and improving performance, as each hash join can be performed by one pair of PQ processes.
  3. For non-parallel query operations the memory requirement is reduced by a factor of n, and the first rows are projected from the query earlier.

You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.

In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.

This topic is very well covered in the documentation.

http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523

12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm

What's the difference between @Component, @Repository & @Service annotations in Spring?

@Repository @Service and @Controller are serves as specialization of @Component for more specific use on that basis you can replace @Service to @Component but in this case you loose the specialization.

1. **@Repository**   - Automatic exception translation in your persistence layer.
2. **@Service**      - It indicates that the annotated class is providing a business service to other layers within the application.

how to get the base url in javascript

in resources/views/layouts/app.blade.php file

<script type="text/javascript">
    var baseUrl = '<?=url('');?>';
</script>

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

How to work with string fields in a C struct?

While Richard's is what you want if you do want to go with a typedef, I'd suggest that it's probably not a particularly good idea in this instance, as you lose sight of it being a pointer, while not gaining anything.

If you were treating it a a counted string, or something with additional functionality, that might be different, but I'd really recommend that in this instance, you just get familiar with the 'standard' C string implementation being a 'char *'...

Regex to validate password strength

For PHP, this works fine!

 if(preg_match("/^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^0-9]*[0-9]){2}).{8,}$/", 
 'CaSu4Li8')){
    return true;
 }else{
    return fasle;
 }

in this case the result is true

Thsks for @ridgerunner

How to cd into a directory with space in the name?

Use the backslash symbol to escape the space

C:\> cd my folder

will be

 C:\> cd my\folder 

Apache server keeps crashing, "caught SIGTERM, shutting down"

try to disable the rewrite module in ubuntu using sudo a2dismod rewrite. This will perhaps stop your apache server to crash.

Getting the HTTP Referrer in ASP.NET

string referrer = HttpContext.Current.Request.UrlReferrer.ToString();

Convert array of JSON object strings to array of JS objects

var json = jQuery.parseJSON(s); //If you have jQuery.

Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

Change the above code to

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

Eg:

$(document).ready(function() {
    var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

    s = jQuery.parseJSON(s);

    alert( s[0]["Select"] );
});

And then use the parse function. It'll surely work.

EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON

Jquery

The json api

Edit (30 April 2020):

Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")

SQL Server convert string to datetime

UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)

For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:

https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql