Programs & Examples On #Motion detection

Related to detection of motion related to programming issues, like computer vision, sensor control, etc.

How do I detect when someone shakes an iPhone?

In 3.0, there's now an easier way - hook into the new motion events.

The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events:

@implementation ShakingView

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if ( event.subtype == UIEventSubtypeMotionShake )
    {
        // Put in code here to handle shake
    }

    if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
        [super motionEnded:motion withEvent:event];
}

- (BOOL)canBecomeFirstResponder
{ return YES; }

@end

You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view).

In the view controller, you want to set this view to become first responder:

- (void) viewWillAppear:(BOOL)animated
{
    [shakeView becomeFirstResponder];
    [super viewWillAppear:animated];
}
- (void) viewWillDisappear:(BOOL)animated
{
    [shakeView resignFirstResponder];
    [super viewWillDisappear:animated];
}

Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns!

This method works even if you set applicationSupportsShakeToEdit to NO.

Synchronous Requests in Node.js

You should take a look at library called async

and try to use async.series call for your problem.

Select SQL Server database size

SELECT
    DB_NAME (database_id) as [Database Name],
    name as [Database File Name],
    [Type] = CASE WHEN Type_Desc = 'ROWS' THEN 'Data File(s)'
            WHEN Type_Desc = 'LOG'  THEN 'Log File(s)'
            ELSE Type_Desc END,
    size*8/1024 as 'Size (MB)',
    physical_name as [Database_File_Location]
FROM sys.master_files
ORDER BY 1,3

Output

Database Name               Database File Name              Type                Size (MB)   Database_File_Location
--------------------------- ------------------------------- ------------------- ----------- ---------------------------------------------------------------
AdventureWorksDW2017        AdventureWorksDW2017            Data File(s)        136         E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2017.mdf
AdventureWorksDW2017        AdventureWorksDW2017_log        Log File(s)         72          E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2017_log.ldf
DBA_Admin                   DBA_Admin                       Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\DBA_Admin.mdf
DBA_Admin                   DBA_Admin_log                   Log File(s)         8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\DBA_Admin_log.ldf
EventNotifications          EventNotifications              Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\EventNotifications.mdf
EventNotifications          EventNotifications_log          Log File(s)         8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\EventNotifications_log.ldf
master                      master                          Data File(s)        4           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\master.mdf
master                      mastlog                         Log File(s)         2           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
model                       modeldev                        Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\model.mdf
model                       modellog                        Log File(s)         8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\modellog.ldf
msdb                        MSDBData                        Data File(s)        19          E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\MSDBData.mdf
msdb                        MSDBLog                         Log File(s)         13          E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf
tempdb                      temp2                           Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_2.ndf
tempdb                      temp3                           Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_3.ndf
tempdb                      temp4                           Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_4.ndf
tempdb                      tempdev                         Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb.mdf
tempdb                      templog                         Log File(s)         8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\templog.ldf

How can I create a border around an Android LinearLayout?

Don't want to create a drawable resource?

  <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/black"
    android:minHeight="128dp">

    <FrameLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_margin="1dp"
      android:background="@android:color/white">

      <TextView ... />
    </FrameLayout>
  </FrameLayout>

Sending multipart/formdata with jQuery.ajax

All the solutions above are looks good and elegant, but the FormData() object does not expect any parameter, but use append() after instantiate it, like what one wrote above:

formData.append(val.name, val.value);

Python != operation vs "is not"

== is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their __eq__ or __cmp__ methods.)

is is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the is operation.

You use is (and is not) for singletons, like None, where you don't care about objects that might want to pretend to be None or where you want to protect against objects breaking when being compared against None.

How can I add a username and password to Jenkins?

  • Try deleting the .jenkins folder from your system which is located ate the below path. C:\Users\"Your PC Name".jenkins

  • Now download a fresh and a stable version of .war file from official website of jenkins. For eg. 2.1 and follow the steps to install.

    • You will be able to do via this method

How to pass variable from jade template file to a script file?

If you're like me and you use this method of passing variables a lot, here's a write-less-code solution.

In your node.js route, pass the variables in an object called window, like this:

router.get('/', function (req, res, next) {
    res.render('index', {
        window: {
            instance: instance
        }
    });
});

Then in your pug/jade layout file (just before the block content), you get them out like this:

if window
    each object, key in window
        script.
            window.!{key} = !{JSON.stringify(object)};

As my layout.pug file gets loaded with each pug file, I don't need to 'import' my variables over and over.

This way all variables/objects passed to window 'magically' end up in the real window object of your browser where you can use them in Reactjs, Angular, ... or vanilla javascript.

How to change legend size with matplotlib.pyplot

Now in 2020, with matplotlib 3.2.2 you can set your legend fonts with

plt.legend(title="My Title", fontsize=10, title_fontsize=15)

where fontsize is the font size of the items in legend and title_fontsize is the font size of the legend title. More information in matplotlib documentation

Is there a real solution to debug cordova apps

The best for me is to attach the Chrome debugger.

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

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

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

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

How do I get length of list of lists in Java?

Java 8

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class HelloWorld{

     public static void main(String []args){
            List<List<String>> stringListList = new ArrayList<>();
            stringListList.add(Arrays.asList(new String[] {"(0,0)", "(0,1)"} ));
            stringListList.add(Arrays.asList(new String[] {"(1,0)", "(1,1)", "(1,2)"} ));
            stringListList.add(Arrays.asList(new String[] {"(2,0)", "(2,1)"} ));

            int count=stringListList.stream().mapToInt(i -> i.size()).sum();

            System.out.println("stringListList count: "+count);
     }
}

How to Insert Double or Single Quotes

Why not just use a custom format for the cell you need to quote?

If you set a custom format to the cell column, all values will take on that format.

For numbers....like a zip code....it would be this '#' For string text, it would be this '@'

You save the file as csv format, and it will have all the quotes wrapped around the cell data as needed.

Blur effect on a div element

I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/

 div {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  width: 100px;
  height: 100px;
  background-color: #ccc;

}

Select multiple columns from a table, but group by one

I use this trick to group by one column when I have a multiple columns selection:

SELECT MAX(id) AS id,
    Nume,
    MAX(intrare) AS intrare,
    MAX(iesire) AS iesire,
    MAX(intrare-iesire) AS stoc,
    MAX(data) AS data
FROM Produse
GROUP BY Nume
ORDER BY Nume

This works.

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

JNI converting jstring to char *

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

How to get a single value from FormGroup

You can do by the following ways

this.your_form.getRawValue()['formcontrolname]
this.your_form.value['formcontrolname]

jQuery .get error response function?

$.get does not give you the opportunity to set an error handler. You will need to use the low-level $.ajax function instead:

$.ajax({
    url: 'http://example.com/page/2/',
    type: 'GET',
    success: function(data){ 
        $(data).find('#reviews .card').appendTo('#reviews');
    },
    error: function(data) {
        alert('woops!'); //or whatever
    }
});

Edit March '10

Note that with the new jqXHR object in jQuery 1.5, you can set an error handler after calling $.get:

$.get('http://example.com/page/2/', function(data){ 
    $(data).find('#reviews .card').appendTo('#reviews');
}).fail(function() {
    alert('woops'); // or whatever
});

Detect the Enter key in a text input field

Try this to detect the Enter key pressed in a textbox.

$(document).on("keypress", "input", function(e){
    if(e.which == 13){
        alert("Enter key pressed");
    }
});

DEMO

Safest way to convert float to integer in python?

That this works is not trivial at all! It's a property of the IEEE floating point representation that int°floor = ?·? if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.

This post explains why it works in that range.

In a double, you can represent 32bit integers without any problems. There cannot be any rounding issues. More precisely, doubles can represent all integers between and including 253 and -253.

Short explanation: A double can store up to 53 binary digits. When you require more, the number is padded with zeroes on the right.

It follows that 53 ones is the largest number that can be stored without padding. Naturally, all (integer) numbers requiring less digits can be stored accurately.

Adding one to 111(omitted)111 (53 ones) yields 100...000, (53 zeroes). As we know, we can store 53 digits, that makes the rightmost zero padding.

This is where 253 comes from.


More detail: We need to consider how IEEE-754 floating point works.

  1 bit    11 / 8     52 / 23      # bits double/single precision
[ sign |  exponent | mantissa ]

The number is then calculated as follows (excluding special cases that are irrelevant here):

-1sign × 1.mantissa ×2exponent - bias

where bias = 2exponent - 1 - 1, i.e. 1023 and 127 for double/single precision respectively.

Knowing that multiplying by 2X simply shifts all bits X places to the left, it's easy to see that any integer must have all bits in the mantissa that end up right of the decimal point to zero.

Any integer except zero has the following form in binary:

1x...x where the x-es represent the bits to the right of the MSB (most significant bit).

Because we excluded zero, there will always be a MSB that is one—which is why it's not stored. To store the integer, we must bring it into the aforementioned form: -1sign × 1.mantissa ×2exponent - bias.

That's saying the same as shifting the bits over the decimal point until there's only the MSB towards the left of the MSB. All the bits right of the decimal point are then stored in the mantissa.

From this, we can see that we can store at most 52 binary digits apart from the MSB.

It follows that the highest number where all bits are explicitly stored is

111(omitted)111.   that's 53 ones (52 + implicit 1) in the case of doubles.

For this, we need to set the exponent, such that the decimal point will be shifted 52 places. If we were to increase the exponent by one, we cannot know the digit right to the left after the decimal point.

111(omitted)111x.

By convention, it's 0. Setting the entire mantissa to zero, we receive the following number:

100(omitted)00x. = 100(omitted)000.

That's a 1 followed by 53 zeroes, 52 stored and 1 added due to the exponent.

It represents 253, which marks the boundary (both negative and positive) between which we can accurately represent all integers. If we wanted to add one to 253, we would have to set the implicit zero (denoted by the x) to one, but that's impossible.

How to get source code of a Windows executable?

I would (and have) used IDA Pro to decompile executables. It creates semi-complete code, you can decompile to assembly or C.

If you have a copy of the debug symbols around, load those into IDA before decompiling and it will be able to name many of the functions, parameters, etc.

Simple way to understand Encapsulation and Abstraction

Abstraction is generalised term. i.e. Encapsulation is subset of Abstraction.

Abstraction is a powerful methodology to manage complex systems. Abstraction is managed by well-defined objects and their hierarchical classification.

For example a car in itself is a well-defined object, which is composed of several other smaller objects like a gearing system, steering mechanism, engine, which are again have their own subsystems. But for humans car is a one single object, which can be managed by the help of its subsystems, even if their inner details are unknown. Courtesy


Encapsulation: Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.

Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.

Encapsulation is like your bag in which you can keep your pen, book etc. It means this is the property of encapsulating members and functions.

class Bag{
    book;
    pen;
    ReadBook();
}

Encapsulation means hiding the internal details of an object, i.e. how an object does something.

Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.

Encapsulation is a technique used to protect the information in an object from the other object.

Hide the data for security such as making the variables as private, and expose the property to access the private data which would be public.

So, when you access the property you can validate the data and set it. Courtesy

How can I select all elements without a given class in jQuery?

You can use the .not() method or :not() selector

Code based on your example:

$("ul#list li").not(".active") // not method
$("ul#list li:not(.active)")   // not selector

How to run .NET Core console app from the command line

Using CMD you can run a console .net core project if .net core SDK is installed in your machine :

To run console project using windows command-Line, choose the specific path from your directory and type following below command

dotnet run

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

How to check if an alert exists using WebDriver?

I found catching exception of driver.switchTo().alert(); is so slow in Firefox (FF V20 & selenium-java-2.32.0).`

So I choose another way:

    private static boolean isDialogPresent(WebDriver driver) {
        try {
            driver.getTitle();
            return false;
        } catch (UnhandledAlertException e) {
            // Modal dialog showed
            return true;
        }
    }

And it's a better way when most of your test cases is NO dialog present (throwing exception is expensive).

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Also, if your service is sending an object instead of an array add isArray:false to its declaration.

'query': {method: 'GET', isArray: false }

How can we run a test method with multiple parameters in MSTest?

This feature is in pre-release now and works with Visual Studio 2015.

For example:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    [DataRow(1, 2, 2)]
    [DataRow(2, 3, 5)]
    [DataRow(3, 5, 8)]
    public void AdditionTest(int a, int b, int result)
    {
        Assert.AreEqual(result, a + b);
    }
}

How do I do base64 encoding on iOS?

Here is an example to convert an NSData object to Base 64. It also shows how to go the other way (decode a base 64 encoded NSData object):

NSData *dataTake2 = 
  [@"iOS Developer Tips" dataUsingEncoding:NSUTF8StringEncoding];

// Convert to Base64 data
NSData *base64Data = [dataTake2 base64EncodedDataWithOptions:0];

// Do something with the data...

// Now convert back from Base64
NSData *nsdataDecoded = [base64Data initWithBase64EncodedData:base64Data options:0];

What's the simplest way of detecting keyboard input in a script from the terminal?

Inspired from code found above (credits), the simple blocking (aka not CPU consuming) macOS version I was looking for:

import termios
import sys
import fcntl
import os

def getKeyCode(blocking = True):
    fd = sys.stdin.fileno()
    oldterm = termios.tcgetattr(fd)
    newattr = termios.tcgetattr(fd)
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)
    if not blocking:
        oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
    try:
        return ord(sys.stdin.read(1))
    except IOError:
        return 0
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        if not blocking:
            fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

def getKeyStroke():
    code  = getKeyCode()
    if code == 27:
        code2 = getKeyCode(blocking = False)
        if code2 == 0:
            return "esc"
        elif code2 == 91:
            code3 = getKeyCode(blocking = False)
            if code3 == 65:
                return "up"
            elif code3 == 66:
                return "down"
            elif code3 == 68:
                return "left"
            elif code3 == 67:
                return "right"
            else:
                return "esc?"
    elif code == 127:
        return "backspace"
    elif code == 9:
        return "tab"
    elif code == 10:
        return "return"
    elif code == 195 or code == 194:        
        code2 = getKeyCode(blocking = False)
        return chr(code)+chr(code2) # utf-8 char
    else:
        return chr(code)


while True:
    print getKeyStroke()

2017-11-09, EDITED: Not tested with Python 3

SQL Query for Logins

Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.

in iPhone App How to detect the screen resolution of the device

UIScreen class lets you find screen resolution in Points and Pixels.

Screen resolutions is measured in Points or Pixels. It should never be confused with screen size. A smaller screen size can have higher resolution.

UIScreen's 'bounds.width' return rectangular size in Points enter image description here

UIScreen's 'nativeBounds.width' return rectangular size in Pixels.This value is detected as PPI ( Point per inch ). Shows the sharpness & clarity of the Image on a device. enter image description here

You can use UIScreen class to detect all these values.

Swift3

// Normal Screen Bounds - Detect Screen size in Points.
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
print("\n width:\(width) \n height:\(height)")

// Native Bounds - Detect Screen size in Pixels.
let nWidth = UIScreen.main.nativeBounds.width
let nHeight = UIScreen.main.nativeBounds.height
print("\n Native Width:\(nWidth) \n Native Height:\(nHeight)")

Console

width:736.0 
height:414.0

Native Width:1080.0 
Native Height:1920.0

Swift 2.x

//Normal Bounds - Detect Screen size in Points.
    let width  = UIScreen.mainScreen.bounds.width
    let height = UIScreen.mainScreen.bounds.height

// Native Bounds - Detect Screen size in Pixels.
    let nWidth  = UIScreen.mainScreen.nativeBounds.width
    let nHeight = UIScreen.mainScreen.nativeBounds.height

ObjectiveC

// Normal Bounds - Detect Screen size in Points.
CGFloat *width  = [UIScreen mainScreen].bounds.size.width;
CGFloat *height = [UIScreen mainScreen].bounds.size.height;

// Native Bounds - Detect Screen size in Pixels.
CGFloat *width  = [UIScreen mainScreen].nativeBounds.size.width
CGFloat *height = [UIScreen mainScreen].nativeBounds.size.width

Align <div> elements side by side

Beware float: left

…there are many ways to align elements side-by-side.

Below are the most common ways to achieve two elements side-by-side…

Demo: View/edit all the below examples on Codepen


Basic styles for all examples below…

Some basic css styles for parent and child elements in these examples:

.parent {
  background: mediumpurple;
  padding: 1rem;
}
.child {
  border: 1px solid indigo;
  padding: 1rem;
}

float:left

Using the float solution my have unintended affect on other elements. (Hint: You may need to use a clearfix.)

html

<div class='parent'>
  <div class='child float-left-child'>A</div>
  <div class='child float-left-child'>B</div>
</div>

css

.float-left-child {
  float: left;
}

display:inline-block

html

<div class='parent'>
  <div class='child inline-block-child'>A</div>
  <div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

Note: the space between these two child elements can be removed, by removing the space between the div tags:

display:inline-block (no space)

html

<div class='parent'>
  <div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

display:flex

html

<div class='parent flex-parent'>
  <div class='child flex-child'>A</div>
  <div class='child flex-child'>B</div>
</div>

css

.flex-parent {
  display: flex;
}
.flex-child {
  flex: 1;
}

display:inline-flex

html

<div class='parent inline-flex-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.inline-flex-parent {
  display: inline-flex;
}

display:grid

html

<div class='parent grid-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.grid-parent {
  display: grid;
  grid-template-columns: 1fr 1fr
}

ip address validation in python using regex

\d{1,3} will match numbers like 00 or 333 as well which wouldn't be a valid ID.

This is an excellent answer from smink, citing:

ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";

`require': no such file to load -- mkmf (LoadError)

Ruby version: 2.7.1 gem version: 3.1.3

You need to check the extension that could not be installed, and find the reasons.

Read the mkmf.log file showed at the installation error under "To see why this extension failed to compile, please check the mkmf.log which can be found here" , perhaps there is a missing lib ( sometimes iconv ), and you must install it.

You can search the extension with your package manager(apt, yum, pacman...) too.

(Personal case) Arch Linux->nokogiri

gem install rails

Showed me:

To see why this extension failed to compile, please check the mkmf.log which can be found here: /home/user/.gem/ruby/2.7.0/extensions/x86_64-linux/2.7.0/nokogiri-1.10.9/mkmf.log

Go to: https://aur.archlinux.org/packages/ruby-nokogiri/

  1. Make sure you have all dependencies installed
  2. Make sure you have make installed
  3. git clone the package
  4. cd to package
  5. makepkg the package

Hope to help!

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

In openCV's documentation there is an example for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in python.

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
{
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;)
    {
        Mat frame;
        cap >> frame; // get a new frame from camera
        cvtColor(frame, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
        Canny(edges, edges, 0, 30, 3);
        imshow("edges", edges);
        if(waitKey(30) >= 0) break;
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

Find the least number of coins required that can make any change from 1 to 99 cents

Solution with greedy approach in java is as below :

public class CoinChange {
    public static void main(String args[]) {
        int denominations[] = {1, 5, 10, 25};
        System.out.println("Total required coins are " + greeadApproach(53, denominations));
    }

    public static int greeadApproach(int amount, int denominations[]) {
        int cnt[] = new int[denominations.length];
        for (int i = denominations.length-1; amount > 0 && i >= 0; i--) {
            cnt[i] = (amount/denominations[i]);
            amount -= cnt[i] * denominations[i];            
        }
        int noOfCoins = 0;
        for (int cntVal : cnt) {
            noOfCoins+= cntVal;
        }
        return noOfCoins;
    }
}

But this works for single amount. If you want to run it for range, than we have to call it for each amount of range.

How to store token in Local or Session Storage in Angular 2?

var arr=[{"username":"sai","email":"[email protected],"}]
localStorage.setItem('logInArr', JSON.stringfy(arr))

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

How to increase IDE memory limit in IntelliJ IDEA on Mac?

As for the intellij2018 version I am using the following configuration for better performance

-server
-Xms1024m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops
-Dfile.encoding=UTF-8
-XX:+UseConcMarkSweepGC
-XX:+AggressiveOpts
-XX:+CMSClassUnloadingEnabled
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:CMSIncrementalDutyCycleMin=0
-XX:-TraceClassUnloading
-XX:+TieredCompilation
-XX:SoftRefLRUPolicyMSPerMB=100
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djdk.http.auth.tunneling.disabledSchemes=""
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-Xverify:none

-XX:ErrorFile=$USER_HOME/java_error_in_idea_%p.log
-XX:HeapDumpPath=$USER_HOME/java_error_in_idea.hprof

How do you dynamically add elements to a ListView on Android?

If you want to have the ListView in an AppCompatActivity instead of ListActivity, you can do the following (Modifying @Shardul's answer):

public class ListViewDemoActivity extends AppCompatActivity {
    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

    //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;
    private ListView mListView;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_list_view_demo);

        if (mListView == null) {
            mListView = (ListView) findViewById(R.id.listDemo);
        }

        adapter=new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }

    protected ListView getListView() {
        if (mListView == null) {
            mListView = (ListView) findViewById(R.id.listDemo);
        }
        return mListView;
    }

    protected void setListAdapter(ListAdapter adapter) {
        getListView().setAdapter(adapter);
    }

    protected ListAdapter getListAdapter() {
        ListAdapter adapter = getListView().getAdapter();
        if (adapter instanceof HeaderViewListAdapter) {
            return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
        } else {
            return adapter;
        }
    }
}

And in you layout instead of using android:id="@android:id/list" you can use android:id="@+id/listDemo"

So now you can have a ListView inside a normal AppCompatActivity.

How to group time by hour or by 10 minutes

select from_unixtime( 600 * ( unix_timestamp( [Date] ) % 600 ) ) AS RecT, avg(Value)
from [FRIIB].[dbo].[ArchiveAnalog]
group by RecT
order by RecT;

replace the two 600 by any number of seconds you want to group.

If you need this often and the table doesn't change, as the name Archive suggests, it would probably be a bit faster to convert and store the date (& time) as a unixtime in the table.

VBA setting the formula for a cell

Try:

.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address

If your worksheet name (strProjectName) has spaces, you need to include the single quotes in the formula string.

If this does not resolve it, please provide more information about the specific error or failure.

Update

In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:

strProjectName = Replace(strProjectName," ", "_")

But if you're not also pushing that change to the Worksheet.Name property, you can expect these to happen:

  1. The file browse dialog appears
  2. The formula returns #REF error

The reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.

So you need to do:

Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")

Then, your formula should work.

How to get the nvidia driver version from the command line?

[NOTE: I am not deleting my answer on purpose, so people see how not to do it]

If you use:

me@over_there:~$  dpkg --status nvidia-current | grep Version | cut -f 1 -d '-' | sed 's/[^.,0-9]//g'
260.19.06

you will get the version of the nVIDIA driver package installed through your distribution's packaging mechanism. But this may not be the version that is actually running as part of your kernel right now.

Server unable to read htaccess file, denying access to be safe

You need to run these commands in /var/www/html/ or any other directory that your project is on:

sudo chgrp -R GROUP ./
sudo chown -R USER:GROUP ./
find ./ -type d -exec chmod 755 -R {} \;
find ./ -type f -exec chmod 644 {} \;

In my case (apache web server) I use www-data for USER and GROUP

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

Another problem is when eclipse doesn't have write access to your src folder. Change the security permission and make sure "Authenticated Users" are added with all permissions checked but Full Control & Special Permissions.

Where is android_sdk_root? and how do I set it.?

Open the terminal and run the command: nano $HOME/.bashrc aggregate the follow line:

export ANDROID_HOME=$HOME/Android/Sdk
export ANDROID_SDK_ROOT=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools

Ctrl+o save and ctrl+x close.

And run the command:

source $HOME/.bashrc

echo $ANDROID_SDK_ROOT

File Not Found when running PHP with Nginx

I just spent like 40 minutes trying to debug a non-working /status with:

$ SCRIPT_NAME=/status SCRIPT_FILENAME=/status QUERY_STRING= REQUEST_METHOD=GET cgi-fcgi -bind -connect /var/run/php5-fpm.sock

It just produced "File not found" error, while the actual scripts (that are found on the filesystem) worked just fine.

Turned out, I had a couple of orphaned processes of php5-fpm. After I killed everything and restarted php5-fpm cleanly, it just went back to normal.

Hope this helps.

Export table from database to csv file

I wrote a small tool that does just that. Code is available on github.

To dump the results of one (or more) SQL queries to one (or more) CSV files:

java -jar sql_dumper.jar /path/sql/files/ /path/out/ user pass jdbcString

Cheers.

How to change the commit author for one specific commit?

If what you need to change is the AUTHOR OF THE LAST commit and no other is using your repository, you may undo your last commit with:

git push -f origin last_commit_hash:branch_name 

change the author name of your commit with:

git commit --amend --author "type new author here"

Exit the editor that opens and push again your code:

git push

How to change the server port from 3000?

1-> Using File Default Config- Angular-cli comes from the ember-cli project. To run the application on specific port, create an .ember-cli file in the project root. Add your JSON config in there:

{ "port": 1337 }

2->Using Command Line Tool Run this command in Angular-Cli

ng serve --port 1234

To change the port number permanently:

Goto

node_modules/angular-cli/commands/server.js

Search for var defaultPort = process.env.PORT || 4200; (change 4200 to anything else you want).

How to create a self-signed certificate for a domain name for development?

To Create the new certificate for your specific domain:

Open Powershell ISE as admin, run the command:

New-SelfSignedCertificate -DnsName *.mydomain.com, localhost -CertStoreLocation cert:\LocalMachine\My

To trust the new certificate:

  • Open mmc.exe
  • Go to Console Root -> Certificates (Local Computer) -> Personal
  • Select the certificate you have created, do right click -> All Tasks -> Export and follow the export wizard to create a .pfx file
  • Go to Console Root -> Certificates -> Trusted Root Certification Authorities and import the new .pfx file

To bind the certificate to your site:

  • Open IIS Manager
  • Select your site and choose Edit Site -> Bindings in the right pane
  • Add new https binding with the correct hostname and the new certificate

Best way to serialize/unserialize objects in JavaScript?

The browser's native JSON API may not give you back your idOld function after you call JSON.stringify, however, if can stringify your JSON yourself (maybe use Crockford's json2.js instead of browser's API), then if you have a string of JSON e.g.

var person_json = "{ \"age:\" : 20, \"isOld:\": false, isOld: function() { return this.age > 60; } }";

then you can call

eval("(" + person + ")") 

, and you will get back your function in the json object.

Android map v2 zoom to show all the markers

   //For adding a marker in Google map
        MarkerOptions mp = new MarkerOptions();
        mp.position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)));
        mp.snippet(strAddress);
        map.addMarker(mp);

        try {

            b = new LatLngBounds.Builder();

            if (MapDetailsList.list != null && MapDetailsList.list.size() > 0) {

                for (int i = 0; i < MapDetailsList.list.size(); i++) {

                    b.include(new LatLng(Double.parseDouble(MapDetailsList.list.get(i).getLatitude()),
                            Double.parseDouble(MapDetailsList.list.get(i).getLongitude())));

                }
                LatLngBounds bounds = b.build();

                DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
                int width = displayMetrics.widthPixels;
                int height = displayMetrics.heightPixels;

                // Change the padding as per needed
                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width-200, height-200, 5);
                // map.setCenter(bounds.getCenter());

                map.animateCamera(cu);

            }

        } catch (Exception e) {

        }

http://i64.tinypic.com/2qjybh4.png

http://i63.tinypic.com/flzwus.png

http://i63.tinypic.com/112g5fm.png

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

How to display string that contains HTML in twig template?

You can also use:

{{ word|striptags('<b>')|raw }}

so that only <b> tag will be allowed.

Is there a JavaScript function that can pad a string to get to a determined length?

padding string has been inplemented in new javascript version.

str.padStart(targetLength [, padString])

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/padStart

If you want your own function check this example:

const myString = 'Welcome to my house';
String.prototype.padLeft = function(times = 0, str = ' ') {
    return (Array(times).join(str) + this);
}
console.log(myString.padLeft(12, ':'));
//:::::::::::Welcome to my house

Manifest Merger failed with multiple errors in Android Studio

After seeing CLIFFORD's answer to see the error, what helped me to solve this issue was renaming 'android:namex' to 'android:name' in the intent-filter action tag. In case if the same solution helps someone else .

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:namex="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Android - how do I investigate an ANR?

my issue with ANR , after much work i found out that a thread was calling a resource that did not exist in the layout, instead of returning an exception , i got ANR ...

How do I check to see if my array includes an object?

#include? should work, it works for general objects, not only strings. Your problem in example code is this test:

unless @suggested_horses.exists?(horse.id)
  @suggested_horses<< horse
end

(even assuming using #include?). You try to search for specific object, not for id. So it should be like this:

unless @suggested_horses.include?(horse)
  @suggested_horses << horse
end

ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id

Angular 4 img src is not found

You must use this code in angular to add the image path. if your images are under assets folder then.

<img src="../assets/images/logo.png" id="banner-logo" alt="Landing Page"/>

if not under the assets folder then you can use this code.

<img src="../images/logo.png" id="banner-logo" alt="Landing Page"/>

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

This is working code for your query,you can use it.

Controler

    [HttpPost]
    public ActionResult save(List<ListName> listObject)
    {
    //operation return
    Json(new { istObject }, JsonRequestBehavior.AllowGet); }
    }

javascript

  $("#btnSubmit").click(function () {
    var myColumnDefs = [];
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            myColumnDefs.push({ 'Status': true, 'ID': $(this).data('id') })
        } else {
            myColumnDefs.push({ 'Status': false, 'ID': $(this).data('id') })
        }
    });
   var data1 = { 'listObject': myColumnDefs};
   var data = JSON.stringify(data1)
   $.ajax({
   type: 'post',
   url: '/Controller/action',
   data:data ,
   contentType: 'application/json; charset=utf-8',
   success: function (response) {
    //do your actions
   },
   error: function (response) {
    alert("error occured");
   }
   });

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

Targeting all elements but html : *:not(html) caused problems on other elements in my case. It modified the stacking context, causing some z-index to break.

We should better try to target the right element and apply -webkit-transform: translate3d(0,0,0) to it only.

Edit : sometimes the translate3D(0,0,0) doesn't work, we can use the following method, targeting the right element :

@keyframes redraw{
    0% {opacity: 1;}
    100% {opacity: .99;}
}

// ios redraw fix
animation: redraw 1s linear infinite;

CSS image resize percentage of itself?

Another solution is to use:

<img srcset="example.png 2x">

It won't validate because the src attribute is required, but it works (except on any version of IE because srcset is not supported).

Why does SSL handshake give 'Could not generate DH keypair' exception?

If you are still bitten by this issue AND you are using Apache httpd v> 2.4.7, try this: http://httpd.apache.org/docs/current/ssl/ssl_faq.html#javadh

copied from the url:

Beginning with version 2.4.7, mod_ssl will use DH parameters which include primes with lengths of more than 1024 bits. Java 7 and earlier limit their support for DH prime sizes to a maximum of 1024 bits, however.

If your Java-based client aborts with exceptions such as java.lang.RuntimeException: Could not generate DH keypair and java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 1024 (inclusive), and httpd logs tlsv1 alert internal error (SSL alert number 80) (at LogLevel info or higher), you can either rearrange mod_ssl's cipher list with SSLCipherSuite (possibly in conjunction with SSLHonorCipherOrder), or you can use custom DH parameters with a 1024-bit prime, which will always have precedence over any of the built-in DH parameters.

To generate custom DH parameters, use the

openssl dhparam 1024

command. Alternatively, you can use the following standard 1024-bit DH parameters from RFC 2409, section 6.2:

-----BEGIN DH PARAMETERS-----
MIGHAoGBAP//////////yQ/aoiFowjTExmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJR
Sgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL
/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR7OZTgf//////////AgEC
-----END DH PARAMETERS-----

Add the custom parameters including the "BEGIN DH PARAMETERS" and "END DH PARAMETERS" lines to the end of the first certificate file you have configured using the SSLCertificateFile directive.


I am using java 1.6 on client side, and it solved my issue. I didn't lowered the cipher suites or like, but added a custom generated DH param to the cert file..

Python: Get the first character of the first string in a list?

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

These two videos cleared things up for me:

"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

How can I run a windows batch file but hide the command window?

For any executable file, you can run your program using cmd with "c" parameter:

cmd /c "your program address"\"YourFileName".bat  

(->if it's a batch file!) As a final solution, I suggest that you create a .cmd file and put this command in it:

cmd /c "your program address"\"YourFileName".bat
exit

Now just run this .cmd file.

Chrome blocks different origin requests

Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.

Stop Chrome Caching My JS Files

You can open an incognito window instead. Switching to an incognito window worked for me when disabling the cache in a normal chrome window still didn't reload a JavaScript file I had changed since the last cache.

https://www.quora.com/Does-incognito-mode-on-Chrome-use-the-cache-that-was-previously-stored

How to run Java program in command prompt

A very general command prompt how to for java is

javac mainjava.java
java mainjava

You'll very often see people doing

javac *.java
java mainjava

As for the subclass problem that's probably occurring because a path is missing from your class path, the -c flag I believe is used to set that.

CMD command to check connected USB devices

You could use wmic command:

wmic logicaldisk where drivetype=2 get <DeviceID, VolumeName, Description, ...>

Drivetype 2 indicates that its a removable disk.

Git - How to use .netrc file on Windows to save user and password

Is it possible to use a .netrc file on Windows?

Yes: You must:

  • define environment variable %HOME% (pre-Git 2.0, no longer needed with Git 2.0+)
  • put a _netrc file in %HOME%

If you are using Windows 7/10, in a CMD session, type:

setx HOME %USERPROFILE%

and the %HOME% will be set to 'C:\Users\"username"'.
Go that that folder (cd %HOME%) and make a file called '_netrc'

Note: Again, for Windows, you need a '_netrc' file, not a '.netrc' file.

Its content is quite standard (Replace the <examples> with your values):

machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>

Luke mentions in the comments:

Using the latest version of msysgit on Windows 7, I did not need to set the HOME environment variable. The _netrc file alone did the trick.

This is indeed what I mentioned in "Trying to “install” github, .ssh dir not there":
git-cmd.bat included in msysgit does set the %HOME% environment variable:

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

??? believes in the comments that "it seems that it won't work for http protocol"

However, I answered that netrc is used by curl, and works for HTTP protocol, as shown in this example (look for 'netrc' in the page): . Also used with HTTP protocol here: "_netrc/.netrc alternative to cURL".


A common trap with with netrc support on Windows is that git will bypass using it if an origin https url specifies a user name.

For example, if your .git/config file contains:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://[email protected]/p/my-project/

Git will not resolve your credentials via _netrc, to fix this remove your username, like so:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://code.google.com/p/my-project/

Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.


With Git 1.8.3 (April 2013):

You now can use an encrypted .netrc (with gpg).
On Windows: %HOME%/_netrc (_, not '.')

A new read-only credential helper (in contrib/) to interact with the .netrc/.authinfo files has been added.

That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.

Files with the .gpg extension will be decrypted by GPG before parsing.
Multiple -f arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.

When no -f option is given, .authinfo.gpg, .netrc.gpg, .authinfo, and .netrc files in your home directory are used in this order.

To enable this credential helper:

git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'

(Note that Git will prepend "git-credential-" to the helper name and look for it in the path.)

# and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'

#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'

See a full example at "Is there a way to skip password typing when using https:// github"


With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'

Global Git ignore

  1. Create a .gitignore file in your home directory
touch ~/.gitignore
  1. Add files to it (folders aren't recognised)

Example

# these work
*.gz
*.tmproj
*.7z

# these won't as they are folders
.vscode/
build/

# but you can do this
.vscode/*
build/*
  1. Check if a git already has a global gitignore
git config --get core.excludesfile
  1. Tell git where the file is
git config --global core.excludesfile '~/.gitignore'

Voila!!

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

C# - Winforms - Global Variables

The consensus here is to put the global variables in a static class as static members. When you create a new Windows Forms application, it usually comes with a Program class (Program.cs), which is a static class and serves as the main entry point of the application. It lives for the the whole lifetime of the app, so I think it is best to put the global variables there instead of creating a new one.

static class Program
{
    public static string globalString = "This is a global string.";

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

And use it as such:

public partial class Form1 : Form
{
    public Form1()
    {
        Program.globalString = "Accessible in Form1.";

        InitializeComponent();
    }
}

java- reset list iterator to first element of the list

What you may actually want to use is an Iterable that can return a fresh Iterator multiple times by calling iterator().

//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
    Iterator<Type> it = ible.iterator(); //Gets an iterator
    while (it.hasNext()) {
        it.next();
    }
    it = ible.iterator(); //Gets a NEW iterator, also from the beginning
    while (it.hasNext()) {
        it.next();
    }
}

You must define what the iterator() method does just once beforehand:

void main() {
    LinkedList<String> list; //This could be any type of object that has an iterator
    //Define an Iterable that knows how to retrieve a fresh iterator
    Iterable<Type> ible = new Iterable<Type>() {
        @Override
        public Iterator<Type> iterator() {
            return list.listIterator(); //Define how to get a fresh iterator from any object
        }
    };
    //Now with a single instance of an Iterable,
    func(ible); //you can iterate through it multiple times.
}

How do I automatically set the $DISPLAY variable for my current session?

You'll need to tell your vnc client to export the correct $DISPLAY once you have logged in. How you do that will probably depend on your vnc client.

What is .Net Framework 4 extended?

Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

* ASP.NET
* Advanced Windows Communication Foundation (WCF) functionality
* .NET Framework Data Provider for Oracle
* MSBuild for compiling

Where do I put image files, css, js, etc. in Codeigniter?

The link_tag() helper is clearly the way to do this. Put your css where it usually belongs, in site_root/css/ and then use the helper:

From The CodeIgniter docs...

echo link_tag('css/mystyles.css');

Output

<link href="http://example.com/css/mystyles.css" rel="stylesheet" type="text/css" />

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

I removed C:\ProgramData\Oracle\Java\javapath from my path, and it worked for me. Perfect Answer, Thanks Nikil.

Convert MFC CString to integer

A _ttoi function can convert CString to integer, both wide char and ansi char can work. Below is the details:

CString str = _T("123");
int i = _ttoi(str);

How to add border radius on table row

All the answers are way too long. The easiest way to add border radius to a table element that accepts border as a property, is doing border radius with overflow: hidden.

border: xStyle xColor xSize;
border-collapse: collapse;
border-radius: 1em;
overflow: hidden;

How do I list all tables in a schema in Oracle SQL?

To see all tables in another schema, you need to have one or more of the following system privileges:

SELECT ANY DICTIONARY
(SELECT | INSERT | UPDATE | DELETE) ANY TABLE

or the big-hammer, the DBA role.

With any of those, you can select:

SELECT DISTINCT OWNER, OBJECT_NAME 
  FROM DBA_OBJECTS
 WHERE OBJECT_TYPE = 'TABLE'
   AND OWNER = '[some other schema]'

Without those system privileges, you can only see tables you have been granted some level of access to, whether directly or through a role.

SELECT DISTINCT OWNER, OBJECT_NAME 
  FROM ALL_OBJECTS
 WHERE OBJECT_TYPE = 'TABLE'
   AND OWNER = '[some other schema]'

Lastly, you can always query the data dictionary for your own tables, as your rights to your tables cannot be revoked (as of 10g):

SELECT DISTINCT OBJECT_NAME 
  FROM USER_OBJECTS
 WHERE OBJECT_TYPE = 'TABLE'

Automatically accept all SDK licences

Download the SDK manager from this link. Then unzip and use the following command in terminal.

!tools/bin/sdkmanager --sdk_root=/usr/lib/android-sdk --licenses <<< $'y\ny\ny\ny\ny\ny\ny\n'

shell-script headers (#!/bin/sh vs #!/bin/csh)

The #! line tells the kernel (specifically, the implementation of the execve system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46 (^?ELF) that identifies them as such.

You can put an absolute path to any program you want after the #!, as long as that program is not itself a #! script. The kernel rewrites an invocation of

./script arg1 arg2 arg3 ...

where ./script starts with, say, #! /usr/bin/perl, as if the command line had actually been

/usr/bin/perl ./script arg1 arg2 arg3

Or, as you have seen, you can use #! /bin/sh to write a script intended to be interpreted by sh.

The #! line is only processed if you directly invoke the script (./script on the command line); the file must also be executable (chmod +x script). If you do sh ./script the #! line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/* -- you will discover that a great many stock programs are in fact using this feature.)

Here are some rules for using this feature:

  • The #! must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #! script.
  • The path after #! must be an absolute path (starts with /). It cannot contain space, tab, or newline characters.
  • It is good style, but not required, to put a space between the #! and the /. Do not put more than one space there.
  • You cannot put shell variables on the #! line, they will not be expanded.
  • You can put one command-line argument after the absolute path, separated from it by a single space. Like the absolute path, this argument cannot contain space, tab, or newline characters. Sometimes this is necessary to get things to work (#! /usr/bin/awk -f), sometimes it's just useful (#! /usr/bin/perl -Tw). Unfortunately, you cannot put two or more arguments after the absolute path.
  • Some people will tell you to use #! /usr/bin/env interpreter instead of #! /absolute/path/to/interpreter. This is almost always a mistake. It makes your program's behavior depend on the $PATH variable of the user who invokes the script. And not all systems have env in the first place.
  • Programs that need setuid or setgid privileges can't use #!; they have to be compiled to machine code. (If you don't know what setuid is, don't worry about this.)

Regarding csh, it relates to sh roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh have caught up) a number of advantages over sh for interactive usage, but using it (or its descendant tcsh) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh. If you are using a csh relative as your login shell, switch to bash or zsh, so that the interactive command language will be the same as the scripting language you're learning.

CSS text-align not working

I try to avoid floating elements unless the design really needs it. Because you have floated the <li> they are out of normal flow.

If you add .navigation { text-align:center; } and change .navigation li { float: left; } to .navigation li { display: inline-block; } then entire navigation will be centred.

One caveat to this approach is that display: inline-block; is not supported in IE6 and needs a workaround to make it work in IE7.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

In case of Request to a REST Service:

You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:

@CrossOrigin(origins = "http://localhost:8080")

Very good tutorial: https://spring.io/guides/gs/rest-service-cors/

Java FileOutputStream Create File if not exists

new FileOutputStream(f) will create a file in most cases, but unfortunately you will get a FileNotFoundException

if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

from Javadoc

I other word there might be plenty of cases where you would get FileNotFoundException meaning "Could not create your file", but you would not be able to find the reason of why the file creation failed.

A solution is to remove any call to the File API and use the Files API instead as it provides much better error handling. Typically replace any new FileOutputStream(f) with Files.newOutputStream(p).

In cases where you do need to use the File API (because you use an external interface using File for example), using Files.createFile(p) is a good way to make sure your file is created properly and if not you would know why it didn't work. Some people commented above that this is redundant. It is true, but you get better error handling which might be necessary in some cases.

How to list all dates between two dates

I made a calendar using:

http://social.technet.microsoft.com/wiki/contents/articles/22776.t-sql-calendar-table.aspx

then a Store procedure passing two dates and thats all:

USE DB_NAME;
GO

CREATE PROCEDURE [dbo].[USP_LISTAR_RANGO_FECHAS]
@FEC_INICIO date,
@FEC_FIN date
AS
Select Date from CALENDARIO where Date BETWEEN @FEC_INICIO AND @FEC_FIN;

form action with javascript

I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:

action="javascript:checkout()"

You try this?

Don't forget include the script reference in the html head.

I don't know cause of that works in firefox. Regards.

Maximum and Minimum values for ints

I rely heavily on commands like this.

python -c 'import sys; print(sys.maxsize)'

Max int returned: 9223372036854775807

For more references for 'sys' you should access

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/sys.html#sys.maxsize

Alternative to a goto statement in Java

Use a labeled break as an alternative to goto.

How can I pass arguments to a batch file?

A friend was asking me about this subject recently, so I thought I'd post how I handle command-line arguments in batch files.

This technique has a bit of overhead as you'll see, but it makes my batch files very easy to understand and quick to implement. As well as supporting the following structures:

>template.bat [-f] [--flag] [/f] [--namedvalue value] arg1 [arg2][arg3][...]

The jist of it is having the :init, :parse, and :main functions.

Example usage

>template.bat /?
test v1.23
This is a sample batch file template,
providing command-line arguments and flags.

USAGE:
test.bat [flags] "required argument" "optional argument"

/?, --help           shows this help
/v, --version        shows the version
/e, --verbose        shows detailed output
-f, --flag value     specifies a named parameter value

>template.bat          <- throws missing argument error
(same as /?, plus..)
****                                   ****
****    MISSING "REQUIRED ARGUMENT"    ****
****                                   ****

>template.bat -v
1.23

>template.bat --version
test v1.23
This is a sample batch file template,
providing command-line arguments and flags.

>template.bat -e arg1
**** DEBUG IS ON
UnNamedArgument:    "arg1"
UnNamedOptionalArg: not provided
NamedFlag:          not provided

>template.bat --flag "my flag" arg1 arg2
UnNamedArgument:    "arg1"
UnNamedOptionalArg: "arg2"
NamedFlag:          "my flag"

>template.bat --verbose "argument #1" --flag "my flag" second
**** DEBUG IS ON
UnNamedArgument:    "argument #1"
UnNamedOptionalArg: "second"
NamedFlag:          "my flag"

template.bat

@::!/dos/rocks
@echo off
goto :init

:header
    echo %__NAME% v%__VERSION%
    echo This is a sample batch file template,
    echo providing command-line arguments and flags.
    echo.
    goto :eof

:usage
    echo USAGE:
    echo   %__BAT_NAME% [flags] "required argument" "optional argument" 
    echo.
    echo.  /?, --help           shows this help
    echo.  /v, --version        shows the version
    echo.  /e, --verbose        shows detailed output
    echo.  -f, --flag value     specifies a named parameter value
    goto :eof

:version
    if "%~1"=="full" call :header & goto :eof
    echo %__VERSION%
    goto :eof

:missing_argument
    call :header
    call :usage
    echo.
    echo ****                                   ****
    echo ****    MISSING "REQUIRED ARGUMENT"    ****
    echo ****                                   ****
    echo.
    goto :eof

:init
    set "__NAME=%~n0"
    set "__VERSION=1.23"
    set "__YEAR=2017"

    set "__BAT_FILE=%~0"
    set "__BAT_PATH=%~dp0"
    set "__BAT_NAME=%~nx0"

    set "OptHelp="
    set "OptVersion="
    set "OptVerbose="

    set "UnNamedArgument="
    set "UnNamedOptionalArg="
    set "NamedFlag="

:parse
    if "%~1"=="" goto :validate

    if /i "%~1"=="/?"         call :header & call :usage "%~2" & goto :end
    if /i "%~1"=="-?"         call :header & call :usage "%~2" & goto :end
    if /i "%~1"=="--help"     call :header & call :usage "%~2" & goto :end

    if /i "%~1"=="/v"         call :version      & goto :end
    if /i "%~1"=="-v"         call :version      & goto :end
    if /i "%~1"=="--version"  call :version full & goto :end

    if /i "%~1"=="/e"         set "OptVerbose=yes"  & shift & goto :parse
    if /i "%~1"=="-e"         set "OptVerbose=yes"  & shift & goto :parse
    if /i "%~1"=="--verbose"  set "OptVerbose=yes"  & shift & goto :parse

    if /i "%~1"=="--flag"     set "NamedFlag=%~2"   & shift & shift & goto :parse

    if not defined UnNamedArgument     set "UnNamedArgument=%~1"     & shift & goto :parse
    if not defined UnNamedOptionalArg  set "UnNamedOptionalArg=%~1"  & shift & goto :parse

    shift
    goto :parse

:validate
    if not defined UnNamedArgument call :missing_argument & goto :end

:main
    if defined OptVerbose (
        echo **** DEBUG IS ON
    )

    echo UnNamedArgument:    "%UnNamedArgument%"

    if defined UnNamedOptionalArg      echo UnNamedOptionalArg: "%UnNamedOptionalArg%"
    if not defined UnNamedOptionalArg  echo UnNamedOptionalArg: not provided

    if defined NamedFlag               echo NamedFlag:          "%NamedFlag%"
    if not defined NamedFlag           echo NamedFlag:          not provided

:end
    call :cleanup
    exit /B

:cleanup
    REM The cleanup function is only really necessary if you
    REM are _not_ using SETLOCAL.
    set "__NAME="
    set "__VERSION="
    set "__YEAR="

    set "__BAT_FILE="
    set "__BAT_PATH="
    set "__BAT_NAME="

    set "OptHelp="
    set "OptVersion="
    set "OptVerbose="

    set "UnNamedArgument="
    set "UnNamedArgument2="
    set "NamedFlag="

    goto :eof

Make an html number input always display 2 decimal places

The accepted solution here is incorrect. Try this in the HTML:

onchange="setTwoNumberDecimal(this)" 

and the function to look like:

 function setTwoNumberDecimal(el) {
        el.value = parseFloat(el.value).toFixed(2);
    };

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

I think the easiest solution is to set

Created DATETIME2 NOT NULL DEFAULT GETDATE()

in column declaration and in VS2010 EntityModel designer set corresponding column property StoreGeneratedPattern = Computed.

Load and execution sequence of a web page?

1) HTML is downloaded.

2) HTML is parsed progressively. When a request for an asset is reached the browser will attempt to download the asset. A default configuration for most HTTP servers and most browsers is to process only two requests in parallel. IE can be reconfigured to downloaded an unlimited number of assets in parallel. Steve Souders has been able to download over 100 requests in parallel on IE. The exception is that script requests block parallel asset requests in IE. This is why it is highly suggested to put all JavaScript in external JavaScript files and put the request just prior to the closing body tag in the HTML.

3) Once the HTML is parsed the DOM is rendered. CSS is rendered in parallel to the rendering of the DOM in nearly all user agents. As a result it is strongly recommended to put all CSS code into external CSS files that are requested as high as possible in the <head></head> section of the document. Otherwise the page is rendered up to the occurance of the CSS request position in the DOM and then rendering starts over from the top.

4) Only after the DOM is completely rendered and requests for all assets in the page are either resolved or time out does JavaScript execute from the onload event. IE7, and I am not sure about IE8, does not time out assets quickly if an HTTP response is not received from the asset request. This means an asset requested by JavaScript inline to the page, that is JavaScript written into HTML tags that is not contained in a function, can prevent the execution of the onload event for hours. This problem can be triggered if such inline code exists in the page and fails to execute due to a namespace collision that causes a code crash.

Of the above steps the one that is most CPU intensive is the parsing of the DOM/CSS. If you want your page to be processed faster then write efficient CSS by eliminating redundent instructions and consolidating CSS instructions into the fewest possible element referrences. Reducing the number of nodes in your DOM tree will also produce faster rendering.

Keep in mind that each asset you request from your HTML or even from your CSS/JavaScript assets is requested with a separate HTTP header. This consumes bandwidth and requires processing per request. If you want to make your page load as fast as possible then reduce the number of HTTP requests and reduce the size of your HTML. You are not doing your user experience any favors by averaging page weight at 180k from HTML alone. Many developers subscribe to some fallacy that a user makes up their mind about the quality of content on the page in 6 nanoseconds and then purges the DNS query from his server and burns his computer if displeased, so instead they provide the most beautiful possible page at 250k of HTML. Keep your HTML short and sweet so that a user can load your pages faster. Nothing improves the user experience like a fast and responsive web page.

How to copy a collection from one database to another in MongoDB

use "Studio3T for MongoDB" that have Export and Import tools by click on database , collections or specific collection download link : https://studio3t.com/download/

Resizing a button

try this one out resizeable button

<button type="submit me" style="height: 25px; width: 100px">submit me</button>

Calculating distance between two points (Latitude, Longitude)

It looks like Microsoft invaded brains of all other respondents and made them write as complicated solutions as possible. Here is the simplest way without any additional functions/declare statements:

SELECT geography::Point(LATITUDE_1, LONGITUDE_1, 4326).STDistance(geography::Point(LATITUDE_2, LONGITUDE_2, 4326))

Simply substitute your data instead of LATITUDE_1, LONGITUDE_1, LATITUDE_2, LONGITUDE_2 e.g.:

SELECT geography::Point(53.429108, -2.500953, 4326).STDistance(geography::Point(c.Latitude, c.Longitude, 4326))
from coordinates c

Best place to insert the Google Analytics code

If you want your scripts to load after page has been rendered, you can use:

function getScript(a, b) {
    var c = document.createElement("script");
    c.src = a;
    var d = document.getElementsByTagName("head")[0],
        done = false;
    c.onload = c.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
            done = true;
            b();
            c.onload = c.onreadystatechange = null;
            d.removeChild(c)
        }
    };
    d.appendChild(c)
}

//call the function
getScript("http://www.google-analytics.com/ga.js", function() {
    // do stuff after the script has loaded
});

How can I check for Python version in a program that uses new language features?

Although the question is: How do I get control early enough to issue an error message and exit?

The question that I answer is: How do I get control early enough to issue an error message before starting the app?

I can answer it a lot differently then the other posts. Seems answers so far are trying to solve your question from within Python.

I say, do version checking before launching Python. I see your path is Linux or unix. However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.

Here is the DOS script with version 2.7:

@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF

This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.

The FOR /F line is the key.

FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul

For multiple python version check check out url: http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17

And my hack version:

[MS script; Python version check prelaunch of Python module] http://pastebin.com/aAuJ91FQ

Pass user defined environment variable to tomcat

My recipe to fix it:

  1. DID NOT WORK >> Set as system environment variable: I had set the environment variable in my mac bash_profile, however, Tomcat did not see that variable.

  2. DID NOT WORK >> setenv.sh: Apache's recommendation was to have user-defined environment variables in setenv.sh file and I did that.

  3. THIS WORKED!! >> After a little research into Tomcat startup scripts, I found that environment variables set using setenv.sh are lost during the startup. So I had to edit my catalina.sh against the recommendation of Apache and that did the trick.

Add your -DUSER_DEFINED variable in the run command in catalina.sh.

eval exec "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
  -classpath "\"$CLASSPATH\"" \
  -Djava.security.manager \
  -Djava.security.policy=="\"$CATALINA_BASE/conf/catalina.policy\"" \
  -Dcatalina.base="\"$CATALINA_BASE\"" \
  -Dcatalina.home="\"$CATALINA_HOME\"" \
  -Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
  -DUSER_DEFINED="$USER_DEFINED" \
  org.apache.catalina.startup.Bootstrap "$@" start

P.S: This problem could have been local to my computer. Others would have different problems. Adding my answer to this post just in case anyone is still facing issues with Tomcat not seeing the environment vars after trying out all recommended approaches.

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

I was having some difficulty translating actual VB.NET to the Expression subset that SSRS uses. You definitely inspired me though and this is what I came up with.

StartDate  
=dateadd("d",0,dateserial(year(dateadd("d",-1,dateserial(year(Today),month(Today),1))),month(dateadd("d",-1,dateserial(year(Today),month(Today),1))),1))

End Date
=dateadd("d",0,dateserial(year(Today),month(Today),1))  

I know it's a bit recursive for the StartDate (first day of last month). Is there anything I'm missing here? These are strictly date fields (i.e. no time), but I think this should capture leap year, etc.

How did I do?

jQuery 'if .change() or .keyup()'

you can bind to multiple events by separating them with a space:

$(":input").on("keyup change", function(e) {
    // do stuff!
})

docs here.

hope that helps. cheers!

PHP: How to get current time in hour:minute:second?

Anytime you have a question about a particular function in PHP, the easiest way to get quick answers is by visiting php.net, which has great documentation on all of the language's capabilities.

Looking up a function is easy, just visit http://php.net/<function name> and it will forward you to the appropriate place. For the date function, we'll visit http://php.net/date.

We immediately learn a couple things about this function by examining its signature:

string date ( string $format [, int $timestamp = time() ] )

First, it returns a string. That's what the first string in the above code means. Secondly, the first parameter is expected to be a string containing the format. There is an optional second parameter for passing in your own timestamp (to construct strings from some time other than now).

date("d-m-Y") // produces something like 03-12-2012

In this code, d represents the day of the month (with a leading 0 is necessary). m represents the month, again with a leading zero if necessary. And Y represents the full 4-digit year. All of these are documented in the aforementioned link.

To satisfy your request of getting the hours, minutes, and seconds, we need to give a quick look at the documentation to see which characters represents those particular units of time. When we do that, we find the following:

h   12-hour format of an hour with leading zeros    01 through 12
i   Minutes with leading zeros                      00 to 59
s   Seconds, with leading zeros                     00 through 59

With this in mind, we can no create a new format string:

date("d-m-Y h:i:s"); // produces something like 03-12-2012 03:29:13

Hope this is helpful, and I hope you find the documentation has benefiting to your development as I have to mine.

git stash apply version

Since version 2.11, it's pretty easy, you can use the N stack number instead of saying "stash@{n}". So now instead of using:

git stash apply "stash@{n}"

You can type:

git stash apply n

For example, in your list:

stash@{0}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{1}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{2}: WIP on design: eb65635... Email Adjust
stash@{3}: WIP on design: eb65635... Email Adjust

If you want to apply stash@{1} you could type:

git stash apply 1

Otherwise, you can use it even if you have some changes in your directory since 1.7.5.1, but you must be sure the stash won't overwrite your working directory changes if it does you'll get an error:

error: Your local changes to the following files would be overwritten by merge:
        file
Please commit your changes or stash them before you merge.

In versions prior to 1.7.5.1, it refused to work if there was a change in the working directory.


Git release notes:

The user always has to say "stash@{$N}" when naming a single element in the default location of the stash, i.e. reflogs in refs/stash. The "git stash" command learned to accept "git stash apply 4" as a short-hand for "git stash apply stash@{4}"

git stash apply" used to refuse to work if there was any change in the working tree, even when the change did not overlap with the change the stash recorded

Jquery checking success of ajax post

I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:

original Code block:

    post: function( url, data, callback, type ) {
    // shift arguments if data argument was omited
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = {};
    }

    return jQuery.ajax({
        type: "POST",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });  

Changed Code block:

        post: function (url, data, callback, failcallback, type) {
        if (type === undefined || type === null) {
            if (!jQuery.isFunction(failcallback)) { 
            type=failcallback
        }
        else if (!jQuery.isFunction(callback)) {
            type = callback
        }
        }
        if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
            failcallback = callback;

        }
        // shift arguments if data argument was omited
        if (jQuery.isFunction(data)) {
            type = type || callback;
            callback = data;
            data = {};

        }


        return jQuery.ajax({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            error:failcallback,
            dataType: type
        });
    },

This should help the one trying to catch error on $.Post in jquery.

Updated: Or there is another way to do this is :

   $.post(url,{},function(res){
        //To do write if call is successful
   }).error(function(p1,p2,p3){
             //To do Write if call is failed
          });

Notepad++ add to every line

Here is my answer. To add ');' to the end of each line I do 'Find What: $' and 'Replace with: \);' you need to do escape; enter image description here

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

I want to let everyone know that sometimes this error just is a result of some weird memory error. Restart your pc and go back into visual studio and it will be gone!! Bizarre! Try that before you start playing around with your web config file etc like I did!!!! ;-)

How to determine whether a year is a leap year?

The whole formula can be contained in a single expression:

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

print n, " is a leap year" if is_leap_year(n) else " is not a leap year"

How to use java.Set

It's difficult to answer this question with the information given. Nothing looks particularly wrong with how you are using HashSet.

Well, I'll hazard a guess that it's not a compilation issue and, when you say "getting errors," you mean "not getting the behavior [you] want."

I'll also go out on a limb and suggest that maybe your Block's equals an hashCode methods are not properly overridden.

Which is the preferred way to concatenate a string in Python?

While somewhat dated, Code Like a Pythonista: Idiomatic Python recommends join() over + in this section. As does PythonSpeedPerformanceTips in its section on string concatenation, with the following disclaimer:

The accuracy of this section is disputed with respect to later versions of Python. In CPython 2.5, string concatenation is fairly fast, although this may not apply likewise to other Python implementations. See ConcatenationTestCode for a discussion.

How to convert String to Date value in SAS?

As stated above, the simple answer is:

date = input(monyy,date9.);

with the addition of:

put date=yymmdd.;

The reason why this works, and what you did doesn't, is because of a common misunderstanding in SAS. DATE9. is an INFORMAT. In an INPUT statement, it provides the SAS interpreter with a set of translation commands it can send to the compiler to turn your text into the right numbers, which will then look like a date once the right FORMAT is applied. FORMATs are just visible representations of numbers (or characters). So by using YYMMDD., you confused the INPUT function by handing it a FORMAT instead of an INFORMAT, and probably got a helpful error that said:

Invalid argument to INPUT function at line... etc...

Which told you absolutely nothing about what to do next.

In summary, to represent your character date as a YYMMDD. In SAS you need to:

  1. change the INFORMAT - date = input(monyy,date9.);
  2. apply the FORMAT - put date=YYMMDD10.;

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

CSS3 Transition not working

If you have a <script> tag anywhere on your page (even in the HTML, even if it is an empty tag with a src), then a transition must be activated by some event (it won't fire automatically when the page loads).

How to remove from a map while iterating it?

I personally prefer this pattern which is slightly clearer and simpler, at the expense of an extra variable:

for (auto it = m.cbegin(), next_it = it; it != m.cend(); it = next_it)
{
  ++next_it;
  if (must_delete)
  {
    m.erase(it);
  }
}

Advantages of this approach:

  • the for loop incrementor makes sense as an incrementor;
  • the erase operation is a simple erase, rather than being mixed in with increment logic;
  • after the first line of the loop body, the meaning of it and next_it remain fixed throughout the iteration, allowing you to easily add additional statements referring to them without headscratching over whether they will work as intended (except of course that you cannot use it after erasing it).

/bin/sh: pushd: not found

A workaround for this would be to have a variable get the current working directory. Then you can cd out of it to do whatever, then when you need it, you can cd back in.

i.e.

oldpath=`pwd`
#do whatever your script does
...
...
...
# go back to the dir you wanted to pushd
cd $oldpath

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

VB.NET VERSION

Okay, so I have just spent several hours looking for a viable method for posting multiple parameters to an MVC 4 WEB API, but most of what I found was either for a 'GET' action or just flat out did not work. However, I finally got this working and I thought I'd share my solution.

  1. Use NuGet packages to download JSON-js json2 and Json.NET. Steps to install NuGet packages:

    (1) In Visual Studio, go to Website > Manage NuGet Packages... enter image description here

    (2) Type json (or something to that effect) into the search bar and find JSON-js json2 and Json.NET. Double-clicking them will install the packages into the current project.enter image description here

    (3) NuGet will automatically place the json file in ~/Scripts/json2.min.js in your project directory. Find the json2.min.js file and drag/drop it into the head of your website. Note: for instructions on installing .js (javascript) files, read this solution.

  2. Create a class object containing the desired parameters. You will use this to access the parameters in the API controller. Example code:

    Public Class PostMessageObj
    
    Private _body As String
    Public Property body As String
        Get
            Return _body
        End Get
        Set(value As String)
            _body = value
        End Set
    End Property
    
    
    Private _id As String
    Public Property id As String
        Get
            Return _id
        End Get
        Set(value As String)
            _id = value
        End Set
    End Property
    End Class
    
  3. Then we setup the actual MVC 4 Web API controller that we will be using for the POST action. In it, we will use Json.NET to deserialize the string object when it is posted. Remember to use the appropriate namespaces. Continuing with the previous example, here is my code:

    Public Sub PostMessage(<FromBody()> ByVal newmessage As String)
    
    Dim t As PostMessageObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PostMessageObj)(newmessage)
    
    Dim body As String = t.body
    Dim i As String = t.id
    
    End Sub
    
  4. Now that we have our API controller set up to receive our stringified JSON object, we can call the POST action freely from the client-side using $.ajax; Continuing with the previous example, here is my code (replace localhost+rootpath appropriately):

    var url = 'http://<localhost+rootpath>/api/Offers/PostMessage';
    var dataType = 'json'
    var data = 'nothn'
    var tempdata = { body: 'this is a new message...Ip sum lorem.',
        id: '1234'
    }
    var jsondata = JSON.stringify(tempdata)
    $.ajax({
        type: "POST",
        url: url,
        data: { '': jsondata},
        success: success(data),
        dataType: 'text'
    });
    

As you can see we are basically building the JSON object, converting it into a string, passing it as a single parameter, and then rebuilding it via the JSON.NET framework. I did not include a return value in our API controller so I just placed an arbitrary string value in the success() function.


Author's notes

This was done in Visual Studio 2010 using ASP.NET 4.0, WebForms, VB.NET, and MVC 4 Web API Controller. For anyone having trouble integrating MVC 4 Web API with VS2010, you can download the patch to make it possible. You can download it from Microsoft's Download Center.

Here are some additional references which helped (mostly in C#):

How to place the ~/.composer/vendor/bin directory in your PATH?

To solve this problem make sure you find the path of composer.phar first

example mine is something like this

alias composer="php /Users/Your-username/composer.phar"

Go to cd Users > Your user > Command ls and see if composer.phar is there if yes then add the above line to your .bash_profile. Make sure you change the username to your own.

Hope this help you out

How can I remove the last character of a string in python?

For a path use os.path.abspath

import os    
print os.path.abspath(my_file_path)

Export to CSV via PHP

I personally use this function to create CSV content from any array.

function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

Then you can make your user download that file using something like:

function download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

Usage example:

download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($array);
die();

How do you read a file into a list in Python?

Two ways to read file into list in python (note these are not either or) -

  1. use of with - supported from python 2.5 and above
  2. use of list comprehensions

1. use of with

This is the pythonic way of opening and reading files.

#Sample 1 - elucidating each step but not memory efficient
lines = []
with open("C:\name\MyDocuments\numbers") as file:
    for line in file: 
        line = line.strip() #or some other preprocessing
        lines.append(line) #storing everything in memory!

#Sample 2 - a more pythonic and idiomatic way but still not memory efficient
with open("C:\name\MyDocuments\numbers") as file:
    lines = [line.strip() for line in file]

#Sample 3 - a more pythonic way with efficient memory usage. Proper usage of with and file iterators. 
with open("C:\name\MyDocuments\numbers") as file:
    for line in file:
        line = line.strip() #preprocess line
        doSomethingWithThisLine(line) #take action on line instead of storing in a list. more memory efficient at the cost of execution speed.

the .strip() is used for each line of the file to remove \n newline character that each line might have. When the with ends, the file will be closed automatically for you. This is true even if an exception is raised inside of it.

2. use of list comprehension

This could be considered inefficient as the file descriptor might not be closed immediately. Could be a potential issue when this is called inside a function opening thousands of files.

data = [line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')]

Note that file closing is implementation dependent. Normally unused variables are garbage collected by python interpreter. In cPython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpreter, like Jython or Iron Python, there may be a delay.

How to check if user input is not an int value

you have following errors which in turn is causing you that exception, let me explain it

this is your existing code:

if(!scan.hasNextInt()) {
        System.out.println("Invalid input!");
        System.out.print("Enter an integer: ");
        usrInput= sc.nextInt();
    }

in the above code if(!scan.hasNextInt()) will become true only when user input contains both characters as well as integers like your input adfd 123.

but you are trying to read only integers inside the if condition using usrInput= sc.nextInt();. Which is incorrect,that's what is throwing Exception in thread "main" java.util.InputMismatchException.

so correct code should be

 if(!scan.hasNextInt()) {
            System.out.println("Invalid input!");
            System.out.print("Enter an integer: ");
            sc.next(); 
            continue;
        }

in the above code sc.next() will help to read new input from user and continue will help in executing same if condition(i.e if(!scan.hasNextInt())) again.

Please use code in my first answer to build your complete logic.let me know if you need any explanation on it.

Microsoft Excel ActiveX Controls Disabled?

I'm an Excel developer, and I definitely felt the pain when this happened. Fortunately, I was able to find a workaround by renaming the MSForms.exd files in VBA even when Excel is running, which also can fix the issue. Excel developers who need to distribute their spreadsheets can add the following VBA code to their spreadsheets to make them immune to the MS update.

Place this code in any module.

Public Sub RenameMSFormsFiles() 
  Const tempFileName As String = "MSForms - Copy.exd"  
  Const msFormsFileName As String = "MSForms.exd"  
  On Error Resume Next 

  'Try to rename the C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\MSForms.exd file  
  RenameFile Environ("TEMP") & "\Excel8.0\" & msFormsFileName, Environ("TEMP") & "\Excel8.0\" & tempFileName 
  'Try to rename the C:\Users\[user.name]\AppData\Local\Temp\VBE\MSForms.exd file  
  RenameFile Environ("TEMP") & "\VBE\" & msFormsFileName, Environ("TEMP") & "\VBE\" & tempFileName 
End Sub  

Private Sub RenameFile(fromFilePath As String, toFilePath As String) 
  If CheckFileExist(fromFilePath) Then 
      DeleteFile toFilePath  
      Name fromFilePath As toFilePath  
  End If  
End Sub

Private Function CheckFileExist(path As String) As Boolean 
  CheckFileExist = (Dir(path) <> "")  
End Function  

Private Sub DeleteFile(path As String) 
  If CheckFileExist(path) Then 
      SetAttr path, vbNormal  
      Kill path  
  End If  
End Sub    

The RenameMSFormsFiles subroutine tries to rename the MSForms.exd files in the C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\ and C:\Users\[user.name]\AppData\Local\Temp\VBE\ folders to MSForms - Copy.exd.

Then call the RenameMSFormsFiles subroutine at the very beginning of the Workbook_Open event.

Private Sub Workbook_Open() 
  RenameMSFormsFiles  
End Sub

The spreadsheet will try to rename the MSForms.exd files when it opens. Obviously, this is not a perfect fix:

  1. The affected user will still experience the ActiveX control errors when running the VBA code the very first time opening the spreadsheet. Only after executing the VBA code once and restarting Excel, the issue is fixed. Normally when a user encounters a broken spreadsheet, the knee-jerk reaction is to close Excel and try to open the spreadsheet again. :)
  2. The MSForms.exd files are renamed every time the spreadsheet opens, even when there's no issue with the MSForms.exd files. But the spreadsheet will work just fine.

At least for now, Excel developers can continue to distribute their work with this workaround until Microsoft releases a fix.

I've posted this solution here.

TypeError: $ is not a function when calling jQuery function

Also, I find the good solution for use jQuery noConflict mode.

(function($){

  $(document).ready(function(){
      // write code here
  });

  // or also you can write jquery code like this

  jQuery(document).ready(function(){
      // write code here
  });

})(jQuery);

I found this solution from here TryVary.com.

Event system in Python

Another handy package is events. It encapsulates the core to event subscription and event firing and feels like a "natural" part of the language. It seems similar to the C# language, which provides a handy way to declare, subscribe to and fire events. Technically, an event is a "slot" where callback functions (event handlers) can be attached to - a process referred to as subscribing to an event.

# Define a callback function
def something_changed(reason):
    print "something changed because %s" % reason

# Use events module to create an event and register one or more callback functions
from events import Events
events = Events()
events.on_change += something_changed

When the event is fired, all attached event handlers are invoked in sequence. To fire the event, perform a call on the slot:

events.on_change('it had to happen')

This will output:

'something changed because it had to happen'

More documentation can be found in the github repo or the documentation.

Windows service on Local Computer started and then stopped error

You may want to unit test the initialization - but because it's in the OnStart method this is near to impossible. I would suggest moving the initialization code out into a separate class so that it can be tested or at least re-used in a form tester.

Secondly to add some logging (using Log4Net or similar) and add some verbose logging so that you can see details about runtime errors. Examples of runtime errors would be AccessViolation etc. especially if your service is running without enough privileges to access the config files.

How can I change the language (to english) in Oracle SQL Developer?

On MAC High Sierra (10.13.6)

cd /Users/vkrishna/.sqldeveloper/18.2.0

nano product.conf

on the last line add

AddVMOption -Duser.language=en

Save the file and restart.

=======================================

If you are using standalone Oracle Data Modeller

find ~/ -name "datamodeler.conf"

and edit this file

cd /Users/vkrishna//Desktop/OracleDataModeler-18.2.0.179.0756.app/Contents/Resources/datamodeler/datamodeler/bin/

Add somewhere in the last

AddVMOption -Duser.language=en

save and restart, done!

dictionary update sequence element #0 has length 3; 2 is required

One of the fast ways to create a dict from equal-length tuples:

>>> t1 = (a,b,c,d)
>>> t2 = (1,2,3,4)
>>> dict(zip(t1, t2))
{'a':1, 'b':2, 'c':3, 'd':4, }

Extract MSI from EXE

For InstallShield MSI based projects I have found the following to work:

setup.exe /s /x /b"C:\FolderInWhichMSIWillBeExtracted" /v"/qn"

This command will lead to an extracted MSI in a directory you can freely specify and a silently failed uninstall of the product.

The command line basically tells the setup.exe to attempt to uninstall the product (/x) and do so silently (/s). While doing that it should extract the MSI to a specific location (/b).

The /v command passes arguments to Windows Installer, in this case the /qn argument. The /qn argument disables any GUI output of the installer.

How to load data to hive from HDFS without removing the source file?

An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.

You can use ALTER TABLE command with 'LOCATION' option. Here is below required command

ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'

The only condition here is, the location should be a directory instead of file.

Hope this will solve the problem.

MySQL - How to select rows where value is in array?

By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:

$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';

If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:

$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';

Laravel eloquent update record without loading from database

You can also use firstOrCreate OR firstOrNew

// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]); 

// update record
$post->title = "Updated title";
$post->save();

Hope it will help you :)

How to parse dates in multiple formats using SimpleDateFormat

For the modern answer I am ignoring the requirement to use SimpleDateFormat. While using this class for parsing was a good idea in 2010 when this question was asked, it is now long outdated. The replacement, DateTimeFormatter, came out in 2014. The idea in the following is pretty much the same as in the accepted answer.

private static DateTimeFormatter[] parseFormatters = Stream.of("M/yy", "M/y", "M/d/y", "M-d-y")
        .map(DateTimeFormatter::ofPattern)
        .toArray(DateTimeFormatter[]::new);

public static YearMonth parseYearMonth(String input) {
    for (DateTimeFormatter formatter : parseFormatters) {
        try {
            return YearMonth.parse(input, formatter);
        } catch (DateTimeParseException dtpe) {
            // ignore, try next format
        }
    }
    throw new IllegalArgumentException("Could not parse " + input);
}

This parses each of the input strings from the question into a year-month of 2009-09. It’s important to try the two-digit year first since "M/y" could also parse 9/09, but into 0009-09 instead.

A limitation of the above code is it ignores the day-of-month from the strings that have one, like 9/1/2009. Maybe it’s OK as long as most formats have only month and year. To pick it up, we’d have to try LocalDate.parse() rather then YearMonth.parse() for the formats that include d in the pattern string. Surely it can be done.

'list' object has no attribute 'shape'

If you have list, you can print its shape as if it is converted to array

import numpy as np
print(np.asarray(X).shape)

What's default HTML/CSS link color?

For me, on Chrome (updated June 2018) the color for an unvisited link is #2779F6. You can always get this by zooming in really close, taking a screenshot, and visiting a website like html-color-codes.info that will convert a screenshot to a color code.

How to add font-awesome to Angular 2 + CLI project

Edit: I'm using angular ^4.0.0 and Electron ^1.4.3

If you have issues with ElectronJS or similar and have a sort of 404 error, a possible workaround is to uedit your webpack.config.js, by adding (and by assuming that you have the font-awesome node module installed through npm or in the package.json file):

new CopyWebpackPlugin([
     { from: 'node_modules/font-awesome/fonts', to: 'assets' },
     { from: 'src/assets', to: 'assets' }
]),

Note that the webpack configuration I'm using has src/app/dist as output, and, in dist, an assets folder is created by webpack:

// our angular app
entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/app/app',
},

// Config for our build files
output: {
    path: helpers.root('src/app/dist'),
    filename: '[name].js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
},

So basically, what is currently happening is:

  • Webpack is copying the fonts folder to the dev assets folder.
  • Webpack is copying the dev assets folder to the dist assets folder

Now, when the build process will be finished, the application will need to look for the .scss file and the folder containing the icons, resolving them properly. To resolve them, I've used this in my webpack config:

// support for fonts
{
    test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
    loader: 'file-loader?name=dist/[name]-[hash].[ext]'
},

Finally, in the .scss file, I'm importing the font-awesome .scss and defining the path of the fonts, which is, again, dist/assets/font-awesome/fonts. The path is dist because in my webpack.config the output.path is set as helpers.root('src/app/dist');

So, in app.scss:

$fa-font-path: "dist/assets/font-awesome/fonts";
@import "~font-awesome/scss/font-awesome.scss";

Note that, in this way, it will define the font path (used later in the .scss file) and import the .scss file using ~font-awesome to resolve the font-awesome path in node_modules.

This is quite tricky, but it's the only way I've found to get around the 404 error issue with Electron.js

How to get the first day of the current week and month?

In this case:

// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY);  <---- is the current hour not 0 hour
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

So the Calendar.HOUR_OF_DAY returns 8, 9, 12, 15, 18 as the current running hour. I think will be better change such line by:

c.set(Calendar.HOUR_OF_DAY,0);

this way the day always begin at 0 hour

Row count with PDO

As I wrote previously in an answer to a similar question, the only reason mysql_num_rows() worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you.

So in PDO, your options are:

  1. Use PDO's fetchAll() function to fetch all the rows into an array, then use count() on it.
  2. Do an extra query to SELECT COUNT(*), as karim79 suggested.
  3. Use MySQL's FOUND_ROWS() function UNLESS the query had SQL_CALC_FOUND_ROWS or a LIMIT clause (in which case the number of rows that were returned by the query and the number returned by FOUND_ROWS() may differ). However, this function is deprecated and will be removed in the future.

How to write to an existing excel file without overwriting data (using pandas)?

Solution by @MaxU worked very well. I have just one suggestion:

If truncate_sheet=True is specified than "startrow" should NOT be retained from existing sheet. I suggest:

        if startrow is None and sheet_name in writer.book.sheetnames:
            if not truncate_sheet: # truncate_sheet would use startrow if provided (or zero below)
                startrow = writer.book[sheet_name].max_row

Detect if an element is visible with jQuery

There's no need, just use fadeToggle() on the element:

$('#testElement').fadeToggle('fast');

Here's a demo.

Simple PHP calculator

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Calculator</title> 
    </head>
<body>

    <form method="GET">
    <h1>Calculator</h1>
    <p>This is a calculator made by Hau Teen Yee Fabrice and is free to use.</p>
        <ul>
     <ol> Multiplication: * </ol>
     <ol> Substraction: - </ol>
     <ol> Division: / </ol>
     <ol> Addition: + </ol>
        </ul>
     <p>Enter first number:</p>
        <input type="text" name="cal1">
        <p>Enter second number:</p>
        <input type="text" name="cal2">
        <p>Enter the calculator symbol</p>
        <input type="text" name="symbol">
        <button>Calculate</button>
    </form>
    <?php
    $cal1= $_GET['cal1'];
    $cal2= $_GET['cal2'];
    $symbol =$_GET['symbol'];

    if($symbol == '+')
    {
        $add = $cal1 + $cal2;
        echo "Addition is:".$add;
    }
    else if($symbol == '-')
    {
        $subs = $cal1 - $cal2;
        echo "Substraction is:".$subs;
    }
     else if($symbol == '*')
    {
        $mul = $cal1 * $cal2;
        echo "Multiply is:".$mul;
    }
    else if($symbol == '/')
    {
        $div = $cal1 / $cal2;
        echo "Division is:".$div;
    }
      else
    { 
        echo "Oops ,something wrong in your code son";
    }
    ?>
    </body> 
</html>

How to set web.config file to show full error message

not sure if it'll work in your scenario, but try adding the following to your web.config under <system.web>:

  <system.web>
    <customErrors mode="Off" />
  ...
  </system.web>

works in my instance.

also see:

CustomErrors mode="Off"

RedirectToAction with parameter

....

int parameter = Convert.ToInt32(Session["Id"].ToString());

....

return RedirectToAction("ActionName", new { Id = parameter });

jQuery limit to 2 decimal places

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

Posting this to help someone.

Symptom:

channel 2: open failed: connect failed: Connection refused
debug1: channel 2: free: direct-tcpip:
   listening port 8890 for 169.254.76.1 port 8890,
   connect from ::1 port 52337 to ::1 port 8890, nchannels 8

My scenario; i had to use the remote server as a bastion host to connect elsewhere. Final Destination/Target: 169.254.76.1, port 8890. Through intermediary server with public ip: ec2-54-162-180-7.compute-1.amazonaws.com

SSH local port forwarding command:

ssh -i ~/keys/dev.tst -vnNT -L :8890:169.254.76.1:8890
[email protected]

What the problem was: There was no service bound on port 8890 in the target host. i had forgotten to start the service.

How did i trouble shoot:

SSH into bastion host and then do curl.

Hope this helps.

jQuery delete confirmation box

function deleteItem(this) {
    if (confirm("Are you sure?")) {
          $(this).remove();
    }
    return false;
}

You can also use jquery modalin same way

JQuery version

Are you sure?
  $(document).ready(function() {
    $("#dialog-box").dialog({
      autoOpen: false,
      modal: true
    });

  $(".close").click(function(e) {
    var currentElem = $(this);
    $("#dialog-box").dialog({
      buttons : {
        "Confirm" : function() {
          currentElem.remove()
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

    $("#dialog-box").dialog("open");
  });
});

Convert a row of a data frame to vector

If you don't want to change to numeric you can try this.

> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6

In Java, how to append a string more efficiently?

java.lang.StringBuilder. Use int constructor to create an initial size.

Fastest way to download a GitHub project

Use

git clone https://github.com/<path>/repository
or
git clone https://github.com/<path>/<master>.git

examples

git clone https://github.com/spring-projects/spring-data-graph-examples
git clone https://github.com/spring-projects/spring-data-graph-examples.git

Resize Google Maps marker icon image

As mentionned in comments, this is the updated solution in favor of Icon object with documentation.

Use Icon object

var icon = {
    url: "../res/sit_marron.png", // url
    scaledSize: new google.maps.Size(50, 50), // scaled size
    origin: new google.maps.Point(0,0), // origin
    anchor: new google.maps.Point(0, 0) // anchor
};

 posicion = new google.maps.LatLng(latitud,longitud)
 marker = new google.maps.Marker({
  position: posicion,
  map: map,
  icon: icon
 });

is there a 'block until condition becomes true' function in java?

Lock-free solution(?)

I had the same issue, but I wanted a solution that didn't use locks.

Problem: I have at most one thread consuming from a queue. Multiple producer threads are constantly inserting into the queue and need to notify the consumer if it's waiting. The queue is lock-free so using locks for notification causes unnecessary blocking in producer threads. Each producer thread needs to acquire the lock before it can notify the waiting consumer. I believe I came up with a lock-free solution using LockSupport and AtomicReferenceFieldUpdater. If a lock-free barrier exists within the JDK, I couldn't find it. Both CyclicBarrier and CoundDownLatch use locks internally from what I could find.

This is my slightly abbreviated code. Just to be clear, this code will only allow one thread to wait at a time. It could be modified to allow for multiple awaiters/consumers by using some type of atomic collection to store multiple owner (a ConcurrentMap may work).

I have used this code and it seems to work. I have not tested it extensively. I suggest you read the documentation for LockSupport before use.

/* I release this code into the public domain.
 * http://unlicense.org/UNLICENSE
 */

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;

/**
 * A simple barrier for awaiting a signal.
 * Only one thread at a time may await the signal.
 */
public class SignalBarrier {
    /**
     * The Thread that is currently awaiting the signal.
     * !!! Don't call this directly !!!
     */
    @SuppressWarnings("unused")
    private volatile Thread _owner;

    /** Used to update the owner atomically */
    private static final AtomicReferenceFieldUpdater<SignalBarrier, Thread> ownerAccess =
        AtomicReferenceFieldUpdater.newUpdater(SignalBarrier.class, Thread.class, "_owner");

    /** Create a new SignalBarrier without an owner. */
    public SignalBarrier() {
        _owner = null;
    }

    /**
     * Signal the owner that the barrier is ready.
     * This has no effect if the SignalBarrer is unowned.
     */
    public void signal() {
        // Remove the current owner of this barrier.
        Thread t = ownerAccess.getAndSet(this, null);

        // If the owner wasn't null, unpark it.
        if (t != null) {
            LockSupport.unpark(t);
        }
    }

    /**
     * Claim the SignalBarrier and block until signaled.
     *
     * @throws IllegalStateException If the SignalBarrier already has an owner.
     * @throws InterruptedException If the thread is interrupted while waiting.
     */
    public void await() throws InterruptedException {
        // Get the thread that would like to await the signal.
        Thread t = Thread.currentThread();

        // If a thread is attempting to await, the current owner should be null.
        if (!ownerAccess.compareAndSet(this, null, t)) {
            throw new IllegalStateException("A second thread tried to acquire a signal barrier that is already owned.");
        }

        // The current thread has taken ownership of this barrier.
        // Park the current thread until the signal. Record this
        // signal barrier as the 'blocker'.
        LockSupport.park(this);
        // If a thread has called #signal() the owner should already be null.
        // However the documentation for LockSupport.unpark makes it clear that
        // threads can wake up for absolutely no reason. Do a compare and set
        // to make sure we don't wipe out a new owner, keeping in mind that only
        // thread should be awaiting at any given moment!
        ownerAccess.compareAndSet(this, t, null);

        // Check to see if we've been unparked because of a thread interrupt.
        if (t.isInterrupted())
            throw new InterruptedException();
    }

    /**
     * Claim the SignalBarrier and block until signaled or the timeout expires.
     *
     * @throws IllegalStateException If the SignalBarrier already has an owner.
     * @throws InterruptedException If the thread is interrupted while waiting.
     *
     * @param timeout The timeout duration in nanoseconds.
     * @return The timeout minus the number of nanoseconds that passed while waiting.
     */
    public long awaitNanos(long timeout) throws InterruptedException {
        if (timeout <= 0)
            return 0;
        // Get the thread that would like to await the signal.
        Thread t = Thread.currentThread();

        // If a thread is attempting to await, the current owner should be null.
        if (!ownerAccess.compareAndSet(this, null, t)) {
            throw new IllegalStateException("A second thread tried to acquire a signal barrier is already owned.");
        }

        // The current thread owns this barrier.
        // Park the current thread until the signal. Record this
        // signal barrier as the 'blocker'.
        // Time the park.
        long start = System.nanoTime();
        LockSupport.parkNanos(this, timeout);
        ownerAccess.compareAndSet(this, t, null);
        long stop = System.nanoTime();

        // Check to see if we've been unparked because of a thread interrupt.
        if (t.isInterrupted())
            throw new InterruptedException();

        // Return the number of nanoseconds left in the timeout after what we
        // just waited.
        return Math.max(timeout - stop + start, 0L);
    }
}

To give a vague example of usage, I'll adopt james large's example:

SignalBarrier barrier = new SignalBarrier();

Consumer thread (singular, not plural!):

try {
    while(!conditionIsTrue()) {
        barrier.await();
    }
    doSomethingThatRequiresConditionToBeTrue();
} catch (InterruptedException e) {
    handleInterruption();
}

Producer thread(s):

doSomethingThatMakesConditionTrue();
barrier.signal();

how to specify new environment location for conda create

like Paul said, use

conda create --prefix=/users/.../yourEnvName python=x.x

if you are located in the folder in which you want to create your virtual environment, just omit the path and use

conda create --prefix=yourEnvName python=x.x

conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with

source activate yourEnvName

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

can use html5 mark tag within paragraph and heading tag.

_x000D_
_x000D_
<p>lorem ipsum <mark>Highlighted Text</mark> dolor sit.</p>
_x000D_
_x000D_
_x000D_

Placeholder in IE9

A bit late to the party but I use my tried and trusted JS that takes advantage of Modernizr. Can be copy/pasted and applied to any project. Works every time:

// Placeholder fallback
if(!Modernizr.input.placeholder){

    $('[placeholder]').focus(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur();
    $('[placeholder]').parents('form').submit(function() {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });

}

Setting the MySQL root user password on OS X

I think this should work :

ALTER USER 'root'@'localhost' IDENTIFIED BY 'YOURNEWPASSWORD'

(Note that you should probably replace root with your username if it isn't root)

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

You could simply create a special Activity for debugging purpose:

@SuppressWarnings("unchecked")
public void loadPreferences() {
// create a textview with id (tv_pref) in Layout.
TextView prefTextView;
prefTextView = (TextView) findViewById(R.id.tv_pref);
    Map<String, ?> prefs = PreferenceManager.getDefaultSharedPreferences(
            context).getAll();
    for (String key : prefs.keySet()) {
        Object pref = prefs.get(key);
        String printVal = "";
        if (pref instanceof Boolean) {
            printVal =  key + " : " + (Boolean) pref;
        }
        if (pref instanceof Float) {
            printVal =  key + " : " + (Float) pref;
        }
        if (pref instanceof Integer) {
            printVal =  key + " : " + (Integer) pref;
        }
        if (pref instanceof Long) {
            printVal =  key + " : " + (Long) pref;
        }
        if (pref instanceof String) {
            printVal =  key + " : " + (String) pref;
        }
        if (pref instanceof Set<?>) {
            printVal =  key + " : " + (Set<String>) pref;
        }
        // Every new preference goes to a new line
        prefTextView.append(printVal + "\n\n");     
    }
}
// call loadPreferences() in the onCreate of your Activity.

Process to convert simple Python script into Windows executable

you may want to see if your app can run under IronPython. If so, you can compile it to an exe http://www.codeplex.com/IronPython

HQL Hibernate INNER JOIN

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;

List<Address> addList=new ArrayList<Address>();


@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getEmpName() {
    return empName;
}
public void setEmpName(String empName) {
    this.empName = empName;
}

@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
    return addList;
}

public void setAddList(List<Address> addList) {
    this.addList = addList;
}
}

We have two entities Employee and Address with One to Many relationship.

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="address")
public class Address implements Serializable{

private static final long serialVersionUID = 1L;

private int address_id;
private String address;
Employee employee;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
    return address_id;
}
public void setAddress_id(int address_id) {
    this.address_id = address_id;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
    return employee;
}
public void setEmployee(Employee employee) {
    this.employee = employee;
}
}

By this way we can implement inner join between two tables

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class Main {

public static void main(String[] args) {
    saveEmployee();

    retrieveEmployee();

}

private static void saveEmployee() {
    Employee employee=new Employee();
    Employee employee1=new Employee();
    Employee employee2=new Employee();
    Employee employee3=new Employee();

    Address address=new Address();
    Address address1=new Address();
    Address address2=new Address();
    Address address3=new Address();

    address.setAddress("1485,Sector 42 b");
    address1.setAddress("1485,Sector 42 c");
    address2.setAddress("1485,Sector 42 d");
    address3.setAddress("1485,Sector 42 a");

    employee.setEmpName("Varun");
    employee1.setEmpName("Krishan");
    employee2.setEmpName("Aasif");
    employee3.setEmpName("Dut");

    address.setEmployee(employee);
    address1.setEmployee(employee1);
    address2.setEmployee(employee2);
    address3.setEmployee(employee3);

    employee.getAddList().add(address);
    employee1.getAddList().add(address1);
    employee2.getAddList().add(address2);
    employee3.getAddList().add(address3);

    Session session=HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();

    session.save(employee);
    session.save(employee1);
    session.save(employee2);
    session.save(employee3);
    session.getTransaction().commit();
    session.close();
}

private static void retrieveEmployee() {
    try{

    String sqlQuery="select e from Employee e inner join e.addList";

    Session session=HibernateUtil.getSessionFactory().openSession();

    Query query=session.createQuery(sqlQuery);

    List<Employee> list=query.list();

     list.stream().forEach((p)->{System.out.println(p.getEmpName());});     
    session.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.

 public class HibernateUtil {
 private static SessionFactory sessionFactory ;
 static {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(Employee.class);
    configuration.addAnnotatedClass(Address.class);
                  configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");                                
    configuration.setProperty("hibernate.connection.username", "root");     
    configuration.setProperty("hibernate.connection.password", "root");
    configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty(" hibernate.connection.pool_size", "10");


   // configuration
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
} 

How to convert text to binary code in JavaScript?

var PADDING = "00000000"

var string = "TEST"
var resultArray = []

for (var i = 0; i < string.length; i++) {
  var compact = string.charCodeAt(i).toString(2)
  var padded  = compact.substring(0, PADDING.length - compact.length) + compact

  resultArray.push(padded)
}

console.log(resultArray.join(" "))

Null vs. False vs. 0 in PHP

False and 0 are conceptually similar, i.e. they are isomorphic. 0 is the initial value for the algebra of natural numbers, and False is the initial value for the Boolean algebra.

In other words, 0 can be defined as the number which, when added to some natural number, yields that same number:

x + 0 = x

Similarly, False is a value such that a disjunction of it and any other value is that same value:

x || False = x

Null is conceptually something totally different. Depending on the language, there are different semantics for it, but none of them describe an "initial value" as False and 0 are. There is no algebra for Null. It pertains to variables, usually to denote that the variable has no specific value in the current context. In most languages, there are no operations defined on Null, and it's an error to use Null as an operand. In some languages, there is a special value called "bottom" rather than "null", which is a placeholder for the value of a computation that does not terminate.

I've written more extensively about the implications of NULL elsewhere.

Why I got " cannot be resolved to a type" error?

for some reason, my.demo.service has the same level as src/ in eclise project explorer view. After I move my.demo.service under src/, it is fine. Seems I should not create new package in "Project Explorer" view in Eclipse...

But thank you for your response:)

Return array in a function

As above mentioned paths are correct. But i think if we just return a local array variable of a function sometimes it returns garbage values as its elements.

in-order to avoid that i had to create the array dynamically and proceed. Which is something like this.

int* func()
{
  int* Arr = new int[100];
  return Arr;
}

int main()
{
  int* ArrResult = func();
  cout << ArrResult[0] << " " << ArrResult[1] << endl;
  return 0;
} 




How to make a gap between two DIV within the same column

I know this was an old answer, but i would like to share my simple solution.

give style="margin-top:5px"

<div style="margin-top:5px">
  div 1
</div>
<div style="margin-top:5px">
  div2 elements
</div> 
div3 elements

Differences between time complexity and space complexity?

The time and space complexities are not related to each other. They are used to describe how much space/time your algorithm takes based on the input.

  • For example when the algorithm has space complexity of:

    • O(1) - constant - the algorithm uses a fixed (small) amount of space which doesn't depend on the input. For every size of the input the algorithm will take the same (constant) amount of space. This is the case in your example as the input is not taken into account and what matters is the time/space of the print command.
    • O(n), O(n^2), O(log(n))... - these indicate that you create additional objects based on the length of your input. For example creating a copy of each object of v storing it in an array and printing it after that takes O(n) space as you create n additional objects.
  • In contrast the time complexity describes how much time your algorithm consumes based on the length of the input. Again:

    • O(1) - no matter how big is the input it always takes a constant time - for example only one instruction. Like

      function(list l) {
          print("i got a list");
      }
      
    • O(n), O(n^2), O(log(n)) - again it's based on the length of the input. For example

      function(list l) {
           for (node in l) {
              print(node);
          }
      }
      

Note that both last examples take O(1) space as you don't create anything. Compare them to

function(list l) {
    list c;
    for (node in l) {
        c.add(node);
    }
}

which takes O(n) space because you create a new list whose size depends on the size of the input in linear way.

Your example shows that time and space complexity might be different. It takes v.length * print.time to print all the elements. But the space is always the same - O(1) because you don't create additional objects. So, yes, it is possible that an algorithm has different time and space complexity, as they are not dependent on each other.

How to delete an element from an array in C#

Removing from an array itself is not simple, as you then have to deal with resizing. This is one of the great advantages of using something like a List<int> instead. It provides Remove/RemoveAt in 2.0, and lots of LINQ extensions for 3.0.

If you can, refactor to use a List<> or similar.

Jquery $.ajax fails in IE on cross domain calls

I have the same problem in IE, I solved it by replacing:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

To

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

So basically upgrade your jquery version.

MINGW64 "make build" error: "bash: make: command not found"

You have to install mingw-get and after that you can run mingw-get install msys-make to have the command make available.

Here is a link for what you want http://www.mingw.org/wiki/getting_started

How to dynamic new Anonymous Class?

You can create an ExpandoObject like this:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

And after casting it to dynamic, those values will look like properties:

dynamic d = expando;
Console.WriteLine(d.Name);

However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:

d.GetType().GetProperty("Name") 

ASP.Net 2012 Unobtrusive Validation with jQuery

All the validator error has been solved by this

 <appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>

Error must be vanished enjoy....

Passing parameters in rails redirect_to

routes.rb

 match 'controller_name/action_name' => 'controller_name#action_name', via: [:get, :post], :as => :abc

Any controller you want to redirect with parameters are given below:

redirect_to abc_path(@abc, id: @id), :notice => "message fine" 

TypeError: 'NoneType' object is not iterable in Python

Another thing that can produce this error is when you are setting something equal to the return from a function, but forgot to actually return anything.

Example:

def foo(dict_of_dicts):
    for key, row in dict_of_dicts.items():
        for key, inner_row in row.items():
            Do SomeThing
    #Whoops, forgot to return all my stuff

return1, return2, return3 = foo(dict_of_dicts)

This is a little bit of a tough error to spot because the error can also be produced if the row variable happens to be None on one of the iterations. The way to spot it is that the trace fails on the last line and not inside the function.

If your only returning one variable from a function, I am not sure if the error would be produced... I suspect error "'NoneType' object is not iterable in Python" in this case is actually implying "Hey, I'm trying to iterate over the return values to assign them to these three variables in order but I'm only getting None to iterate over"

How to convert C# nullable int to int

A simple conversion between v1 and v2 is not possible because v1 has a larger domain of values than v2. It's everything v1 can hold plus the null state. To convert you need to explicitly state what value in int will be used to map the null state. The simplest way to do this is the ?? operator

v2 = v1 ?? 0;  // maps null of v1 to 0

This can also be done in long form

int v2;
if (v1.HasValue) {
  v2 = v1.Value;
} else {
  v2 = 0;
}

PHP function to get the subdomain of a URL

We use this function to handle multiple subdomain and multiple tld also handle ip and localhost

function analyse_host($_host)
    {
        $my_host   = explode('.', $_host);
        $my_result = ['subdomain' => null, 'root' => null, 'tld' => null];

        // if host is ip, only set as root
        if(filter_var($_host, FILTER_VALIDATE_IP))
        {
            // something like 127.0.0.5
            $my_result['root'] = $_host;
        }
        elseif(count($my_host) === 1)
        {
            // something like localhost
            $my_result['root'] = $_host;
        }
        elseif(count($my_host) === 2)
        {
            // like jibres.com
            $my_result['root'] = $my_host[0];
            $my_result['tld']  = $my_host[1];
        }
        elseif(count($my_host) >= 3)
        {
            // some conditons like
            // ermile.ac.ir
            // ermile.jibres.com
            // ermile.jibres.ac.ir
            // a.ermile.jibres.ac.ir

            // get last one as tld
            $my_result['tld']  = end($my_host);
            array_pop($my_host);

            // check last one after remove is probably tld or not
            $known_tld    = ['com', 'org', 'net', 'gov', 'co', 'ac', 'id', 'sch', 'biz'];
            $probably_tld = end($my_host);
            if(in_array($probably_tld, $known_tld))
            {
                $my_result['tld'] = $probably_tld. '.'. $my_result['tld'];
                array_pop($my_host);
            }

            $my_result['root'] = end($my_host);
            array_pop($my_host);

            // all remain is subdomain
            if(count($my_host) > 0)
            {
                $my_result['subdomain'] = implode('.', $my_host);
            }
        }

        return $my_result;
    }

Casting objects in Java

Casting is necessary to tell that you are calling a child and not a parent method. So it's ever downward. However if the method is already defined in the parent class and overriden in the child class, you don't any cast. Here an example:

class Parent{
   void method(){ System.out.print("this is the parent"); }
}

class Child extends Parent{
   @override
   void method(){ System.out.print("this is the child"); }
}
...
Parent o = new Child();
o.method();
((Child)o).method();  

The two method call will both print : "this is the child".

How do I start Mongo DB from Windows?

It is showing admin web console waiting for connections on port 28017.

The above message means that mongodb has started successfully and is listening on port 28017.

You can use the mongo shell(mongo.exe) to connect to the mongoDB and perform db operations.

There are several GUI tools available for MongoDB like MongoVUE, etc.

Search and replace a particular string in a file using Perl

Quick and dirty:

#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/<PREF>/ABCD/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);

Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.

Is the buildSessionFactory() Configuration method deprecated in Hibernate

here are many APIs deprecated in the hibernate core framework.

we have created the session factory as below:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be:

  1. Configuration configuration = new Configuration().configure();

  2. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());

  3. SessionFactory factory = configuration.buildSessionFactory(builder.build());

Class ServiceRegistryBuilder is replaced by StandardServiceRegistryBuilder from 4.3.0. It looks like there will be lot of changes in the 5.0 release. Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0.

Take a char input from the Scanner

You can solve this problem, of "grabbing keyboard input one char at a time" very simply. Without having to use a Scanner all and also not clearing the input buffer as a side effect, by using this.

char c = (char)System.in.read();

If all you need is the same functionality as the C language "getChar()" function then this will work great. The Big advantage of the "System.in.read()" is the buffer is not cleared out after each char your grab. So if you still need all the users input you can still get the rest of it from the input buffer. The "char c = scanner.next().charAt(0);" way does grab the char but will clear the buffer.

// Java program to read character without using Scanner
public class Main
{
    public static void main(String[] args)
    {
        try {
            String input = "";
            // Grab the First char, also wait for user input if the buffer is empty.
            // Think of it as working just like getChar() does in C.
            char c = (char)System.in.read();
            while(c != '\n') {
                //<do your magic you need to do with the char here>
                input += c; // <my simple magic>

                //then grab the next char
                c = (char)System.in.read();
            }
            //print back out all the users input
            System.out.println(input);
        } catch (Exception e){
            System.out.println(e);
        }
    }
}  

Hope this helpful, and good luck! P.S. Sorry i know this is an older post, but i hope that my answer bring new insight and could might help other people who also have this problem.

os.path.dirname(__file__) returns empty

Because os.path.abspath = os.path.dirname + os.path.basename does not hold. we rather have

os.path.dirname(filename) + os.path.basename(filename) == filename

Both dirname() and basename() only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.

To get the dirname of the absolute path, use

os.path.dirname(os.path.abspath(__file__))

Sort divs in jQuery based on attribute 'data-sort'?

I used this to sort a gallery of images where the sort array would be altered by an ajax call. Hopefully it can be useful to someone.

_x000D_
_x000D_
var myArray = ['2', '3', '1'];_x000D_
var elArray = [];_x000D_
_x000D_
$('.imgs').each(function() {_x000D_
    elArray[$(this).data('image-id')] = $(this);_x000D_
});_x000D_
_x000D_
$.each(myArray,function(index,value){_x000D_
   $('#container').append(elArray[value]); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
   <div class="imgs" data-image-id='1'>1</div>_x000D_
   <div class="imgs" data-image-id='2'>2</div>_x000D_
   <div class="imgs" data-image-id='3'>3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: http://jsfiddle.net/ruys9ksg/

Load CSV data into MySQL in Python

using pymsql if it helps

import pymysql
import csv
db = pymysql.connect("localhost","root","12345678","data" )

cursor = db.cursor()
csv_data = csv.reader(open('test.csv'))
next(csv_data)
for row in csv_data:
    cursor.execute('INSERT INTO PM(col1,col2) VALUES(%s, %s)',row)

db.commit()
cursor.close()

Using global variables in a function

In addition to already existing answers and to make this more confusing:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Source: What are the rules for local and global variables in Python?.

How do you get the cursor position in a textarea?

Here's a cross browser function I have in my standard library:

function getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
        return {
            start: input.selectionStart,
            end: input.selectionEnd
        };
    }
    else if (input.createTextRange) {
        var sel = document.selection.createRange();
        if (sel.parentElement() === input) {
            var rng = input.createTextRange();
            rng.moveToBookmark(sel.getBookmark());
            for (var len = 0;
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                len++;
            }
            rng.setEndPoint("StartToStart", input.createTextRange());
            for (var pos = { start: 0, end: len };
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                pos.start++;
                pos.end++;
            }
            return pos;
        }
    }
    return -1;
}

Use it in your code like this:

var cursorPosition = getCursorPos($('#myTextarea')[0])

Here's its complementary function:

function setCursorPos(input, start, end) {
    if (arguments.length < 3) end = start;
    if ("selectionStart" in input) {
        setTimeout(function() {
            input.selectionStart = start;
            input.selectionEnd = end;
        }, 1);
    }
    else if (input.createTextRange) {
        var rng = input.createTextRange();
        rng.moveStart("character", start);
        rng.collapse();
        rng.moveEnd("character", end - start);
        rng.select();
    }
}

http://jsfiddle.net/gilly3/6SUN8/

Flexbox: center horizontally and vertically

Don't forgot to use important browsers specific attributes:

align-items: center; -->

-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

justify-content: center; -->

-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;

You could read this two links for better understanding flex: http://css-tricks.com/almanac/properties/j/justify-content/ and http://ptb2.me/flexbox/

Good Luck.

Stretch horizontal ul to fit width of div

People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">

Sort arrays of primitive types in descending order

I think it would be best not to re-invent the wheel and use Arrays.sort().

Yes, I saw the "descending" part. The sorting is the hard part, and you want to benefit from the simplicity and speed of Java's library code. Once that's done, you simply reverse the array, which is a relatively cheap O(n) operation. Here's some code I found to do this in as little as 4 lines:

for (int left=0, right=b.length-1; left<right; left++, right--) {
    // exchange the first and last
    int temp = b[left]; b[left]  = b[right]; b[right] = temp;
}

Software Design vs. Software Architecture

As others also pointed out, laying out the architecture of a piece of software is actually taking the major design decisions which have overall influence over the software development or execution life-cycle; so simplistically architecture is just high level design.

Even if an architecture decision does not affect all components (is thus, local) it must still be globally relevant, i.e. it impacts the whole system in some way; otherwise is simply a local design decision.

What I'd like to point out though, that a more relevant question related to architecture might be Architecture vs Organization as defined by Hennessy & Patterson in Computer Architecture. Based on this we could think about architecture as the data model (input/output, state) abstraction of the system and the organization as the typical design decisions taken during the implementation (software development) process.

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

How can I tell what edition of SQL Server runs on the machine?

select @@version

Sample Output

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Developer Edition (64-bit) on Windows NT 6.1 (Build 7600: )

If you just want to get the edition, you can use:

select serverproperty('Edition')

To use in an automated script, you can get the edition ID, which is an integer:

select serverproperty('EditionID')
  • -1253826760 = Desktop
  • -1592396055 = Express
  • -1534726760 = Standard
  • 1333529388 = Workgroup
  • 1804890536 = Enterprise
  • -323382091 = Personal
  • -2117995310 = Developer
  • 610778273 = Enterprise Evaluation
  • 1044790755 = Windows Embedded SQL
  • 4161255391 = Express with Advanced Services

SQL Server: IF EXISTS ; ELSE

I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_a
AS
(
    SELECT [id] [id]
    , MAX([value]) [value]
    FROM table_a
    GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN  cte_table_a
ON table_b.id = cte_table_a.id

How does one make random number between range for arc4random_uniform()?

If You want i create that for random numbers. this is extension of number Int and Double, Float

/**
    Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
    var r: T = 0
    arc4random_buf(&r, UInt(sizeof(T)))
    return r
}
public extension Int {
    /**
    Create a random num Int
    :param: lower number Int
    :param: upper number Int
    :return: random number Int
    By DaRkDOG
    */
    public static func random (#lower: Int , upper: Int) -> Int {
        return lower + Int(arc4random_uniform(upper - lower + 1))
    }

}
public extension Double {
    /**
    Create a random num Double
    :param: lower number Double
    :param: upper number Double
    :return: random number Double
    By DaRkDOG
    */
    public static func random(#lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
}
public extension Float {
    /**
    Create a random num Float
    :param: lower number Float
    :param: upper number Float
    :return: random number Float
    By DaRkDOG
    */
    public static func random(#lower: Float, upper: Float) -> Float {
        let r = Float(arc4random(UInt32)) / Float(UInt32.max)
        return (r * (upper - lower)) + lower
    }
}

USE :

let randomNumDouble = Double.random(lower: 0.00, upper: 23.50)
let randomNumInt = Int.random(lower: 56, upper: 992)
let randomNumInt =Float.random(lower: 6.98, upper: 923.09)

Is it possible to declare a public variable in vba and assign a default value?

You can define the variable in General Declarations and then initialise it in the first event that fires in your environment.

Alternatively, you could create yourself a class with the relevant properties and initialise them in the Initialise method

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

jQuery won't parse my JSON from AJAX query

If returning an array works and returning a single object doesn't, you might also try returning your single object as an array containing that single object:

[ { title: "One", key: "1" } ]

that way you are returning a consistent data structure, an array of objects, no matter the data payload.

i see that you've tried wrapping your single object in "parenthesis", and suggest this with example because of course JavaScript treats [ .. ] differently than ( .. )

What are the differences between WCF and ASMX web services?

WCF completely replaces ASMX web services. ASMX is the old way to do web services and WCF is the current way to do web services. All new SOAP web service development, on the client or the server, should be done using WCF.

Multi-dimensional arrays in Bash

After a lot of trial and error i actually find the best, clearest and easiest multidimensional array on bash is to use a regular var. Yep.

Advantages: You don't have to loop through a big array, you can just echo "$var" and use grep/awk/sed. It's easy and clear and you can have as many columns as you like.

Example:

$ var=$(echo -e 'kris hansen oslo\nthomas jonson peru\nbibi abu johnsonville\njohnny lipp peru')

$ echo "$var"
kris hansen oslo
thomas johnson peru
bibi abu johnsonville
johnny lipp peru

If you want to find everyone in peru

$ echo "$var" | grep peru
thomas johnson peru
johnny lipp peru

Only grep(sed) in the third field

$ echo "$var" | sed -n -E '/(.+) (.+) peru/p'
thomas johnson peru
johnny lipp peru

If you only want x field

$ echo "$var" | awk '{print $2}'
hansen
johnson
abu
johnny

Everyone in peru that's called thomas and just return his lastname

$ echo "$var" |grep peru|grep thomas|awk '{print $2}'
johnson

Any query you can think of... supereasy.

To change an item:

$ var=$(echo "$var"|sed "s/thomas/pete/")

To delete a row that contains "x"

$ var=$(echo "$var"|sed "/thomas/d")

To change another field in the same row based on a value from another item

$ var=$(echo "$var"|sed -E "s/(thomas) (.+) (.+)/\1 test \3/")
$ echo "$var"
kris hansen oslo                                                                                                                                             
thomas test peru                                                                                                                                          
bibi abu johnsonville
johnny lipp peru

Of course looping works too if you want to do that

$ for i in "$var"; do echo "$i"; done
kris hansen oslo
thomas jonson peru
bibi abu johnsonville
johnny lipp peru

The only gotcha iv'e found with this is that you must always quote the var(in the example; both var and i) or things will look like this

$ for i in "$var"; do echo $i; done
kris hansen oslo thomas jonson peru bibi abu johnsonville johnny lipp peru

and someone will undoubtedly say it won't work if you have spaces in your input, however that can be fixed by using another delimeter in your input, eg(using an utf8 char now to emphasize that you can choose something your input won't contain, but you can choose whatever ofc):

$ var=$(echo -e 'field one?field two hello?field three yes moin\nfield 1?field 2?field 3 dsdds aq')

$ for i in "$var"; do echo "$i"; done
field one?field two hello?field three yes moin
field 1?field 2?field 3 dsdds aq

$ echo "$var" | awk -F '?' '{print $3}'
field three yes moin
field 3 dsdds aq

$ var=$(echo "$var"|sed -E "s/(field one)?(.+)?(.+)/\1?test?\3/")
$ echo "$var"
field one?test?field three yes moin
field 1?field 2?field 3 dsdds aq

If you want to store newlines in your input, you could convert the newline to something else before input and convert it back again on output(or don't use bash...). Enjoy!

Read a file line by line assigning the value to a variable

#! /bin/bash
cat filename | while read LINE; do
    echo $LINE
done