Programs & Examples On #Viewstack

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

I had the same problem and I found this solution working with bindParam :

    bindParam(':param', $myvar = NULL, PDO::PARAM_INT);

Get the (last part of) current directory name in C#

var lastFolderName = Path.GetFileName(
    path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));

This works if the path happens to contain forward slash separators or backslash separators.

curl: (60) SSL certificate problem: unable to get local issuer certificate

Had that problem and it was not solved with newer version. /etc/certs had the root cert, the browser said everything is fine. After some testing I got from ssllabs.com the warning, that my chain was not complete (Indeed it was the chain for the old certificate and not the new one). After correcting the cert chain everything was fine, even with curl.

How to print the current Stack Trace in .NET without any exception?

   private void ExceptionTest()
    {
        try
        {
            int j = 0;
            int i = 5;
            i = 1 / j;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            var stList = ex.StackTrace.ToString().Split('\\');
            Console.WriteLine("Exception occurred at " + stList[stList.Count() - 1]);
        }
    }

Seems to work for me

What causes: "Notice: Uninitialized string offset" to appear?

Try to test and initialize your arrays before you use them :

if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;

If $catagory[$i] doesn't exist, you create (Uninitialized) one ... that's all ; => PHP try to read on your table in the address $i, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string. So you code is not very clean, it takes you some resources that down you server's performance (just a very little).

Take care about your MySQL tables default values

if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;

or

if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;

What's the point of the X-Requested-With header?

A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.

Only the following headers are allowed cross domain:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type

any others cause a "pre-flight" request to be issued in CORS supported browsers.

Without CORS it is not possible to add X-Requested-With to a cross domain XHR request.

If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin header could be an option in supported browsers, although you will leave old browsers vulnerable.)

New Flash bypass discovered

You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.

OWASP Recommend combining this with an Origin and Referer check:

This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)

However, for the reasons already discussed checking Origin can be tricky.

Update

Written a more in depth blog post on CORS, CSRF and X-Requested-With here.

How do I call an Angular.js filter with multiple arguments?

In templates, you can separate filter arguments by colons.

{{ yourExpression | yourFilter: arg1:arg2:... }}

From Javascript, you call it as

$filter('yourFilter')(yourExpression, arg1, arg2, ...)

There is actually an example hidden in the orderBy filter docs.


Example:

Let's say you make a filter that can replace things with regular expressions:

myApp.filter("regexReplace", function() { // register new filter

  return function(input, searchRegex, replaceRegex) { // filter arguments

    return input.replace(RegExp(searchRegex), replaceRegex); // implementation

  };
});

Invocation in a template to censor out all digits:

<p>{{ myText | regexReplace: '[0-9]':'X' }}</p>

Couldn't connect to server 127.0.0.1:27017

Just run mongod --repair from C:\Program Files\MongoDB\Server\4.0\bin

Here is the doc https://docs.mongodb.com/manual/tutorial/recover-data-following-unexpected-shutdown/

Javascript foreach loop on associative array object

Here is a simple way to use an associative array as a generic Object type:

_x000D_
_x000D_
Object.prototype.forEach = function(cb){_x000D_
   if(this instanceof Array) return this.forEach(cb);_x000D_
   let self = this;_x000D_
   Object.getOwnPropertyNames(this).forEach(_x000D_
      (k)=>{ cb.call(self, self[k], k); }_x000D_
   );_x000D_
};_x000D_
_x000D_
Object({a:1,b:2,c:3}).forEach((value, key)=>{ _x000D_
    console.log(`key/value pair: ${key}/${value}`);_x000D_
});
_x000D_
_x000D_
_x000D_

how to inherit Constructor from super class to sub class

Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?

It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.

zsh compinit: insecure directories

I fixed it by doing

sudo chown root:staff -R /usr/local/share/zsh

in my case other directories inside share/ also have "staff" group assigned

Emulate Samsung Galaxy Tab

What resolution and density should I set?

  • 1024x600

How can I indicate that this is large screen device?

  • you can't really (not that i know of)

What hardware does this tablet support?

What is max heap size?

  • not sure

Which Android version?

  • 2.2

Hope that helps - check the spec page for all unanswered questions.

iOS start Background Thread

Well that's pretty easy actually with GCD. A typical workflow would be something like this:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        // Perform async operation
        // Call your method/function here
        // Example:
        // NSString *result = [anObject calculateSomething];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // Update UI
                    // Example:
                    // self.myLabel.text = result;
                });
    });

For more on GCD you can take a look into Apple's documentation here

javascript code to check special characters

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

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

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

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

How do I write a Windows batch script to copy the newest file from a directory?

Bash:

 find -type f -printf "%T@ %p \n" \
     | sort  \
     | tail -n 1  \
     | sed -r "s/^\S+\s//;s/\s*$//" \
     | xargs -iSTR cp STR newestfile

where "newestfile" will become the newestfile

alternatively, you could do newdir/STR or just newdir

Breakdown:

  1. list all files in {time} {file} format.
  2. sort them by time
  3. get the last one
  4. cut off the time, and whitespace from the start/end
  5. copy resulting value

Important

After running this once, the newest file will be whatever you just copied :p ( assuming they're both in the same search scope that is ). So you may have to adjust which filenumber you copy if you want this to work more than once.

jQuery slide left and show

You can add new function to your jQuery library by adding these line on your own script file and you can easily use fadeSlideRight() and fadeSlideLeft().

Note: you can change width of animation as you like instance of 750px.

$.fn.fadeSlideRight = function(speed,fn) {
    return $(this).animate({
        'opacity' : 1,
        'width' : '750px'
    },speed || 400, function() {
        $.isFunction(fn) && fn.call(this);
    });
}

$.fn.fadeSlideLeft = function(speed,fn) {
    return $(this).animate({
        'opacity' : 0,
        'width' : '0px'
    },speed || 400,function() {
        $.isFunction(fn) && fn.call(this);
    });
}

How to query as GROUP BY in django?

You need to do custom SQL as exemplified in this snippet:

Custom SQL via subquery

Or in a custom manager as shown in the online Django docs:

Adding extra Manager methods

What are the differences between git branch, fork, fetch, merge, rebase and clone?

Here is Oliver Steele's image of how it all fits together:

enter image description here

Determine installed PowerShell version

This is the top search result for "Batch file get powershell version", so I'd like to provide a basic example of how to do conditional flow in a batch file depending on the powershell version

Generic example

powershell "exit $PSVersionTable.PSVersion.Major"
if %errorlevel% GEQ 5 (
    echo Do some fancy stuff that only powershell v5 or higher supports
) else (
    echo Functionality not support by current powershell version.
)

Real world example

powershell "exit $PSVersionTable.PSVersion.Major"
if %errorlevel% GEQ 5 (
    rem Unzip archive automatically
    powershell Expand-Archive Compressed.zip
) else (
    rem Make the user unzip, because lazy
    echo Please unzip Compressed.zip prior to continuing...
    pause
)

How to make div occupy remaining height?

<div>
  <div id="header">header</div>
  <div id="content">content</div>
  <div id="footer">footer</div>
</div>

#header {
  height: 200px;
}

#content {
  height: 100%;
  margin-bottom: -200px;
  padding-bottom: 200px;
  margin-top: -200px;
  padding-top: 200px;
}

#footer {
  height: 200px;
}

How to show SVG file on React Native?

I've tried all the above solutions and other solutions outside of the stack and none of working for me. finally, after long research, I've found one solution for my expo project.

If you need it to work in expo, one workaround might be to use https://react-svgr.com/playground/ and move the spreading of props to a G element instead of the SVG root like this:

import * as React from 'react';
import Svg, { G, Path } from 'react-native-svg';

function SvgComponent(props) {
  return (
    <Svg viewBox="0 0 511 511">
      <G {...props}>
        <Path d="M131.5 96c-11.537 0-21.955 8.129-29.336 22.891C95.61 132 92 149.263 92 167.5s3.61 35.5 10.164 48.609C109.545 230.871 119.964 239 131.5 239s21.955-8.129 29.336-22.891C167.39 203 171 185.737 171 167.5s-3.61-35.5-10.164-48.609C153.455 104.129 143.037 96 131.5 96zm15.92 113.401C142.78 218.679 136.978 224 131.5 224s-11.28-5.321-15.919-14.599C110.048 198.334 107 183.453 107 167.5s3.047-30.834 8.581-41.901C120.22 116.321 126.022 111 131.5 111s11.28 5.321 15.919 14.599C152.953 136.666 156 151.547 156 167.5s-3.047 30.834-8.58 41.901z" />
        <Path d="M474.852 158.011c-1.263-40.427-10.58-78.216-26.555-107.262C430.298 18.023 405.865 0 379.5 0h-248c-26.365 0-50.798 18.023-68.797 50.749C45.484 82.057 36 123.52 36 167.5s9.483 85.443 26.703 116.751C80.702 316.977 105.135 335 131.5 335a57.57 57.57 0 005.867-.312 7.51 7.51 0 002.133.312h48a7.5 7.5 0 000-15h-16c10.686-8.524 20.436-20.547 28.797-35.749 4.423-8.041 8.331-16.756 11.703-26.007V503.5a7.501 7.501 0 0011.569 6.3l20.704-13.373 20.716 13.374a7.498 7.498 0 008.134 0l20.729-13.376 20.729 13.376a7.49 7.49 0 004.066 1.198c1.416 0 2.832-.4 4.07-1.2l20.699-13.372 20.726 13.374a7.5 7.5 0 008.133 0l20.732-13.377 20.738 13.377a7.5 7.5 0 008.126.003l20.783-13.385 20.783 13.385a7.5 7.5 0 0011.561-6.305v-344a7.377 7.377 0 00-.146-1.488zM187.154 277.023C171.911 304.737 152.146 320 131.5 320s-40.411-15.263-55.654-42.977C59.824 247.891 51 208.995 51 167.5s8.824-80.391 24.846-109.523C91.09 30.263 110.854 15 131.5 15s40.411 15.263 55.654 42.977C203.176 87.109 212 126.005 212 167.5s-8.824 80.391-24.846 109.523zm259.563 204.171a7.5 7.5 0 00-8.122 0l-20.78 13.383-20.742-13.38a7.5 7.5 0 00-8.131 0l-20.732 13.376-20.729-13.376a7.497 7.497 0 00-8.136.002l-20.699 13.373-20.727-13.375a7.498 7.498 0 00-8.133 0l-20.728 13.375-20.718-13.375a7.499 7.499 0 00-8.137.001L227 489.728V271h8.5a7.5 7.5 0 000-15H227v-96.5c0-.521-.054-1.03-.155-1.521-1.267-40.416-10.577-78.192-26.548-107.231C191.936 35.547 182.186 23.524 171.5 15h208c20.646 0 40.411 15.263 55.654 42.977C451.176 87.109 460 126.005 460 167.5V256h-.5a7.5 7.5 0 000 15h.5v218.749l-13.283-8.555z" />
        <Path d="M283.5 256h-16a7.5 7.5 0 000 15h16a7.5 7.5 0 000-15zM331.5 256h-16a7.5 7.5 0 000 15h16a7.5 7.5 0 000-15zM379.5 256h-16a7.5 7.5 0 000 15h16a7.5 7.5 0 000-15zM427.5 256h-16a7.5 7.5 0 000 15h16a7.5 7.5 0 000-15z" />
      </G>
    </Svg>
  );
}

export default function App() {
  return (
    <SvgComponent width="100%" height="100%" strokeWidth={5} stroke="black" />
  );
}

Spring REST Service: how to configure to remove null objects in json response

If you are using Jackson 2, the message-converters tag is:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="prefixJson" value="true"/>
            <property name="supportedMediaTypes" value="application/json"/>
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion" value="NON_NULL"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

What does the arrow operator, '->', do in Java?

I believe, this arrow exists because of your IDE. IntelliJ IDEA does such thing with some code. This is called code folding. You can click at the arrow to expand it.

Environment Specific application.properties file in Spring Boot application

we can do like this:

in application.yml:

spring:
  profiles:
    active: test //modify here to switch between environments
    include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
  port: 5000

and in application-local.yml:

server:
  address: 0.0.0.0
  port: 8080

then spring boot will start our app as we wish to.

Transposing a 2D-array in JavaScript

array[0].map((_, colIndex) => array.map(row => row[colIndex]));

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. [source]

python plot normal distribution

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math

mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.show()

gass distro, mean is 0 variance 1

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

I'm learning from udemy. I followed every step that my instructor show me to do. In spring mvc crud section while setting up the devlopment environment i had the same error for:

<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" />

then i just replaced

    http://www.springframework.org/schema/mvc/spring-mvc.xsd 

with

    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

and

    http://www.springframework.org/schema/tx/spring-tx.xsd

with

    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

actually i visited these two sites http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/ and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd and spring-tx-4.2.xsd

So, i suggest to try this. Hope this helps. Thank you.

DateTime to javascript date

Another late answer, but this is missing here. If you want to handle conversion of serialized /Date(1425408717000)/ in javascript, you can simply call:

var cSharpDate = "/Date(1425408717000)/"
var jsDate = new Date(parseInt(cSharpDate.replace(/[^0-9 +]/g, '')));

Source: amirsahib

Is there a way to comment out markup in an .ASPX page?

Another way assuming it's not server side code you want to comment out is...

<asp:panel runat="server" visible="false">
    html here
</asp:panel>

Check if value exists in Postgres array

Simpler with the ANY construct:

SELECT value_variable = ANY ('{1,2,3}'::int[])

The right operand of ANY (between parentheses) can either be a set (result of a subquery, for instance) or an array. There are several ways to use it:

Important difference: Array operators (<@, @>, && et al.) expect array types as operands and support GIN or GiST indices in the standard distribution of PostgreSQL, while the ANY construct expects an element type as left operand and does not support these indices. Example:

None of this works for NULL elements. To test for NULL:

How to cut a string after a specific character in unix

Using sed:

$ [email protected]:/home/some/directory/file
$ echo $var | sed 's/.*://'
/home/some/directory/file

Why is the Android emulator so slow? How can we speed up the Android emulator?

I've similar issues on a Mac. What I did;

  • 1) on the emulator, settings-display -> disable screen orientation
  • 2) on Eclipse, emulator startup options -> -cpu-delay 100

Those had some effect in lowering CPU use (not it is around 40-60%), not ultimate solution. But again, the CPU use is NOT >100% anymore!

Move UIView up when the keyboard appears in iOS

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - keyboard movements
- (void)keyboardWillShow:(NSNotification *)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = -keyboardSize.height;
        self.view.frame = f;
    }];
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = 0.0f;
        self.view.frame = f;
    }];
}

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

Now you can get time for the current location but for this you have to set the system's persistent default time zone.setTimeZone(String timeZone) which can be get from

Calendar calendar = Calendar.getInstance();
 long now = calendar.getTimeInMillis();
 TimeZone current = calendar.getTimeZone();

setAutoTimeEnabled(boolean enabled)

Sets whether or not wall clock time should sync with automatic time updates from NTP.

TimeManager timeManager = TimeManager.getInstance();
 // Use 24-hour time
 timeManager.setTimeFormat(TimeManager.FORMAT_24);

 // Set clock time to noon
 Calendar calendar = Calendar.getInstance();
 calendar.set(Calendar.MILLISECOND, 0);
 calendar.set(Calendar.SECOND, 0);
 calendar.set(Calendar.MINUTE, 0);
 calendar.set(Calendar.HOUR_OF_DAY, 12);
 long timeStamp = calendar.getTimeInMillis();
 timeManager.setTime(timeStamp);

I was looking for that type of answer I read your answer but didn't satisfied and it was bit old. I found the new solution and share it. :)

For more information visit: https://developer.android.com/things/reference/com/google/android/things/device/TimeManager.html

Creating stored procedure and SQLite?

Answer: NO

Here's Why ... I think a key reason for having stored procs in a database is that you're executing SP code in the same process as the SQL engine. This makes sense for database engines designed to work as a network connected service but the imperative for SQLite is much less given that it runs as a DLL in your application process rather than in a separate SQL engine process. So it makes more sense to implement all your business logic including what would have been SP code in the host language.

You can however extend SQLite with your own user defined functions in the host language (PHP, Python, Perl, C#, Javascript, Ruby etc). You can then use these custom functions as part of any SQLite select/update/insert/delete. I've done this in C# using DevArt's SQLite to implement password hashing.

Using app.config in .Net Core

I have a .Net Core 3.1 MSTest project with similar issue. This post provided clues to fix it.

Breaking this down to a simple answer for .Net core 3.1:

  • add/ensure nuget package: System.Configuration.ConfigurationManager to project
  • add your app.config(xml) to project.

If it is a MSTest project:

  • rename file in project to testhost.dll.config

    OR

  • Use post-build command provided by DeepSpace101

Colspan all columns

If you want to make a 'title' cell that spans all columns, as header for your table, you may want to use the caption tag (http://www.w3schools.com/tags/tag_caption.asp / https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) This element is meant for this purpose. It behaves like a div, but doesn't span the entire width of the parent of the table (like a div would do in the same position (don't try this at home!)), instead, it spans the width of the table. There are some cross-browser issues with borders and such (was acceptable for me). Anyways, you can make it look as a cell that spans all columns. Within, you can make rows by adding div-elements. I'm not sure if you can insert it in between tr-elements, but that would be a hack I guess (so not recommended). Another option would be messing around with floating divs, but that is yuck!

Do

<table>
    <caption style="gimme some style!"><!-- Title of table --></caption>
    <thead><!-- ... --></thead>
    <tbody><!-- ... --></tbody>
</table>

Don't

<div>
    <div style="float: left;/* extra styling /*"><!-- Title of table --></div>
    <table>
        <thead><!-- ... --></thead>
        <tbody><!-- ... --></tbody>
    </table>
    <div style="clear: both"></div>
</div>

Turn a simple socket into an SSL socket

Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>

#include <breakermindsslserver.h>

using namespace std;

int main(int argc, char *argv[])
{
    BreakermindSslServer boom;
    boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
    return 0;
}

Return a value if no rows are found in Microsoft tSQL

I read all the answers here, and it took a while to figure out what was going on. The following is based on the answer by Moe Sisko and some related research

If your SQL query does not return any data there is not a field with a null value so neither ISNULL nor COALESCE will work as you want them to. By using a sub query, the top level query gets a field with a null value, and both ISNULL and COALESCE will work as you want/expect them to.

My query

select isnull(
 (select ASSIGNMENTM1.NAME
 from dbo.ASSIGNMENTM1
 where ASSIGNMENTM1.NAME = ?)
, 'Nothing Found') as 'ASSIGNMENTM1.NAME'

My query with comments

select isnull(
--sub query either returns a value or returns nothing (no value)
 (select ASSIGNMENTM1.NAME
 from dbo.ASSIGNMENTM1
 where ASSIGNMENTM1.NAME = ?)
 --If there is a value it is displayed 
 --If no value, it is perceived as a field with a null value, 
 --so the isnull function can give the desired results
, 'Nothing Found') as 'ASSIGNMENTM1.NAME'

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

How to keep environment variables when using sudo

If you have the need to keep the environment variables in a script you can put your command in a here document like this. Especially if you have lots of variables to set things look tidy this way.

# prepare a script e.g. for running maven
runmaven=/tmp/runmaven$$
# create the script with a here document 
cat << EOF > $runmaven
#!/bin/bash
# run the maven clean with environment variables set
export ANT_HOME=/usr/share/ant
export MAKEFLAGS=-j4
mvn clean install
EOF
# make the script executable
chmod +x $runmaven
# run it
sudo $runmaven
# remove it or comment out to keep
rm $runmaven

Asp.net Validation of viewstate MAC failed

If you're using a web farm and running the same application on multiple computers, you need to define the machine key explicitly in the machine.config file:

<machineKey validationKey="JFDSGOIEURTJKTREKOIRUWTKLRJTKUROIUFLKSIOSUGOIFDS..." decryptionKey="KAJDFOIAUOILKER534095U43098435H43OI5098479854" validation="SHA1" />

Put it under the <system.web> tag.

The AutoGenerate for the machine code can not be used. To generate your own machineKey see this powershell script: https://support.microsoft.com/en-us/kb/2915218#bookmark-appendixa

AngularJS : ng-model binding not updating when changed with jQuery

Just use:

$('#selectedDueDate').val(dateText).trigger('input');

instead of:

$('#selectedDueDate').val(dateText);

move_uploaded_file gives "failed to open stream: Permission denied" error

Change permissions for this folder

# chmod -R 0755 /var/www/html/mysite/images/

How to get second-highest salary employees in a table

Simple way WITHOUT using any special feature specific to Oracle, MySQL etc.

Suppose EMPLOYEE table has data as below. Salaries can be repeated. enter image description here

By manual analysis we can decide ranks as follows :-
enter image description here

Same result can be achieved by query

select  *
from  (
select tout.sal, id, (select count(*) +1 from (select distinct(sal) distsal from     
EMPLOYEE ) where  distsal >tout.sal)  as rank  from EMPLOYEE tout
) result
order by rank

enter image description here

First we find out distinct salaries. Then we find out count of distinct salaries greater than each row. This is nothing but the rank of that id. For highest salary, this count will be zero. So '+1' is done to start rank from 1.

Now we can get IDs at Nth rank by adding where clause to above query.

select  *
from  (
select tout.sal, id, (select count(*) +1 from (select distinct(sal) distsal from     
EMPLOYEE ) where  distsal >tout.sal)  as rank  from EMPLOYEE tout
) result
where rank = N;

How to export data to an excel file using PHPExcel

I currently use this function in my project after a series of googling to download excel file from sql statement

    // $sql = sql query e.g "select * from mytablename"
    // $filename = name of the file to download 
        function queryToExcel($sql, $fileName = 'name.xlsx') {
                // initialise excel column name
                // currently limited to queries with less than 27 columns
        $columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
                // Execute the database query
                $result =  mysql_query($sql) or die(mysql_error());

                // Instantiate a new PHPExcel object
                $objPHPExcel = new PHPExcel();
                // Set the active Excel worksheet to sheet 0
                $objPHPExcel->setActiveSheetIndex(0);
                // Initialise the Excel row number
                $rowCount = 1;
    // fetch result set column information
                $finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter                
$columnlenght = 0;
                foreach ($finfo as $val) {
// set column header values                   
  $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
                }
// make the column headers bold
                $objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);

                $rowCount++;
                // Iterate through each result from the SQL query in turn
                // We fetch each database result row into $row in turn

                while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
                    for ($i = 0; $i < $columnLenght; $i++) {
                        $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
                    }
                    $rowCount++;
                }
// set header information to force download
                header('Content-type: application/vnd.ms-excel');
                header('Content-Disposition: attachment; filename="' . $fileName . '"');
                // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file        
                // Write the Excel file to filename some_excel_file.xlsx in the current directory                
                $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
                // Write the Excel file to filename some_excel_file.xlsx in the current directory
                $objWriter->save('php://output');
            }

jQuery - Trigger event when an element is removed from the DOM

Hooking .remove() is not the best way to handle this as there are many ways to remove elements from the page (e.g. by using .html(), .replace(), etc).

In order to prevent various memory leak hazards, internally jQuery will try to call the function jQuery.cleanData() for each removed element regardless of the method used to remove it.

See this answer for more details: javascript memory leaks

So, for best results, you should hook the cleanData function, which is exactly what the jquery.event.destroyed plugin does:

http://v3.javascriptmvc.com/jquery/dist/jquery.event.destroyed.js

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

If you use MVC, tables, it works like this:

<td>@(((DateTime)detalle.fec).ToString("dd'/'MM'/'yyyy"))</td>

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

When I had an error Access Error: 404 -- Not Found I fixed it by doing the following:

  1. Open command prompt and type "netstat -aon" (without the quotes)
  2. Search for port 8080 and look at its PID number/code.
  3. Open Task Manager (CTRL+ALT+DELETE), go to Services tab, and find the service with the exact PID number. Then right click it and stop the process.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

I added -XX: MaxPermSize = 128m (you can experiment which works best) to VM Arguments as I'm using eclipse ide. In most of JVM, default PermSize is around 64MB which runs out of memory if there are too many classes or huge number of Strings in the project.

For eclipse, it is also described at answer.

STEP 1 : Double Click on the tomcat server at Servers Tab

enter image description here

STEP 2 : Open launch Conf and add -XX: MaxPermSize = 128m to the end of existing VM arguements.

enter image description here

Best way to handle multiple constructors in Java

Consider using the Builder pattern. It allows for you to set default values on your parameters and initialize in a clear and concise way. For example:


    Book b = new Book.Builder("Catcher in the Rye").Isbn("12345")
       .Weight("5 pounds").build();

Edit: It also removes the need for multiple constructors with different signatures and is way more readable.

Is it possible to access an SQLite database from JavaScript?

One of the most interesting features in HTML5 is the ability to store data locally and to allow the application to run offline. There are three different APIs that deal with these features and choosing one depends on what exactly you want to do with the data you're planning to store locally:

  1. Web storage: For basic local storage with key/value pairs
  2. Offline storage: Uses a manifest to cache entire files for offline use
  3. Web database: For relational database storage

For more reference see Introducing the HTML5 storage APIs

And how to use

http://cookbooks.adobe.com/post_Store_data_in_the_HTML5_SQLite_database-19115.html

Detect if page has finished loading

there are two ways to do this in jquery depending what you are looking for..

using jquery you can do

  • //this will wait for the text assets to be loaded before calling this (the dom.. css.. js)

    $(document).ready(function(){...});
    
  • //this will wait for all the images and text assets to finish loading before executing

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

How do I delete everything below row X in VBA/Excel?

Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.

Split string using a newline delimiter with Python

data = """a,b,c
d,e,f
g,h,i
j,k,l"""

print(data.split())       # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

str.split, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use

print(data.split("\n"))   # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Or as @Ashwini Chaudhary suggested in the comments, you can use

print(data.splitlines())

POST string to ASP.NET Web Api application - returns null

Web API works very nicely if you accept the fact that you are using HTTP. It's when you start trying to pretend that you are sending objects over the wire that it starts to get messy.

 public class TextController : ApiController
    {
        public HttpResponseMessage Post(HttpRequestMessage request) {

            var someText = request.Content.ReadAsStringAsync().Result;
            return new HttpResponseMessage() {Content = new StringContent(someText)};

        }

    }

This controller will handle a HTTP request, read a string out of the payload and return that string back.

You can use HttpClient to call it by passing an instance of StringContent. StringContent will be default use text/plain as the media type. Which is exactly what you are trying to pass.

    [Fact]
    public void PostAString()
    {

        var client = new HttpClient();

        var content = new StringContent("Some text");
        var response = client.PostAsync("http://oak:9999/api/text", content).Result;

        Assert.Equal("Some text",response.Content.ReadAsStringAsync().Result);

    }

How do I collapse sections of code in Visual Studio Code for Windows?

Or, if you want to remove the folding buttons, for extra space:

"editor.folding": false

(add to your settings.json file)

Disable Drag and Drop on HTML elements?

This might work: You can disable selecting with css3 for text, image and basically everything.

.unselectable {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   /*
     Introduced in IE 10.
     See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   */
   -ms-user-select: none;
   user-select: none;
}

Of course only for the newer browsers. For more details check:

How to disable text selection highlighting using CSS?

How to set background color of a View

mButton.setBackgroundColor(getResources().getColor(R.color.myColor));

How can I de-install a Perl module installed via `cpan`?

You can't. There isn't a feature in my CPAN client to do such a thing. We were talking about how we might do something like that at this weekend's Perl QA Workshop, but it's generally hard for all the reasons that Ether mentioned.

Python not working in the command line of git bash

You can change target for Git Bash shortcut from:

"C:\Program Files\Git\git-bash.exe" --cd-to-home 

to

"C:\Program Files\Git\git-cmd.exe" --no-cd --command=usr/bin/bash.exe -l -i

This is the way ConEmu used to start git bash (version 16). Recent version starts it normally and it's how I got there...

VB.NET - How to move to next item a For Each Loop?

I want to be clear that the following code is not good practice. You can use GOTO Label:

For Each I As Item In Items

    If I = x Then
       'Move to next item
        GOTO Label1
    End If

    ' Do something
    Label1:
Next

Delete all Duplicate Rows except for One in MySQL?

If you want to keep the row with the lowest id value:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MIN(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

If you want the id value that is the highest:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MAX(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.

Sanitizing user input before adding it to the DOM in Javascript

You need to take extra precautions when using user supplied data in HTML attributes. Because attributes has many more attack vectors than output inside HTML tags.

The only way to avoid XSS attacks is to encode everything except alphanumeric characters. Escape all characters with ASCII values less than 256 with the &#xHH; format. Which unfortunately may cause problems in your scenario, if you are using CSS classes and javascript to fetch those elements.

OWASP has a good description of how to mitigate HTML attribute XSS:

http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.233_-_JavaScript_Escape_Before_Inserting_Untrusted_Data_into_HTML_JavaScript_Data_Values

phpexcel to download

$excel = new PHPExcel();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');

// Do your stuff here

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');

// This line will force the file to download
$writer->save('php://output');

Install GD library and freetype on Linux

Installing GD :

For CentOS / RedHat / Fedora :

sudo yum install php-gd

For Debian/ubuntu :

sudo apt-get install php5-gd

Installing freetype :

For CentOS / RedHat / Fedora :

sudo yum install freetype*

For Debian/ubuntu :

sudo apt-get install freetype*

Don't forget to restart apache after that (if you are using apache):

CentOS / RedHat / Fedora :

sudo /etc/init.d/httpd restart

Or

sudo service httpd restart

Debian/ubuntu :

sudo /etc/init.d/apache2 restart

Or

sudo service apache2 restart

iOS 6 apps - how to deal with iPhone 5 screen size?

I have just finished updating and sending an iOS 6.0 version of one of my Apps to the store. This version is backwards compatible with iOS 5.0, thus I kept the shouldAutorotateToInterfaceOrientation: method and added the new ones as listed below.

I had to do the following:

Autorotation is changing in iOS 6. In iOS 6, the shouldAutorotateToInterfaceOrientation: method of UIViewController is deprecated. In its place, you should use the supportedInterfaceOrientationsForWindow: and shouldAutorotate methods. Thus, I added these new methods (and kept the old for iOS 5 compatibility):

- (BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAllButUpsideDown;    
}
  • Used the view controller’s viewWillLayoutSubviews method and adjust the layout using the view’s bounds rectangle.
  • Modal view controllers: The willRotateToInterfaceOrientation:duration:,
    willAnimateRotationToInterfaceOrientation:duration:, and
    didRotateFromInterfaceOrientation: methods are no longer called on any view controller that makes a full-screen presentation over
    itself
    —for example, presentViewController:animated:completion:.
  • Then I fixed the autolayout for views that needed it.
  • Copied images from the simulator for startup view and views for the iTunes store into PhotoShop and exported them as png files.
  • The name of the default image is: [email protected] and the size is 640×1136. It´s also allowed to supply 640×1096 for the same portrait mode (Statusbar removed). Similar sizes may also be supplied in landscape mode if your app only allows landscape orientation on the iPhone.
  • I have dropped backward compatibility for iOS 4. The main reason for that is because support for armv6 code has been dropped. Thus, all devices that I am able to support now (running armv7) can be upgraded to iOS 5.
  • I am also generation armv7s code to support the iPhone 5 and thus can not use any third party frameworks (as Admob etc.) until they are updated.

That was all but just remember to test the autorotation in iOS 5 and iOS 6 because of the changes in rotation.

Angularjs $http.get().then and binding to a list

Try using the success() call back

$http.get('/Documents/DocumentsList/' + caseId).success(function (result) {
    $scope.Documents = result;
});

But now since Documents is an array and not a promise, remove the ()

<li ng-repeat="document in Documents" ng-class="IsFiltered(document.Filtered)"> <span>
           <input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" />
        </span>
 <span>{{document.Name}}</span>

</li>

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

One very practical way to do this is to create a dummy start page for your tests that is simply a form with POST that has a single "start test" button and a bunch of <input type="hidden"... elements with the appropriate post data.

For example you might create a SeleniumTestStart.html page with these contents:

<body>
  <form action="/index.php" method="post">
    <input id="starttestbutton" type="submit" value="starttest"/>
    <input type="hidden" name="stageid" value="stage-you-need-your-test-to-start-at"/>
  </form>
</body>

In this example, index.php is where your normal web app is located.

The Selenium code at the start of your tests would then include:

open /SeleniumTestStart.html
clickAndWait starttestbutton

This is very similar to other mock and stub techniques used in automated testing. You are just mocking the entry point to the web app.

Obviously there are some limitations to this approach:

  1. data cannot be too large (e.g. image data)
  2. security might be an issue so you need to make sure that these test files don't end up on your production server
  3. you may need to make your entry points with something like php instead of html if you need to set cookies before the Selenium test gets going
  4. some web apps check the referrer to make sure someone isn't hacking the app - in this case this approach probably won't work - you may be able to loosen this checking in a dev environment so it allows referrers from trusted hosts (not self, but the actual test host)

Please consider reading my article about the Qualities of an Ideal Test

How to add image to canvas

You have to use .onload

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); 

const drawImage = (url) => {
    const image = new Image();
    image.src = url;
    image.onload = () => {
       ctx.drawImage(image, 0, 0)
    }
}

Here's Why

If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()

Query to get only numbers from a string

If you are using Postgres and you have data like '2000 - some sample text' then try substring and position combination, otherwise if in your scenario there is no delimiter, you need to write regex:

SUBSTRING(Column_name from 0 for POSITION('-' in column_name) - 1) as 
number_column_name

automatically execute an Excel macro on a cell change

Your code looks pretty good.

Be careful, however, for your call to Range("H5") is a shortcut command to Application.Range("H5"), which is equivalent to Application.ActiveSheet.Range("H5"). This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.

With this in mind, I would utilize Target.Worksheet.Range("H5"):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub

Or you can use Me.Range("H5"), if the event handler is on the code page for the worksheet in question (it usually is):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub

Hope this helps...

Locking pattern for proper use of .NET MemoryCache

I assume this code has concurrency issues:

Actually, it's quite possibly fine, though with a possible improvement.

Now, in general the pattern where we have multiple threads setting a shared value on first use, to not lock on the value being obtained and set can be:

  1. Disastrous - other code will assume only one instance exists.
  2. Disastrous - the code that obtains the instance is not can only tolerate one (or perhaps a certain small number) concurrent operations.
  3. Disastrous - the means of storage is not thread-safe (e.g. have two threads adding to a dictionary and you can get all sorts of nasty errors).
  4. Sub-optimal - the overall performance is worse than if locking had ensured only one thread did the work of obtaining the value.
  5. Optimal - the cost of having multiple threads do redundant work is less than the cost of preventing it, especially since that can only happen during a relatively brief period.

However, considering here that MemoryCache may evict entries then:

  1. If it's disastrous to have more than one instance then MemoryCache is the wrong approach.
  2. If you must prevent simultaneous creation, you should do so at the point of creation.
  3. MemoryCache is thread-safe in terms of access to that object, so that is not a concern here.

Both of these possibilities have to be thought about of course, though the only time having two instances of the same string existing can be a problem is if you're doing very particular optimisations that don't apply here*.

So, we're left with the possibilities:

  1. It is cheaper to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().
  2. It is cheaper not to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().

And working that out can be difficult (indeed, the sort of thing where it's worth profiling rather than assuming you can work it out). It's worth considering here though that most obvious ways of locking on insert will prevent all additions to the cache, including those that are unrelated.

This means that if we had 50 threads trying to set 50 different values, then we'll have to make all 50 threads wait on each other, even though they weren't even going to do the same calculation.

As such, you're probably better off with the code you have, than with code that avoids the race-condition, and if the race-condition is a problem, you quite likely either need to handle that somewhere else, or need a different caching strategy than one that expels old entries†.

The one thing I would change is I'd replace the call to Set() with one to AddOrGetExisting(). From the above it should be clear that it probably isn't necessary, but it would allow the newly obtained item to be collected, reducing overall memory use and allowing a higher ratio of low generation to high generation collections.

So yeah, you could use double-locking to prevent concurrency, but either the concurrency isn't actually a problem, or your storing the values in the wrong way, or double-locking on the store would not be the best way to solve it.

*If you know only one each of a set of strings exists, you can optimise equality comparisons, which is about the only time having two copies of a string can be incorrect rather than just sub-optimal, but you'd want to be doing very different types of caching for that to make sense. E.g. the sort XmlReader does internally.

†Quite likely either one that stores indefinitely, or one that makes use of weak references so it will only expel entries if there are no existing uses.

laravel 5 : Class 'input' not found

It's changed in laravel 6. See for more info here

Don't do anything in app.php and anywhere else, just replace

input::get() with Request::input()

and

on top where you declare Input,Validator,Hash etc., remove Input and add Request

use something like :

Config,DB,File,Hash,Input,Redirect,Session,View,Validator,Request;

Regular expression to match non-ASCII characters?

All Unicode-enabled Regex flavours should have a special character class like \w that match any Unicode letter. Take a look at your specific flavour here.

MVC Calling a view from a different controller

To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.

public class CommentsController : Controller
{
    public ActionResult Index()
    { 
        return View("../Articles/Index", model );
    }
}

and

public class ArticlesController : Controller
{
    public ActionResult Index()
    { 
        return View();
    }
}

Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.

Is there a way I can capture my iPhone screen as a video?

As others have suggested, AirPlay mirroring is the way to go. To mirror directly to your computer use an AirPlay server like http://www.airserverapp.com/. Then, since it's showing up directly on your computer you can capture it using the built-in Quicktime app (File > New Screen Recording). Works great!

Delete the 'first' record from a table in SQL Server, without a WHERE condition

What do you mean by «'first' record from a table» ? There's no such concept as "first record" in a relational db, i think.

Using MS SQL Server 2005, if you intend to delete the "top record" (the first one that is presented when you do a simple "*select * from tablename*"), you may use "delete top(1) from tablename"... but be aware that this does not assure which row is deleted from the recordset, as it just removes the first row that would be presented if you run the command "select top(1) from tablename".

AngularJS ng-class if-else expression

you could try by using a function like that :

<div ng-class='whatClassIsIt(call.State)'>

Then put your logic in the function itself :

    $scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
     else
         return "ClassC";
    }

I made a fiddle with an example : http://jsfiddle.net/DotDotDot/nMk6M/

node.js execute system command synchronously

See execSync library.

It's fairly easy to do with node-ffi. I wouldn't recommend for server processes, but for general development utilities it gets things done. Install the library.

npm install node-ffi

Example script:

var FFI = require("node-ffi");
var libc = new FFI.Library(null, {
  "system": ["int32", ["string"]]
});

var run = libc.system;
run("echo $USER");

[EDIT Jun 2012: How to get STDOUT]

var lib = ffi.Library(null, {
    // FILE* popen(char* cmd, char* mode);
    popen: ['pointer', ['string', 'string']],

    // void pclose(FILE* fp);
    pclose: ['void', [ 'pointer']],

    // char* fgets(char* buff, int buff, in)
    fgets: ['string', ['string', 'int','pointer']]
});

function execSync(cmd) {
  var
    buffer = new Buffer(1024),
    result = "",
    fp = lib.popen(cmd, 'r');

  if (!fp) throw new Error('execSync error: '+cmd);

  while(lib.fgets(buffer, 1024, fp)) {
    result += buffer.readCString();
  };
  lib.pclose(fp);

  return result;
}

console.log(execSync('echo $HOME'));

How do I convert speech to text?

.NET can do it with its System.Speech namespace.

You would have to convert to .wav first or capture the audio live from the mic.

Details on implementation can be found here: Transcribing Audio with .NET

How to Add Incremental Numbers to a New Column Using Pandas

import numpy as np

df['New_ID']=np.arange(880,880+len(df.Fruit))
df=df.reindex(columns=['New_ID','ID','Fruit'])

Windows error 2 occured while loading the Java VM

In cmd

C:\Users\Downloads>install.exe LAX_VM "C:\Program Files\Java\jdk1.8.0_60\bin\java.exe"

Inconsistent accessibility: property type is less accessible

Your class Delivery has no access modifier, which means it defaults to internal. If you then try to expose a property of that type as public, it won't work. Your type (class) needs to have the same, or higher access as your property.

More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx

How to change css property using javascript

Just for the info, this can be done with CSS only with just minor HTML and CSS changes

HTML:

<div class="left">
    Hello
</div>
<div class="right">
    Hello2
</div>
<div class="center">
       <div class="left1">
           Bye
    </div>
       <div class="right1">
           Bye1
    </div>    
</div>

CSS:

.left, .right{
    margin:10px;
    float:left;
    border:1px solid red;
    height:60px;
    width:60px
}
.left:hover, .right:hover{
    border:1px solid blue;
}
.right{
     float :right;
}
.center{
    float:left;
    height:60px;
    width:160px
}

.center .left1, .center .right1{
    margin:10px;
    float:left;
    border:1px solid green;
    height:60px;
    width:58px;
    display:none;
}
.left:hover ~ .center .left1 {
    display:block;
}

.right:hover ~ .center .right1 {
    display:block;
}

and the DEMO: http://jsfiddle.net/pavloschris/y8LKM/

How to get the current date without the time?

Well, you can get just today's date as a DateTime using the Today property:

 DateTime today = DateTime.Today;

or more generally, you can use the Date property. For example, if you wanted the UTC date you could use:

 DateTime dateTime = DateTime.UtcNow.Date;

It's not very clear whether that's what you need or not though... if you're just looking to print the date, you can use:

Console.WriteLine(dateTime.ToString("d"));

or use an explicit format:

Console.WriteLine(dateTime.ToString("dd/MM/yyyy"));

See more about standard and custom date/time format strings. Depending on your situation you may also want to specify the culture.

If you want a more expressive date/time API which allows you to talk about dates separately from times, you might want to look at the Noda Time project which I started. It's not ready for production just yet, but we'd love to hear what you'd like to do with it...

Setting environment variables for accessing in PHP when using Apache

If your server is Ubuntu and Apache version is 2.4

Server version: Apache/2.4.29 (Ubuntu)

Then you export variables in "/etc/apache2/envvars" location.

Just like this below line, you need to add an extra line in "/etc/apache2/envvars" export GOROOT=/usr/local/go

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Regex Explanation ^.*$

  • ^ matches position just before the first character of the string
  • $ matches position just after the last character of the string
  • . matches a single character. Does not matter what character it is, except newline
  • * matches preceding match zero or more times

So, ^.*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.

Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones and Matthew's last name is Jones. The pattern ^Matt.*Jones$ will match Matthew's last name is Jones. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.

Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.

Reverting single file in SVN to a particular revision

sudo svn revert filename

this is the better way to revert a single file

Adding link a href to an element using css

You don't need CSS for this.

     <img src="abc"/>

now with link:

     <a href="#myLink"><img src="abc"/></a>

Or with jquery, later on, you can use the wrap property, see these questions answer:

how to add a link to an image using jquery?

How to position a Bootstrap popover?

I solved this (partially) by adding some lines of code to the bootstrap css library. You will have to modify tooltip.js, tooltip.less, popover.js, and popover.less

in tooltip.js, add this case in the switch statement there

case 'bottom-right':
          tp = {top: pos.top + pos.height, left: pos.left + pos.width}
          break

in tooltip.less, add these two lines in .tooltip{}

&.bottom-right { margin-top:   -2px; }
&.bottom-right .tooltip-arrow { #popoverArrow > .bottom(); }

do the same in popover.js and popover.less. Basically, wherever you find code where other positions are mentioned, add your desired position accordingly.

As I mentioned earlier, this solved the problem partially. My problem now is that the little arrow of the popover does not appear.

note: if you want to have the popover in top-left, use top attribute of '.top' and left attribute of '.left'

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

Adding new files to a subversion repository

Probably svn import would be the best option around. Check out Getting Data into Your Repository (in Version Control with Subversion, For Subversion).

The svn import command is a quick way to copy an unversioned tree of files into a repository, creating intermediate directories as necessary. svn import doesn't require a working copy, and your files are immediately committed to the repository. You typically use this when you have an existing tree of files that you want to begin tracking in your Subversion repository. For example:

$ svn import /path/to/mytree \
             http://svn.example.com/svn/repo/some/project \
             -m "Initial import"
Adding         mytree/foo.c
Adding         mytree/bar.c
Adding         mytree/subdir
Adding         mytree/subdir/quux.h

Committed revision 1.
$

The previous example copied the contents of the local directory mytree into the directory some/project in the repository. Note that you didn't have to create that new directory first—svn import does that for you. Immediately after the commit, you can see your data in the repository:

$ svn list http://svn.example.com/svn/repo/some/project
bar.c
foo.c
subdir/
$

Note that after the import is finished, the original local directory is not converted into a working copy. To begin working on that data in a versioned fashion, you still need to create a fresh working copy of that tree.

Note: if you are on the same machine as the Subversion repository you can use the file:// specifier with a path rather than the https:// with a URL specifier.

Naming returned columns in Pandas aggregate function?

For pandas >= 0.25

The functionality to name returned aggregate columns has been reintroduced in the master branch and is targeted for pandas 0.25. The new syntax is .agg(new_col_name=('col_name', 'agg_func'). Detailed example from the PR linked above:

In [2]: df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
   ...:                    'height': [9.1, 6.0, 9.5, 34.0],
   ...:                    'weight': [7.9, 7.5, 9.9, 198.0]})
   ...:

In [3]: df
Out[3]:
  kind  height  weight
0  cat     9.1     7.9
1  dog     6.0     7.5
2  cat     9.5     9.9
3  dog    34.0   198.0

In [4]: df.groupby('kind').agg(min_height=('height', 'min'), 
                               max_weight=('weight', 'max'))
Out[4]:
      min_height  max_weight
kind
cat          9.1         9.9
dog          6.0       198.0

It will also be possible to use multiple lambda expressions with this syntax and the two-step rename syntax I suggested earlier (below) as per this PR. Again, copying from the example in the PR:

In [2]: df = pd.DataFrame({"A": ['a', 'a'], 'B': [1, 2], 'C': [3, 4]})

In [3]: df.groupby("A").agg({'B': [lambda x: 0, lambda x: 1]})
Out[3]:
         B
  <lambda> <lambda 1>
A
a        0          1

and then .rename(), or in one go:

In [4]: df.groupby("A").agg(b=('B', lambda x: 0), c=('B', lambda x: 1))
Out[4]:
   b  c
A
a  0  0

For pandas < 0.25

The currently accepted answer by unutbu describes are great way of doing this in pandas versions <= 0.20. However, as of pandas 0.20, using this method raises a warning indicating that the syntax will not be available in future versions of pandas.

Series:

FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version

DataFrames:

FutureWarning: using a dict with renaming is deprecated and will be removed in a future version

According to the pandas 0.20 changelog, the recommended way of renaming columns while aggregating is as follows.

# Create a sample data frame
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
                   'B': range(5),
                   'C': range(5)})

# ==== SINGLE COLUMN (SERIES) ====
# Syntax soon to be deprecated
df.groupby('A').B.agg({'foo': 'count'})
# Recommended replacement syntax
df.groupby('A').B.agg(['count']).rename(columns={'count': 'foo'})

# ==== MULTI COLUMN ====
# Syntax soon to be deprecated
df.groupby('A').agg({'B': {'foo': 'sum'}, 'C': {'bar': 'min'}})
# Recommended replacement syntax
df.groupby('A').agg({'B': 'sum', 'C': 'min'}).rename(columns={'B': 'foo', 'C': 'bar'})
# As the recommended syntax is more verbose, parentheses can
# be used to introduce line breaks and increase readability
(df.groupby('A')
    .agg({'B': 'sum', 'C': 'min'})
    .rename(columns={'B': 'foo', 'C': 'bar'})
)

Please see the 0.20 changelog for additional details.

Update 2017-01-03 in response to @JunkMechanic's comment.

With the old style dictionary syntax, it was possible to pass multiple lambda functions to .agg, since these would be renamed with the key in the passed dictionary:

>>> df.groupby('A').agg({'B': {'min': lambda x: x.min(), 'max': lambda x: x.max()}})

    B    
  max min
A        
1   2   0
2   4   3

Multiple functions can also be passed to a single column as a list:

>>> df.groupby('A').agg({'B': [np.min, np.max]})

     B     
  amin amax
A          
1    0    2
2    3    4

However, this does not work with lambda functions, since they are anonymous and all return <lambda>, which causes a name collision:

>>> df.groupby('A').agg({'B': [lambda x: x.min(), lambda x: x.max]})
SpecificationError: Function names must be unique, found multiple named <lambda>

To avoid the SpecificationError, named functions can be defined a priori instead of using lambda. Suitable function names also avoid calling .rename on the data frame afterwards. These functions can be passed with the same list syntax as above:

>>> def my_min(x):
>>>     return x.min()

>>> def my_max(x):
>>>     return x.max()

>>> df.groupby('A').agg({'B': [my_min, my_max]})

       B       
  my_min my_max
A              
1      0      2
2      3      4

Java: Check if command line arguments are null

You should check for (args == null || args.length == 0). Although the null check isn't really needed, it is a good practice.

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

This looks like a missing SPN issue. The website you had pointed to has

principal="webserver/[email protected]" 

This is the principal for which the ticket would be obtained. Did you change this to a value relative to your AD domain?

You could use the command line kerberos tools to test if you have the SPN defined:

[root@gen-cs218 bin]# kinit Administrator
[email protected]'s Password:
[root@gen-cs218 bin]# kgetcred host/[email protected]
[root@gen-cs218 bin]# klist
Credentials cache: FILE:/tmp/krb5cc_0
        Principal: [email protected]

  Issued                Expires               Principal <br>
Dec 15 11:42:34 2012  Dec 15 21:42:34 2012  krbtgt/[email protected]
Dec 15 11:42:48 2012  Dec 15 21:42:34 2012  host/[email protected]

Hostname based SPNs are pre-defined. If you want to use a SPN that is not pre-defined you will have to explicitly define it in AD using the setspn.exe tool and associate it with either a computer or an user account, for example:

c:\> setspn.exe -A "webserver/bully@MYDOMAIN" myuser

You can check which account a SPN is associated with by using the command below. This will not show pre-defined SPNs.

c:\> setspn.exe -L "webserver/bully@MYDOMAIN"

Detect page change on DataTable

In my case, the 'page.dt' event did not do the trick.

I used 'draw.dt' event instead, and it works!, some code:

$(document).on('draw.dt', function () {
    //Do something
});

'Draw.dt' event is fired everytime the datatable page change by searching, ordering or page changing.

/***** Aditional Info *****/

There are some diferences in the way we can declare the event listener. You can asign it to the 'document' or to a 'html object'. The 'document' listeners will always exist in the page and the 'html object' listener will exist only if the object exist in the DOM in the moment of the declaration. Some code:

//Document event listener

$(document).on('draw.dt', function () {
    //This will also work with objects loaded by ajax calls
});

//HTML object event listener

$("#some-id").on('draw.dt', function () {
    //This will work with existing objects only
});

recyclerview No adapter attached; skipping layout

I had the same problem and realized I was setting both the LayoutManager and adapter after retrieving the data from my source instead of setting the two in the onCreate method.

salesAdapter = new SalesAdapter(this,ordersList);
        salesView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        salesView.setAdapter(salesAdapter);

Then notified the adapter on data change

               //get the Orders
                Orders orders;
                JSONArray ordersArray = jObj.getJSONArray("orders");
                    for (int i = 0; i < ordersArray.length() ; i++) {
                        JSONObject orderItem = ordersArray.getJSONObject(i);
                        //populate the Order model

                        orders = new Orders(
                                orderItem.getString("order_id"),
                                orderItem.getString("customer"),
                                orderItem.getString("date_added"),
                                orderItem.getString("total"));
                        ordersList.add(i,orders);
                        salesAdapter.notifyDataSetChanged();
                    }

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

Number of regex matches

If you always need to know the length, and you just need the content of the match rather than the other info, you might as well use re.findall. Otherwise, if you only need the length sometimes, you can use e.g.

matches = re.finditer(...)
...
matches = tuple(matches)

to store the iteration of the matches in a reusable tuple. Then just do len(matches).

Another option, if you just need to know the total count after doing whatever with the match objects, is to use

matches = enumerate(re.finditer(...))

which will return an (index, match) pair for each of the original matches. So then you can just store the first element of each tuple in some variable.

But if you need the length first of all, and you need match objects as opposed to just the strings, you should just do

matches = tuple(re.finditer(...))

setBackground vs setBackgroundDrawable (Android)

Using Android studio 1.5.1 i got the following warnings:

Call requires API level 16 (current min is 9): android.view.View#setBackground

and the complaints about deprecation

'setBackgroundDrawable(android.graphics.drawable.Drawable)' is deprecated

Using this format, i got rid of both:

    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        //noinspection deprecation
        layout.setBackgroundDrawable(drawable);
    } else {
        layout.setBackground(drawable);
    }

Make div scrollable

Place this into your DIV style

overflow:scroll;

Remove unused imports in Android Studio

Since Android Studio 3+, this can be done by open the option "Optimize imports".

Alt+Enter the select "Optimize imports".

enter image description here

This must be enough to removed the unused imports.

enter image description here

Python Tkinter clearing a frame

pack_forget and grid_forget will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy method.

To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.

Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

This can also happen when using an old version of Java that isn't capable of communicating properly with the HTTPS protocol that is now required. Version 8 and above should work as of the time writing this.

python - if not in list

Your code should work, but you can also try:

    if not item in mylist :

what is the difference between ajax and jquery and which one is better?

They aren't comparable.

Ajax (Asynchronous Javascript and XML) is a subset of javascript. Ajax is way for the client-side browser to communicate with the server (for example: retrieve data from a database) without having to perform a page refresh.

jQuery is a javascript library that standardizes the javascript differences cross-browser. jQuery includes some ajax functions.

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

If you use Java and spring MVC you just need to add the following annotation to your method returning your page :

@CrossOrigin(origins = "*")

"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.

A server with the specified hostname could not be found

Turn off the push notification. Then,Restart your XCode and Turn back ON the Push Notification. It works for me.

Where to change default pdf page width and font size in jspdf.debug.js?

For anyone trying to this in react. There is a slight difference.

// Document of 8.5 inch width and 11 inch high
new jsPDF('p', 'in', [612, 792]);

or

// Document of 8.5 inch width and 11 inch high
new jsPDF({
        orientation: 'p', 
        unit: 'in', 
        format: [612, 792]
});

When i tried the @Aidiakapi solution the pages were tiny. For a difference size take size in inches * 72 to get the dimensions you need. For example, i wanted 8.5 so 8.5 * 72 = 612. This is for [email protected].

What is the difference between a port and a socket?

In a broad sense, Socket - is just that, a socket, just like your electrical, cable or telephone socket. A point where "requisite stuff" (power, signal, information) can go out and come in from. It hides a lot of detailed stuff, which is not required for the use of the "requisite stuff". In software parlance, it provides a generic way of defining a mechanism of communication between two entities (those entities could be anything - two applications, two physically separate devices, User & Kernel space within an OS, etc)

A Port is an endpoint discriminator. It differentiates one endpoint from another. At networking level, it differentiates one application from another, so that the networking stack can pass on information to the appropriate application.

CSS: On hover show and hide different div's at the same time?

http://jsfiddle.net/MBLZx/

Here is the code

_x000D_
_x000D_
 .showme{ _x000D_
   display: none;_x000D_
 }_x000D_
 .showhim:hover .showme{_x000D_
   display : block;_x000D_
 }_x000D_
 .showhim:hover .ok{_x000D_
   display : none;_x000D_
 }
_x000D_
 <div class="showhim">_x000D_
     HOVER ME_x000D_
     <div class="showme">hai</div>_x000D_
     <div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

ReferenceError: variable is not defined

Got the error (in the function init) with the following code ;

"use strict" ;

var hdr ;

function init(){ // called on load
    hdr = document.getElementById("hdr");
}

... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

The fix for this was to change

var hdr ;

to

var hdr = null ;

Find an object in array?

You can use the index method available on Array with a predicate (see Apple's documentation here).

func index(where predicate: (Element) throws -> Bool) rethrows -> Int?

For your specific example this would be:

Swift 5.0

if let i = array.firstIndex(where: { $0.name == "Foo" }) {
    return array[i]
}

Swift 3.0

if let i = array.index(where: { $0.name == Foo }) {
    return array[i]
}

Swift 2.0

if let i = array.indexOf({ $0.name == Foo }) {
    return array[i]
}

Get all files and directories in specific path fast

I know this is old, but... Another option may be to use the FileSystemWatcher like so:

void SomeMethod()
{
    System.IO.FileSystemWatcher m_Watcher = new System.IO.FileSystemWatcher();
    m_Watcher.Path = path;
    m_Watcher.Filter = "*.*";
    m_Watcher.NotifyFilter = m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    m_Watcher.Created += new FileSystemEventHandler(OnChanged);
    m_Watcher.EnableRaisingEvents = true;
}

private void OnChanged(object sender, FileSystemEventArgs e)
    {
        string path = e.FullPath;

        lock (listLock)
        {
            pathsToUpload.Add(path);
        }
    }

This would allow you to watch the directories for file changes with an extremely lightweight process, that you could then use to store the names of the files that changed so that you could back them up at the appropriate time.

How to delete all files and folders in a folder by cmd call

One easy one-line option is to create an empty directory somewhere on your file system, and then use ROBOCOPY (http://technet.microsoft.com/en-us/library/cc733145.aspx) with the /MIR switch to remove all files and subfolders. By default, robocopy does not copy security, so the ACLs in your root folder should remain intact.

Also probably want to set a value for the retry switch, /r, because the default number of retries is 1 million.

robocopy "C:\DoNotDelete_UsedByScripts\EmptyFolder" "c:\temp\MyDirectoryToEmpty" /MIR /r:3

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

If the former actions haven't had effect, backup your server configurations, remove the server and reinclude it. It was my case.

Downloading a file from spring controllers

something like below

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void getFile(HttpServletResponse response) {
    try {
        DefaultResourceLoader loader = new DefaultResourceLoader();
        InputStream is = loader.getResource("classpath:META-INF/resources/Accepted.pdf").getInputStream();
        IOUtils.copy(is, response.getOutputStream());
        response.setHeader("Content-Disposition", "attachment; filename=Accepted.pdf");
        response.flushBuffer();
    } catch (IOException ex) {
        throw new RuntimeException("IOError writing file to output stream");
    }
}

You can display PDF or download it examples here

Numpy array dimensions

import numpy as np   
>>> np.shape(a)
(2,2)

Also works if the input is not a numpy array but a list of lists

>>> a = [[1,2],[1,2]]
>>> np.shape(a)
(2,2)

Or a tuple of tuples

>>> a = ((1,2),(1,2))
>>> np.shape(a)
(2,2)

Bootstrap Modal immediately disappearing

I had the same issue because I was toggling my modal twice as shown below:

statusCode: {
    410: function (request, status, error) { //custom error code

        document.getElementById('modalbody').innerHTML = error;
        $('#myErrorModal').modal('toggle')
    }
},
error: function (request, error) {

    document.getElementById('modalbody').innerHTML = error;
    $('#myErrorModal').modal('toggle')
}

I removed one occurrence of:

$('#myErrorModal').modal('toggle')

and it worked like magic!

Confirmation before closing of tab/browser

If you want to ask based on condition:

var ask = true
window.onbeforeunload = function (e) {
    if(!ask) return null
    e = e || window.event;
    //old browsers
    if (e) {e.returnValue = 'Sure?';}
    //safari, chrome(chrome ignores text)
    return 'Sure?';
};

How can I see which Git branches are tracking which remote / upstream branch?

In case anyone's reading this and wanting to protect master with client-side branch protection,

git branch -vv | grep "^\*" |grep -E '\* master |origin\/master'

will return 0 if either the local checked-out branch or its upstream remote branch is master.

Just put this in your .git/hooks directory's pre-commit and update files accordingly and Bob is your father's brother.

Bootstrap 3 .col-xs-offset-* doesn't work?

instead of using col-md-offset-4 use instead offset-md-4, you no longer have to use col when you're offsetting. In your case use offset-xs-1 and this will work. make sure you've called the bootstrap.css folder into your html as follows .

Get all unique values in a JavaScript array (remove duplicates)

This should have better performance than the variant with list.indexOf

function uniq(list) { return [...new Set(list)] }

Is there a max array length limit in C++?

I would agree with the above, that if you're intializing your array with

 int myArray[SIZE] 

then SIZE is limited by the size of an integer. But you can always malloc a chunk of memory and have a pointer to it, as big as you want so long as malloc doesnt return NULL.

How can I view the shared preferences file using Android Studio?

The Device File Explorer that is part of Android Studio 3.x is really good for exploring your preference file(s), cache items or database.

  1. Shared Preferences /data/data//shared_prefs directory

enter image description here

It looks something like this

enter image description here

To open The Device File Explorer:

Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool window bar.

enter image description here

Importing CSV File to Google Maps

none of that needed.... just go to:

http://www.gpsvisualizer.com/

now and load your csv file as-is. extra columns and all. it will slice and dice and use just the log & lat columns and plot it for you on google maps.

jQuery UI Alert Dialog as a replacement for alert()

I took @EkoJR's answer, and added an additional parameter to pass in with a callback function to occur when the user closes the dialog.

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: onCloseCallback
    });
}

You can then call it and pass it a function, that will occur when the user closes the dialog, as so:

jqAlert('Your payment maintenance has been saved.', 
        'Processing Complete', 
        function(){ window.location = 'search.aspx' })

Python - Get path of root project structure

I used the ../ method to fetch the current project path.

Example: Project1 -- D:\projects

src

ConfigurationFiles

Configuration.cfg

Path="../src/ConfigurationFiles/Configuration.cfg"

How to set custom location for local installation of npm package?

TL;DR

You can do this by using the --prefix flag and the --global* flag.

pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower

*Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules exists in PATH.

TL;DR

Every configurable attribute of npm can be set in any of six different places. In order of priority:

  • Command-Line Flags: --prefix ./vendor/node_modules
  • Environment Variables: NPM_CONFIG_PREFIX=./vendor/node_modules
  • User Config File: $HOME/.npmrc or userconfig param
  • Global Config File: $PREFIX/etc/npmrc or userconfig param
  • Built-In Config File: path/to/npm/itself/npmrc
  • Default Config: node_modules/npmconf/config-defs.js

By default, locally-installed packages go into ./node_modules. global ones go into the prefix config variable (/usr/local by default).

You can run npm config list to see your current config and npm config edit to change it.

PS

In general, npm's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.

Pad with leading zeros

The concept of leading zero is meaningless for an int, which is what you have. It is only meaningful, when printed out or otherwise rendered as a string.

Console.WriteLine("{0:0000000}", FileRecordCount);

Forgot to end the double quotes!

set initial viewcontroller in appdelegate - swift

Code for Swift 4.2 and 5 code:

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     self.window = UIWindow(frame: UIScreen.main.bounds)

     let storyboard = UIStoryboard(name: "Main", bundle: nil)

     let initialViewController = storyboard.instantiateViewController(withIdentifier: "dashboardVC")

     self.window?.rootViewController = initialViewController
     self.window?.makeKeyAndVisible()
}

And for Xcode 11+ and for Swift 5+ :

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

     var window: UIWindow?

     func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
         if let windowScene = scene as? UIWindowScene {
             let window = UIWindow(windowScene: windowScene)

              window.rootViewController = // Your RootViewController in here

              self.window = window
              window.makeKeyAndVisible()
         }
    }
}

Javascript add method to object

This all depends on how you're creating Foo, and how you intend to use .bar().

First, are you using a constructor-function for your object?

var myFoo = new Foo();

If so, then you can extend the Foo function's prototype property with .bar, like so:

function Foo () { /*...*/ }
Foo.prototype.bar = function () { /*...*/ };

var myFoo = new Foo();
myFoo.bar();

In this fashion, each instance of Foo now has access to the SAME instance of .bar.
To wit: .bar will have FULL access to this, but will have absolutely no access to variables within the constructor function:

function Foo () { var secret = 38; this.name = "Bob"; }
Foo.prototype.bar = function () { console.log(secret); };
Foo.prototype.otherFunc = function () { console.log(this.name); };

var myFoo = new Foo();
myFoo.otherFunc(); // "Bob";
myFoo.bar(); // error -- `secret` is undefined...
             // ...or a value of `secret` in a higher/global scope

In another way, you could define a function to return any object (not this), with .bar created as a property of that object:

function giveMeObj () {
    var private = 42,
        privateBar = function () { console.log(private); },
        public_interface = {
            bar : privateBar
        };

    return public_interface;
}

var myObj = giveMeObj();
myObj.bar(); // 42

In this fashion, you have a function which creates new objects.
Each of those objects has a .bar function created for them.
Each .bar function has access, through what is called closure, to the "private" variables within the function that returned their particular object.
Each .bar still has access to this as well, as this, when you call the function like myObj.bar(); will always refer to myObj (public_interface, in my example Foo).

The downside to this format is that if you are going to create millions of these objects, that's also millions of copies of .bar, which will eat into memory.

You could also do this inside of a constructor function, setting this.bar = function () {}; inside of the constructor -- again, upside would be closure-access to private variables in the constructor and downside would be increased memory requirements.

So the first question is:
Do you expect your methods to have access to read/modify "private" data, which can't be accessed through the object itself (through this or myObj.X)?

and the second question is: Are you making enough of these objects so that memory is going to be a big concern, if you give them each their own personal function, instead of giving them one to share?

For example, if you gave every triangle and every texture their own .draw function in a high-end 3D game, that might be overkill, and it would likely affect framerate in such a delicate system...

If, however, you're looking to create 5 scrollbars per page, and you want each one to be able to set its position and keep track of if it's being dragged, without letting every other application have access to read/set those same things, then there's really no reason to be scared that 5 extra functions are going to kill your app, assuming that it might already be 10,000 lines long (or more).

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

Dim userReply As String
userReply = Microsoft.VisualBasic.InputBox("Message")
If userReply = "" Then 
  MsgBox("You did not enter anything. Try again")
ElseIf userReply.Length = 0 Then 
  MsgBox("You did not enter anything")
End If

PHP/MySQL: How to create a comment section in your website

Create a new table called comments

They should have a column containing the id of the post they are assigned to.

Make a form which adds a new comment to that table.

An example (not tested so may contain lil' syntax errors): I call a page with comments a post

Post.php

<!-- Post content here -->

<!-- Then cmments below -->
<h1>Comments</h1>
<?php
$result = mysql_query("SELECT * FROM comments WHERE postid=0");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <?php echo $row->author; //Or similar in your table ?>
<p>
<?php echo;$row->body; ?>
</p>
</div>
<?php
}
?>
<h1>Leave a comment:</h1>
<form action="insertcomment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="hidden" name="postid" value="<?php //your posts id ?>" />
<input type="submit" />
</form>

insertcomment.php

<?php
//First check if everything is filled in
if(/*some statements*/)
{
//Do a mysql_real_escape_string() to all fields

//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>

You must change the code a bit to make it work. I'n not doing your homework. Only a part of it ;)

jQuery window scroll event does not fire up

The solution is:

 $('body').scroll(function(e){
    console.log(e);
});

Border length smaller than div width?

div{
    font-size: 25px;
    line-height: 27px;
    display:inline-block;
    width:200px;
    text-align:center;
}

div::after {
    background: #f1991b none repeat scroll 0 0;
    content: "";
    display: block;
    height: 3px;
    margin-top: 15px;
    width: 100px;
    margin:auto;
}

How to convert date into this 'yyyy-MM-dd' format in angular 2

The same problem I faced in my project. Thanks to @Umar Rashed, but I am going to explain it in detail.

First, Provide Date Pipe from app.module:

providers: [DatePipe]

Import to your component and app.module:

import { DatePipe } from '@angular/common';

Second, declare it under the constructor:

constructor(
    public datepipe: DatePipe
  ) {

Dates come from the server and parsed to console like this:

2000-09-19T00:00:00

I convert the date to how I need with this code; in TypeScript:

this.datepipe.transform(this.birthDate, 'dd/MM/yyyy')

Show from HTML template:

{{ user.birthDate }}

and it is seen like this:

19/09/2000

also seen on the web site like this: dates shown as it is filtered (click to see the screenshot)

Stopping python using ctrl+c

On Windows, the only sure way is to use CtrlBreak. Stops every python script instantly!

(Note that on some keyboards, "Break" is labeled as "Pause".)

How to stop a setTimeout loop?

As this is tagged with the extjs tag it may be worth looking at the extjs method: http://docs.sencha.com/extjs/6.2.0/classic/Ext.Function.html#method-interval

This works much like setInterval, but also takes care of the scope, and allows arguments to be passed too:

function setBgPosition() {
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
       Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length){
            c=0;
        }
    }
    return Ext.Function.interval(run,200);
}

var bgPositionTimer = setBgPosition();

when you want to stop you can use clearInterval to stop it

clearInterval(bgPositionTimer);

An example use case would be:

Ext.Ajax.request({
    url: 'example.json',

    success: function(response, opts) {
        clearInterval(bgPositionTimer);
    },

    failure: function(response, opts) {
        console.log('server-side failure with status code ' + response.status);
        clearInterval(bgPositionTimer);
    }
});

Percentage calculation

You can hold onto the percentage as decimal (value \ total) and then when you want to render to a human you can make use of Habeeb's answer or using string interpolation you could have something even cleaner:

var displayPercentage = $"{(decimal)value / total:P}";

or

//Calculate percentage earlier in code
decimal percentage = (decimal)value / total;
...
//Now render percentage
var displayPercentage = $"{percentage:P}";

Why write <script type="text/javascript"> when the mime type is set by the server?

Douglas Crockford says:

type="text/javascript"

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

He also says:

W3C did not adopt the language attribute, favoring instead a type attribute which takes a MIME type. Unfortunately, the MIME type was not standardized, so it is sometimes "text/javascript" or "application/ecmascript" or something else. Fortunately, all browsers will always choose JavaScript as the default programming language, so it is always best to simply write <script>. It is smallest, and it works on the most browsers.

For entertainment purposes only, I tried out the following five scripts

  <script type="application/ecmascript">alert("1");</script>
  <script type="text/javascript">alert("2");</script>
  <script type="baloney">alert("3");</script>
  <script type="">alert("4");</script>
  <script >alert("5");</script>

On Chrome, all but script 3 (type="baloney") worked. IE8 did not run script 1 (type="application/ecmascript") or script 3. Based on my non-extensive sample of two browsers, it looks like you can safely ignore the type attribute, but that it you use it you better use a legal (browser dependent) value.

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

Shared hosting no ssh or shell access?

Here is how i did it;

  1. Visit https://wkhtmltopdf.org/downloads.html and download the appropriate stable release for Linux. For my case I chose 32-bit which is wkhtmltox-0.12.4_linux-generic-i386.tar.xz
  2. Unzip to a folder on your local drive.
  3. Upload the folder to public_html (or whichever location fits your need) using an FTP program just like any other file(s)
  4. Change the binary paths in snappy.php file to point the appropriate files in the folder you just uploaded. Bingo! there you have it. You should be able to generate PDF files.

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

My solution was rather simple: backup everything from the application, uninstall it, delete everything from the remaining folders (but not the folders so I won't have to grant the same permissions again) then copy back the files from the backup.

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

Try to update the package.json file so that "@angular-devkit/build-angular": "^0.800.1" reads "@angular-devkit/build-angular": "^0.12.4"

Then run npm install in the command line.

Reference: https://stackoverflow.com/a/56537342

Query to list all users of a certain group

For Active Directory users, an alternative way to do this would be -- assuming all your groups are stored in OU=Groups,DC=CorpDir,DC=QA,DC=CorpName -- to use the query (&(objectCategory=group)(CN=GroupCN)). This will work well for all groups with less than 1500 members. If you want to list all members of a large AD group, the same query will work, but you'll have to use ranged retrieval to fetch all the members, 1500 records at a time.

The key to performing ranged retrievals is to specify the range in the attributes using this syntax: attribute;range=low-high. So to fetch all members of an AD Group with 3000 members, first run the above query asking for the member;range=0-1499 attribute to be returned, then for the member;range=1500-2999 attribute.

Why not inherit from List<T>?

I just wanted to add that Bertrand Meyer, the inventor of Eiffel and design by contract, would have Team inherit from List<Player> without so much as batting an eyelid.

In his book, Object-Oriented Software Construction, he discusses the implementation of a GUI system where rectangular windows can have child windows. He simply has Window inherit from both Rectangle and Tree<Window> to reuse the implementation.

However, C# is not Eiffel. The latter supports multiple inheritance and renaming of features. In C#, when you subclass, you inherit both the interface and the implemenation. You can override the implementation, but the calling conventions are copied directly from the superclass. In Eiffel, however, you can modify the names of the public methods, so you can rename Add and Remove to Hire and Fire in your Team. If an instance of Team is upcast back to List<Player>, the caller will use Add and Remove to modify it, but your virtual methods Hire and Fire will be called.

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

Meaning of "n:m" and "1:n" in database design

In a relational database all types of relationships are represented in the same way: as relations. The candidate key(s) of each relation (and possibly other constraints as well) determine what kind of relationship is being represented. 1:n and m:n are two kinds of binary relationship:

C {Employee*,Company}
B {Book*,Author*}

In each case * designates the key attribute(s). {Book,Author} is a compound key.

C is a relation where each employee works for only one company but each company may have many employees (1:n): B is a relation where a book can have many authors and an author may write many books (m:n):

Notice that the key constraints ensure that each employee can only be associated with one company whereas any combination of books and authors is permitted.

Other kinds of relationship are possible as well: n-ary (having more than two components); fixed cardinality (m:n where m and n are fixed constants or ranges); directional; and so on. William Kent in his book "Data and Reality" identifies at least 432 kinds - and that's just for binary relationships. In practice, the binary relationships 1:n and m:n are very common and are usually singled out as specially important in designing and understanding data models.

How to confirm RedHat Enterprise Linux version?

Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:

rpm -qia '*release*'

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

Convert iterator to pointer?

here it is, obtaining a reference to the coresponding pointer of an iterator use :

example:

string my_str= "hello world";

string::iterator it(my_str.begin());

char* pointer_inside_buffer=&(*it); //<--

[notice operator * returns a reference so doing & on a reference will give you the address].

MongoDB - admin user not authorized

I had a similar problem here on a Windows environment: I have installed Bitnami DreamFactory and it also installs another MongoDb that is started on system boot. I was running my MongoDbService (that was started without any error) but I noticed after losing a lot of time that I was in fact connecting on Bitnami's MongoDb Service. Please, take a look if there is not another instance of mongoDB running on your server.

Good Luck!

Write HTML file using Java

If you are willing to use Groovy, the MarkupBuilder is very convenient for this sort of thing, but I don't know that Java has anything like it.

http://groovy.codehaus.org/Creating+XML+using+Groovy's+MarkupBuilder

Get encoding of a file in Windows

Here's my take how to detect the Unicode family of text encodings via BOM. The accuracy of this method is low, as this method only works on text files (specifically Unicode files), and defaults to ascii when no BOM is present (like most text editors, the default would be UTF8 if you want to match the HTTP/web ecosystem).

Update 2018: I no longer recommend this method. I recommend using file.exe from GIT or *nix tools as recommended by @Sybren, and I show how to do that via PowerShell in a later answer.

# from https://gist.github.com/zommarin/1480974
function Get-FileEncoding($Path) {
    $bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4)

    if(!$bytes) { return 'utf8' }

    switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) {
        '^efbbbf'   { return 'utf8' }
        '^2b2f76'   { return 'utf7' }
        '^fffe'     { return 'unicode' }
        '^feff'     { return 'bigendianunicode' }
        '^0000feff' { return 'utf32' }
        default     { return 'ascii' }
    }
}

dir ~\Documents\WindowsPowershell -File | 
    select Name,@{Name='Encoding';Expression={Get-FileEncoding $_.FullName}} | 
    ft -AutoSize

Recommendation: This can work reasonably well if the dir, ls, or Get-ChildItem only checks known text files, and when you're only looking for "bad encodings" from a known list of tools. (i.e. SQL Management Studio defaults to UTF16, which broke GIT auto-cr-lf for Windows, which was the default for many years.)

Display Images Inline via CSS

You have a line break <br> in-between the second and third images in your markup. Get rid of that, and it'll show inline.

npm install hangs

This method is working for me when npm blocks in installation Package for IONIC installation and ReactNative and another package npm.

You can change temporary:

npm config set prefix C:\Users\[username]\AppData\Roaming\npm\node_modules2

  • Change the path in environment variables. Set:

    C:\Users[username]\AppData\Roaming\npm\node_modules2

  • Run the command to install your package.

  • Open file explorer, copy the link:

    C:\Users[username]\AppData\Roaming\npm\node_modules

    ok file yourpackage.CMD created another folder Created "node_modules2" in node_modules and contain your package folder.

  • Copy your package file CMD to parent folder "npm".

  • Copy your package folder to parent folder "node_modules".

  • Now run:

    npm config set prefix C:\Users\[username]\AppData\Roaming\npm

  • Change the path in environment variables. Set:

    C:\Users[username]\AppData\Roaming\npm

Now the package is working correctly with the command line.

Create an ArrayList with multiple object types?

You can always create an ArrayList of Objects. But it will not be very useful to you. Suppose you have created the Arraylist like this:

List<Object> myList = new ArrayList<Object>();

and add objects to this list like this:

myList.add(new Integer("5"));

myList.add("object");

myList.add(new Object());

You won't face any problem while adding and retrieving the object but it won't be very useful. You have to remember at what location each type of object is it in order to use it. In this case after retrieving, all you can do is calling the methods of Object on them.

How to navigate through textfields (Next / Done Buttons)

A safer and more direct way, assuming:

  • the text field delegates are set to your view controller
  • all of the text fields are subviews of the same view
  • the text fields have tags in the order you want to progress (e.g., textField2.tag = 2, textField3.tag = 3, etc.)
  • moving to the next text field will happen when you tap the return button on the keyboard (you can change this to next, done, etc.)
  • you want the keyboard to dismiss after the last text field

Swift 4.1:

extension ViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let nextTag = textField.tag + 1
        guard let nextTextField = textField.superview?.viewWithTag(nextTag) else {
            textField.resignFirstResponder()
            return false
        }

    nextTextField.becomeFirstResponder()

    return false

    }
}

Adding a JAR to an Eclipse Java library

As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.

jQuery callback on image load (even when the image is cached)

Do you really have to do it with jQuery? You can attach the onload event directly to your image as well;

<img src="/path/to/image.jpg" onload="doStuff(this);" />

It will fire every time the image has loaded, from cache or not.

Error to run Android Studio

The error is self explanatory, you need to set your environment variable to JDK path instead of JRE here is it

JDK_HOME: C:\Program Files\Java\jdk1.7.0_07

check the path for linux

and here is possible duplicate Android Studio not working

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

I addition to the accepted answer, the error can also occur when the destination folder is read-only (Common when using TFS)

How do I export a project in the Android studio?

Follow the below steps to sign the application in the android studio:-

  1. First Go to Build->Generate Signed APK

    First screenshot

  2. Then Once you click on the Generate Signed APK then there is info dialog message appear.

    Second screenshot

  3. Click on the Create New button if you don't have any keystore file. If you have click on the Choose Existing.

    This screenshot

  4. Once you click on the Create New button then now dialog box appear where you need to enter the keystore file info, other signing authority details.

    Fourth screenshot

  5. Once you fill complete details then click on the Ok button then it redirect to this dialog.

    Fifth screenshot

  6. Click on the Next button then check mark on the Run ProGuard and click on the finish. It generate the signed APK.

    Sixth screenshot

    Seventh screenshot

Button background as transparent

Selectors work only for drawables, not styles. Reference


First, to make the button background transparent use the following attribute as this will not affect the material design animations:

style="?attr/buttonBarButtonStyle"

There are many ways to style your button. Check out this tutorial.

Second, to make the text bold on pressed, use this java code:

btn.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            // When the user clicks the Button
            case MotionEvent.ACTION_DOWN:
                btn.setTypeface(Typeface.DEFAULT_BOLD);
                break;

            // When the user releases the Button
            case MotionEvent.ACTION_UP:
                btn.setTypeface(Typeface.DEFAULT);
                break;
        }
        return false;
    }
});

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

toBe(true) vs toBeTruthy() vs toBeTrue()

There are a lot many good answers out there, i just wanted to add a scenario where the usage of these expectations might be helpful. Using element.all(xxx), if i need to check if all elements are displayed at a single run, i can perform -

expect(element.all(xxx).isDisplayed()).toBeTruthy(); //Expectation passes
expect(element.all(xxx).isDisplayed()).toBe(true); //Expectation fails
expect(element.all(xxx).isDisplayed()).toBeTrue(); //Expectation fails

Reason being .all() returns an array of values and so all kinds of expectations(getText, isPresent, etc...) can be performed with toBeTruthy() when .all() comes into picture. Hope this helps.

Jquery mouseenter() vs mouseover()

Old question, but still no good up-to-date answer with insight imo.

As jQuery uses Javascript wording for events and handlers, but does its own undocumented, but different interpretation of those, let me first shed light on the difference from the pure Javascript viewpoint:

  • both event pairs
    • the mouse can “jump” from outside/outer elements to inner/innermost elements when moved faster than the browser samples its position
    • any enter/over gets a corresponding leave/out (possibly late/jumpy)
    • events go to the visible element below the pointer (invisible elements can’t be target)
  • mouseenter/mouseleave
    • does not bubble (event not useful for delegate handlers)
    • the event registration itself defines the area of observation and abstraction
    • works on the target area, like a park with a pond: the pond is considered part of the park
    • the event is emitted on the target/area whenever the element itself or any descendant directly is entered/left the first time
    • entering a descendant, moving from one descendant to another or moving back into the target does not finish/restart the mouseenter/mouseleave cycle (i.e. no events fire)
    • if you want to observe multiple areas with one handler, register it on each area/element or use the other event pair discussed next
    • descendants of registered areas/elements can have their own handlers, creating an independent observation area with its independent mouseenter/mouseleave event cycles
    • if you think about how a bubbling version of mouseenter/mouseleave could look like, you end up with with something like mouseover/mouseout
  • mouseover/mouseout
    • events bubble
    • events fire whenever the element below the pointer changes
      • mouseout on the previously sampled element
      • followed by mouseover on the new element
      • the events don’t “nest”: before e.g. a child is “overed” the parent will be “out”
    • target/relatedTarget indicate new and previous element
    • if you want to watch different areas
      • register one handler on a common parent (or multiple parents, which together cover all elements you want to watch)
      • look for the element you are interested in between the handler element and the target element; maybe $(event.target).closest(...) suits your needs

Not-so-trivial mouseover/mouseout example:

$('.side-menu, .top-widget')
  .on('mouseover mouseout', event => {
    const target = event.type === 'mouseover' ? event.target : event.relatedTarget;
    const thing = $(target).closest('[data-thing]').attr('data-thing') || 'default';
    // do something with `thing`
  });

These days, all browsers support mouseover/mouseout and mouseenter/mouseleave natively. Nevertheless, jQuery does not register your handler to mouseenter/mouseleave, but silently puts them on a wrappers around mouseover/mouseout as the code below exposes.

The emulation is unnecessary, imperfect and a waste of CPU cycles: it filters out mouseover/mouseout events that a mouseenter/mouseleave would not get, but the target is messed. The real mouseenter/mouseleave would give the handler element as target, the emulation might indicate children of that element, i.e. whatever the mouseover/mouseout carried.

For that reason I do not use jQuery for those events, but e.g.:

$el[0].addEventListener('mouseover', e => ...);

_x000D_
_x000D_
const list = document.getElementById('log');
const outer = document.getElementById('outer');
const $outer = $(outer);

function log(tag, event) {
  const li = list.insertBefore(document.createElement('li'), list.firstChild);
  // only jQuery handlers have originalEvent
  const e = event.originalEvent || event;
  li.append(`${tag} got ${e.type} on ${e.target.id}`);
}

outer.addEventListener('mouseenter', log.bind(null, 'JSmouseenter'));
$outer.on('mouseenter', log.bind(null, '$mouseenter'));
_x000D_
div {
  margin: 20px;
  border: solid black 2px;
}

#inner {
  min-height: 80px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div id=outer>
    <ul id=log>
    </ul>
  </div>
</body>
_x000D_
_x000D_
_x000D_


Note: For delegate handlers never use jQuery’s “delegate handlers with selector registration”. (Reason in another answer.) Use this (or similar):

$(parent).on("mouseover", e => {
  if ($(e.target).closest('.gold').length) {...};
});

instead of

$(parent).on("mouseover", '.gold', e => {...});

Convert a String In C++ To Upper Case

If you only want to capitalize, try this function.

#include <iostream>


using namespace std;

string upper(string text){
    string upperCase;
    for(int it : text){
        if(it>96&&it<123){
            upperCase += char(it-32);
        }else{
            upperCase += char(it);
        }
    }
    return upperCase;
}

int main() {
    string text = "^_abcdfghopqrvmwxyz{|}";
    cout<<text<<"/";
    text = upper(text);
    cout<<text;
    return 0;
}

Error: Range-based 'for' loops are not allowed in C++98 mode

recursion versus iteration

I seem to remember my computer science professor say back in the day that all problems that have recursive solutions also have iterative solutions. He says that a recursive solution is usually slower, but they are frequently used when they are easier to reason about and code than iterative solutions.

However, in the case of more advanced recursive solutions, I don't believe that it will always be able to implement them using a simple for loop.

Count the number of occurrences of a string in a VARCHAR field?

This should do the trick:

SELECT 
    title,
    description,    
    ROUND (   
        (
            LENGTH(description)
            - LENGTH( REPLACE ( description, "value", "") ) 
        ) / LENGTH("value")        
    ) AS count    
FROM <table> 

C# winforms combobox dynamic autocomplete

Here is my final solution. It works fine with a large amount of data. I use Timer to make sure the user want find current value. It looks like complex but it doesn't. Thanks to Max Lambertini for the idea.

        private bool _canUpdate = true; 

        private bool _needUpdate = false;       

        //If text has been changed then start timer
        //If the user doesn't change text while the timer runs then start search
        private void combobox1_TextChanged(object sender, EventArgs e)
        {
            if (_needUpdate)
            {
                if (_canUpdate)
                {
                    _canUpdate = false;
                    UpdateData();                   
                }
                else
                {
                    RestartTimer();
                }
            }
        }

        private void UpdateData()
        {
            if (combobox1.Text.Length > 1)
            {
                List<string> searchData = Search.GetData(combobox1.Text);
                HandleTextChanged(searchData);
            }
        }       

        //If an item was selected don't start new search
        private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            _needUpdate = false;
        }

        //Update data only when the user (not program) change something
        private void combobox1_TextUpdate(object sender, EventArgs e)
        {
            _needUpdate = true;
        }

        //While timer is running don't start search
        //timer1.Interval = 1500;
        private void RestartTimer()
        {
            timer1.Stop();
            _canUpdate = false;
            timer1.Start();
        }

        //Update data when timer stops
        private void timer1_Tick(object sender, EventArgs e)
        {
            _canUpdate = true;
            timer1.Stop();
            UpdateData();
        }

        //Update combobox with new data
        private void HandleTextChanged(List<string> dataSource)
        {
            var text = combobox1.Text;

            if (dataSource.Count() > 0)
            {
                combobox1.DataSource = dataSource;  

                var sText = combobox1.Items[0].ToString();
                combobox1.SelectionStart = text.Length;
                combobox1.SelectionLength = sText.Length - text.Length;
                combobox1.DroppedDown = true;


                return;
            }
            else
            {
                combobox1.DroppedDown = false;
                combobox1.SelectionStart = text.Length;
            }
        }

This solution isn't very cool. So if someone has another solution please share it with me.

MySQL - Make an existing Field Unique

The easiest and fastest way would be with phpmyadmin structure table.

USE PHPMYADMIN ADMIN PANEL!

There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.

Splitting comma separated string in a PL/SQL stored proc

This should do what you are looking for.. It assumes your list will always be just numbers. If that is not the case, just change the references to DBMS_SQL.NUMBER_TABLE to a table type that works for all of your data:

CREATE OR REPLACE PROCEDURE insert_from_lists(
    list1_in IN VARCHAR2,
    list2_in IN VARCHAR2,
    delimiter_in IN VARCHAR2 := ','
)
IS 
    v_tbl1 DBMS_SQL.NUMBER_TABLE;
    v_tbl2 DBMS_SQL.NUMBER_TABLE;

    FUNCTION list_to_tbl
    (
        list_in IN VARCHAR2
    )
    RETURN DBMS_SQL.NUMBER_TABLE
    IS
        v_retval DBMS_SQL.NUMBER_TABLE;
    BEGIN

        IF list_in is not null
        THEN
            /*
            || Use lengths loop through the list the correct amount of times,
            || and substr to get only the correct item for that row
            */
            FOR i in 1 .. length(list_in)-length(replace(list_in,delimiter_in,''))+1
            LOOP
                /*
                || Set the row = next item in the list
                */
                v_retval(i) := 
                        substr (
                            delimiter_in||list_in||delimiter_in,
                            instr(delimiter_in||list_in||delimiter_in, delimiter_in, 1, i  ) + 1,
                            instr (delimiter_in||list_in||delimiter_in, delimiter_in, 1, i+1) - instr (delimiter_in||list_in||delimiter_in, delimiter_in, 1, i) -1
                        );
            END LOOP;
        END IF;

        RETURN v_retval;

    END list_to_tbl;
BEGIN 
   -- Put lists into collections
   v_tbl1 := list_to_tbl(list1_in);
   v_tbl2 := list_to_tbl(list2_in);

   IF v_tbl1.COUNT <> v_tbl2.COUNT
   THEN
      raise_application_error(num => -20001, msg => 'Length of lists do not match');
   END IF;

   -- Bulk insert from collections
   FORALL i IN INDICES OF v_tbl1
      insert into tmp (a, b)
      values (v_tbl1(i), v_tbl2(i));

END insert_from_lists; 

How to pass the password to su/sudo/ssh without overriding the TTY?

One way would be to use read -s option .. this way the password characters are not echoed back to the screen. I wrote a small script for some use cases and you can see it in my blog: http://www.datauniv.com/blogs/2013/02/21/a-quick-little-expect-script/

Deserialize JSON with C#

Sometimes I prefer dynamic objects:

public JsonResult GetJson()
{
  string res;
  WebClient client = new WebClient();

  // Download string
  string value = client.DownloadString("https://api.instagram.com/v1/users/000000000/media/recent/?client_id=clientId");

  // Write values
  res = value;
  dynamic dyn = JsonConvert.DeserializeObject(res);
  var lstInstagramObjects = new List<InstagramModel>();

  foreach(var obj in dyn.data)
  {
    lstInstagramObjects.Add(new InstagramModel()
    {
      Link = (obj.link != null) ? obj.link.ToString() : "",
      VideoUrl = (obj.videos != null) ? obj.videos.standard_resolution.url.ToString() : "",
      CommentsCount = int.Parse(obj.comments.count.ToString()),
      LikesCount = int.Parse(obj.likes.count.ToString()),
      CreatedTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((double.Parse(obj.created_time.ToString()))),
      ImageUrl = (obj.images != null) ? obj.images.standard_resolution.url.ToString() : "",
      User = new InstagramModel.UserAccount()
             {
               username = obj.user.username,
               website = obj.user.website,
               profile_picture = obj.user.profile_picture,
               full_name = obj.user.full_name,
               bio = obj.user.bio,
               id = obj.user.id
             }
    });
  }

  return Json(lstInstagramObjects, JsonRequestBehavior.AllowGet);
}

How to upgrade PowerShell version from 2.0 to 3.0

As of today, Windows PowerShell 5.1 is the latest version. It can be installed as part of Windows Management Framework 5.1. It was released in January 2017.

Quoting from the official Microsoft download page here.

Some of the new and updated features in this release include:

  • Constrained file copying to/from JEA endpoints
  • JEA support for Group Managed Service Accounts and Conditional Access Policies
  • PowerShell console support for VT100 and redirecting stdin with interactive input
  • Support for catalog signed modules in PowerShell Get
  • Specifying which module version to load in a script
  • Package Management cmdlet support for proxy servers
  • PowerShellGet cmdlet support for proxy servers
  • Improvements in PowerShell Script Debugging
  • Improvements in Desired State Configuration (DSC)
  • Improved PowerShell usage auditing using Transcription and Logging
  • New and updated cmdlets based on community feedback

nodejs vs node on ubuntu 12.04

Will be helpful for absolute beginners

Although, you have got the answer, just wanted to point out that the node command (without any parameters) will start node in REPL read-eval-print-loop mode to execute raw javascript code.

Another way to use node command is by providing it a js file as a parameter. This is how we mostly use it.

Fatal error: Call to a member function prepare() on null

In ---- model: Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

Change the class ----- extends Model to class ----- extends Eloquent

An "and" operator for an "if" statement in Bash

Quote:

The "-a" operator also doesn't work:

if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]

For a more elaborate explanation: [ and ] are not Bash reserved words. The if keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0 or false otherwise).

For trivial tests, there is the test program (man test).

As some find lines like if test -f filename; then foo bar; fi, etc. annoying, on most systems you find a program called [ which is in fact only a symlink to the test program. When test is called as [, you have to add ] as the last positional argument.

So if test -f filename is basically the same (in terms of processes spawned) as if [ -f filename ]. In both cases the test program will be started, and both processes should behave identically.

Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]] will parse to if + some job, the job being everything except the if itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([) is the command and the rest its positional arguments. There are remaining arguments after the first ].

Also not, [[ is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.

What is the preferred syntax for defining enums in JavaScript?

This answer is an alternative approach for specific circumstances. I needed a set of bitmask constants based on attribute sub-values (cases where an attribute value is an array or list of values). It encompasses the equivalent of several overlapping enums.

I created a class to both store and generate the bitmask values. I can then use the pseudo-constant bitmask values this way to test, for example, if green is present in an RGB value:

if (value & Ez.G) {...}

In my code I create only one instance of this class. There doesn't seem to be a clean way to do this without instantiating at least one instance of the class. Here is the class declaration and bitmask value generation code:

class Ez {
constructor() {
    let rgba = ["R", "G", "B", "A"];
    let rgbm = rgba.slice();
    rgbm.push("M");              // for feColorMatrix values attribute
    this.createValues(rgba);
    this.createValues(["H", "S", "L"]);
    this.createValues([rgba, rgbm]);
    this.createValues([attX, attY, attW, attH]);
}
createValues(a) {                // a for array
    let i, j;
    if (isA(a[0])) {             // max 2 dimensions
        let k = 1;
        for (i of a[0]) {
            for (j of a[1]) {
                this[i + j] = k;
                k *= 2;
            }
        }
    }
    else {                       // 1D array is simple loop
        for (i = 0, j = 1; i < a.length; i++, j *= 2)
            this[a[i]] = j;
   }
}

The 2D array is for the SVG feColorMatrix values attribute, which is a 4x5 matrix of RGBA by RGBAM, where M is a multiplier. The resulting Ez properties are Ez.RR, Ez.RG, etc.

How to enable file upload on React's Material UI simple input?

Nov 2020

With Material-UI and React Hooks

import * as React from "react";
import {
  Button,
  IconButton,
  Tooltip,
  makeStyles,
  Theme,
} from "@material-ui/core";
import { PhotoCamera } from "@material-ui/icons";

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
    },
  },
  input: {
    display: "none",
  },
  faceImage: {
    color: theme.palette.primary.light,
  },
}));

interface FormProps {
  saveFace: any; //(fileName:Blob) => Promise<void>, // callback taking a string and then dispatching a store actions
}

export const FaceForm: React.FunctionComponent<FormProps> = ({ saveFace }) => {

  const classes = useStyles();
  const [selectedFile, setSelectedFile] = React.useState(null);

  const handleCapture = ({ target }: any) => {
    setSelectedFile(target.files[0]);
  };

  const handleSubmit = () => {
    saveFace(selectedFile);
  };

  return (
    <>
      <input
        accept="image/jpeg"
        className={classes.input}
        id="faceImage"
        type="file"
        onChange={handleCapture}
      />
      <Tooltip title="Select Image">
        <label htmlFor="faceImage">
          <IconButton
            className={classes.faceImage}
            color="primary"
            aria-label="upload picture"
            component="span"
          >
            <PhotoCamera fontSize="large" />
          </IconButton>
        </label>
      </Tooltip>
      <label>{selectedFile ? selectedFile.name : "Select Image"}</label>. . .
      <Button onClick={() => handleSubmit()} color="primary">
        Save
      </Button>
    </>
  );
};

How do I round a double to two decimal places in Java?

You can try this one:

public static String getRoundedValue(Double value, String format) {
    DecimalFormat df;
    if(format == null)
        df = new DecimalFormat("#.00");
    else 
        df = new DecimalFormat(format);
    return df.format(value);
}

or

public static double roundDoubleValue(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

How to update npm

Tried the options above on Ubuntu 14.04, but they would constantly produce this error:

npm ERR! tar pack Error reading /root/tmp/npm-15864/1465947804069-0.4854120113886893/package

Then found this solution online:

1) Clean the cache of npm first:

sudo npm cache clean -f

2) Install n module of npm:

sudo npm install -g n

3) Begin the installation by selecting the version of node to install: stable or latest, we will use stable here:

sudo n stable

4) Check the version of node:

node -v

5) Check the version of npm:

npm -v

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

This should work...tested on a mac...

#include <stdio.h>
#include <sys/time.h>

int main() {
        struct timeval tv;
        struct timezone tz;
        struct tm *tm;
        gettimeofday(&tv,&tz);
        tm=localtime(&tv.tv_sec);
        printf("StartTime: %d:%02d:%02d %d \n", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec);
}

Yeah...run it twice and subtract...

What's the difference between :: (double colon) and -> (arrow) in PHP?

The difference between static and instantiated methods and properties seem to be one of the biggest obstacles to those just starting out with OOP PHP in PHP 5.

The double colon operator (which is called the Paamayim Nekudotayim from Hebrew - trivia) is used when calling an object or property from a static context. This means an instance of the object has not been created yet.

The arrow operator, conversely, calls methods or properties that from a reference of an instance of the object.

Static methods can be especially useful in object models that are linked to a database for create and delete methods, since you can set the return value to the inserted table id and then use the constructor to instantiate the object by the row id.

Difference between Java SE/EE/ME?

I guess Java SE (Standard Edition) is the one I should install on my Windows 7 desktop

Yes, of course. Java SE is the best one to start with. BTW you must learn Java basics. That means you must learn some of the libraries and APIs in Java SE.

Difference between Java Platform Editions:

Java Micro Edition (Java ME):

  • Highly optimized runtime environment.
  • Target consumer products (Pagers, cell phones).
  • Java ME was formerly known as Java 2 Platform, Micro Edition or J2ME.

Java Standard Edition (Java SE):

Java tools, runtimes, and APIs for developers writing, deploying, and running applets and applications. Java SE was formerly known as Java 2 Platform, Standard Edition or J2SE. (everyone/beginners starting from this)

Java Enterprise Edition(Java EE):

Targets enterprise-class server-side applications. Java EE was formerly known as Java 2 Platform, Enterprise Edition or J2EE.

Another duplicated question for this question.


Lastly, about J.. confusion

JVM (Java Virtual Machine):

JVM is a part of both the JDK and JRE that translates Java byte codes and executes them as native code on the client machine.

JRE (Java Runtime Environment):

It is the environment provided for the java programs to get executed. It contains a JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger and so on.

JDK (Java Development Kit):

JDK contains tools needed to develop the java programs (javac, java, javadoc, appletviewer, jdb, javap, rmic,...) and JRE to run the program.

Java SDK (Java Software Development Kit):

SDK comprises a JDK and extra software, such as application servers, debuggers, and documentation.

Java SE:

Java platform, Standard Edition (Java SE) lets you develop and deploy Java applications on desktops and servers (same as SDK).

J2SE, J2ME, J2EE

Any Java edition from 1.2 to 1.5

Read more about these topics:

How to implement band-pass Butterworth filter with Scipy.signal.butter

For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.

wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.

gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.

Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.

Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.

To create your filter, you'd call buttord as

fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
   gpass=0.0, gstop=30.0)

The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.

Spring Boot Program cannot find main class

Have a look under "Run -> Run Configurations..." in Eclipse. You should delete the new one which you created by mistake, you should still have the existing one.

I suspect it has created a new run configuration for the "Run as Maven Test" and you are now always starting this one.