Programs & Examples On #Preemption

How to recover stashed uncommitted changes

On mac this worked for me:

git stash list(see all your stashs)

git stash list

git stash apply (just the number that you want from your stash list)

like this:

git stash apply 1

Curl command line for consuming webServices?

curl -H "Content-Type: text/xml; charset=utf-8" \
-H "SOAPAction:" \
-d @soap.txt -X POST http://someurl

href="javascript:" vs. href="javascript:void(0)"

When using javascript: in navigation the return value of the executed script, if there is one, becomes the content of a new document which is displayed in the browser. The void operator in JavaScript causes the return value of the expression following it to return undefined, which prevents this action from happening. You can try it yourself, copy the following into the address bar and press return:

javascript:"hello"

The result is a new page with only the word "hello". Now change it to:

javascript:void "hello"

...nothing happens.

When you write javascript: on its own there's no script being executed, so the result of that script execution is also undefined, so the browser does nothing. This makes the following more or less equivalent:

javascript:undefined;
javascript:void 0;
javascript:

With the exception that undefined can be overridden by declaring a variable with the same name. Use of void 0 is generally pointless, and it's basically been whittled down from void functionThatReturnsSomething().

As others have mentioned, it's better still to use return false; in the click handler than use the javascript: protocol.

How to link an image and target a new window

<a href="http://www.google.com" target="_blank"> //gives blank window
<img width="220" height="250" border="0" align="center"  src=""/> // show image into new window
</a>

See the code

CSS :selected pseudo class similar to :checked, but for <select> elements

This worked for me :

select option {
   color: black;
}
select:not(:checked) {
   color: gray;
}

IIS - can't access page by ip address instead of localhost

The IIS is a multi web site server. The way is distinct the site is by the host header name. So you need to setup that on your web site.

Here is the steps that you need to follow:

How to configure multiple IIS websites to access using host headers?

In general, open your web site properties, locate the Ip Address and near its there is the advanced, "multiple identities for this web site". There you need ether to add all income to this site with a star: "*", ether place the names you like to work with.

Where can I find error log files?

What OS you are using and which Webserver? On Linux and Apache you can find the apache error_log in /var/log/apache2/

How to call a method daily, at specific time, in C#?

It may just be me but it seemed like most of these answers were not complete or would not work correctly. I made something very quick and dirty. That being said not sure how good of an idea it is to do it this way, but it works perfectly every time.

while (true)
{
    if(DateTime.Now.ToString("HH:mm") == "22:00")
    {
        //do something here
        //ExecuteFunctionTask();
        //Make sure it doesn't execute twice by pausing 61 seconds. So that the time is past 2200 to 2201
        Thread.Sleep(61000);
    }

    Thread.Sleep(10000);
}

Laravel 5 – Clear Cache in Shared Hosting Server

This worked for me. In your project go to: storage > framework > views. Delete all the files in there and refresh your page.

Darken background image on hover

I would add a div around the image and make the image change in opacity on hover and add an inset box shadow to the div on hover.

img:hover{
    opacity:.5;
}
.image:hover{
    box-shadow: inset 10px 10px 100px 100px #000;
}

<div class="image"><img src="image.jpg" /></div>

How and when to use ‘async’ and ‘await’

All the answers here use Task.Delay() or some other built in async function. But here is my example that use none of those async functions:

// Starts counting to a large number and then immediately displays message "I'm counting...". 
// Then it waits for task to finish and displays "finished, press any key".
static void asyncTest ()
{
    Console.WriteLine("Started asyncTest()");
    Task<long> task = asyncTest_count();
    Console.WriteLine("Started counting, please wait...");
    task.Wait(); // if you comment this line you will see that message "Finished counting" will be displayed before we actually finished counting.
    //Console.WriteLine("Finished counting to " + task.Result.ToString()); // using task.Result seems to also call task.Wait().
    Console.WriteLine("Finished counting.");
    Console.WriteLine("Press any key to exit program.");
    Console.ReadLine();
}

static async Task<long> asyncTest_count()
{
    long k = 0;
    Console.WriteLine("Started asyncTest_count()");
    await Task.Run(() =>
    {
        long countTo = 100000000;
        int prevPercentDone = -1;
        for (long i = 0; i <= countTo; i++)
        {
            int percentDone = (int)(100 * (i / (double)countTo));
            if (percentDone != prevPercentDone)
            {
                prevPercentDone = percentDone;
                Console.Write(percentDone.ToString() + "% ");
            }

            k = i;
        }
    });
    Console.WriteLine("");
    Console.WriteLine("Finished asyncTest_count()");
    return k;
}

CSS background image to fit height, width should auto-scale in proportion

body.bg {
    background-size: cover;
    background-repeat: no-repeat;
    min-height: 100vh;
    background: white url(../images/bg-404.jpg) center center no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
}   
Try This
_x000D_
_x000D_
    body.bg {_x000D_
     background-size: cover;_x000D_
     background-repeat: no-repeat;_x000D_
     min-height: 100vh;_x000D_
     background: white url(http://lorempixel.com/output/city-q-c-1920-1080-7.jpg) center center no-repeat;_x000D_
     -webkit-background-size: cover;_x000D_
     -moz-background-size: cover;_x000D_
     -o-background-size: cover;_x000D_
    } 
_x000D_
    <body class="bg">_x000D_
_x000D_
_x000D_
     _x000D_
    </body>
_x000D_
_x000D_
_x000D_

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

Here is your relief for the problem :

I have a problem of running different versions of STS this morning, the application crash with the similar way as the question did.

Excerpt of my log file.

A fatal error has been detected by the Java Runtime Environment:
#a
#  SIGSEGV (0xb) at pc=0x00007f459db082a1, pid=4577, tid=139939015632640
#
# JRE version: 6.0_30-b12
# Java VM: Java HotSpot(TM) 64-Bit Server VM 
(20.5-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libsoup-2.4.so.1+0x6c2a1]  short+0x11

note that exception occured at # C [libsoup-2.4.so.1+0x6c2a1] short+0x11

Okay then little below the line:

R9 =0x00007f461829e550: <offset 0xa85550> in /usr/share/java/jdk1.6.0_30/jre/lib/amd64/server/libjvm.so at 0x00007f4617819000
R10=0x00007f461750f7c0 is pointing into the stack for thread: 0x00007f4610008000
R11=0x00007f459db08290: soup_session_feature_detach+0 in /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1 at 0x00007f459da9c000
R12=0x0000000000000000 is an unknown value
R13=0x000000074404c840 is an oop
{method} 

This line tells you where the actual bug or crash is to investigate more on this crash issue please use below links to see more, but let's continue the crash investigation and how I resolved it and the novelty of this bug :)

links are :

a fATAL ERROR JAVA THIS ONE IS GREAT LOTS OF USER!

a fATAL ERROR JAVA 2

Okay, after that here's what I found out to casue this case and why it happens as general advise.

  1. Most of the time, check that if you have installed, updated recently on Ubunu and Windows there are libraries like libsoup in linux which were the casuse of my crash.

  2. Check also for a new hardware problem and try to investigate the Logfile which STS or Java generated and also syslog in linux by

    tail - f /var/lib/messages or some other file
    

Then by carfully looking at those files the one you have the crash log for ... you can really solve the issue as follows:

sudo unlink /usr/lib/i386-linux-gnu/libsoup-2.4.so.1

or

sudo unlink /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1

Done !! Cheers!!

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

Get column from a two dimensional array

You can use the following array methods to obtain a column from a 2D array:

Array.prototype.map()

const array_column = (array, column) => array.map(e => e[column]);

Array.prototype.reduce()

const array_column = (array, column) => array.reduce((a, c) => {
  a.push(c[column]);
  return a;
}, []);

Array.prototype.forEach()

const array_column = (array, column) => {
  const result = [];

  array.forEach(e => {
    result.push(e[column]);
  });

  return result;
};

If your 2D array is a square (the same number of columns for each row), you can use the following method:

Array.prototype.flat() / .filter()

const array_column = (array, column) => array.flat().filter((e, i) => i % array.length === column);

Android Respond To URL in Intent

You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

Note that path prefix is optional.

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />

            <data android:host="www.docs.google.com" />
            <data android:host="docs.google.com" />

            <data android:pathPrefix="/forms" />
        </intent-filter>

How does autowiring work in Spring?

First, and most important - all Spring beans are managed - they "live" inside a container, called "application context".

Second, each application has an entry point to that context. Web applications have a Servlet, JSF uses a el-resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener.

Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.

What is "living" in the application context? This means that the context instantiates the objects, not you. I.e. - you never make new UserServiceImpl() - the container finds each injection point and sets an instance there.

In your controllers, you just have the following:

@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {

    // Tells the application context to inject an instance of UserService here
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void login(@RequestParam("username") String username,
           @RequestParam("password") String password) {

        // The UserServiceImpl is already injected and you can use it
        userService.login(username, password);

    }
}

A few notes:

  • In your applicationContext.xml you should enable the <context:component-scan> so that classes are scanned for the @Controller, @Service, etc. annotations.
  • The entry point for a Spring-MVC application is the DispatcherServlet, but it is hidden from you, and hence the direct interaction and bootstrapping of the application context happens behind the scene.
  • UserServiceImpl should also be defined as bean - either using <bean id=".." class=".."> or using the @Service annotation. Since it will be the only implementor of UserService, it will be injected.
  • Apart from the @Autowired annotation, Spring can use XML-configurable autowiring. In that case all fields that have a name or type that matches with an existing bean automatically get a bean injected. In fact, that was the initial idea of autowiring - to have fields injected with dependencies without any configuration. Other annotations like @Inject, @Resource can also be used.

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

How to create new folder?

Have you tried os.mkdir?

You might also try this little code snippet:

mypath = ...
if not os.path.isdir(mypath):
   os.makedirs(mypath)

makedirs creates multiple levels of directories, if needed.

Laravel PHP Command Not Found

For Developers use zsh Add the following to .zshrc file

vi ~/.zshrc or nano ~/.zshrc

export PATH="$HOME/.composer/vendor/bin:$PATH"

at the end of the file.

zsh doesn't know ~ so instead it by use $HOME.

source ~/.zshrc

Done! try command laravel you will see.

How get total sum from input box values using Javascript?

I need to sum the span elements so I edited Akhil Sekharan's answer below.

var arr = document.querySelectorAll('span[id^="score"]');
var total=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].innerHTML))
            total+= parseInt(arr[i].innerHTML);
    }
console.log(total)

You can change the elements with other elements link will guide you with editing.

https://www.w3.org/TR/css3-selectors/#attribute-substrings

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

With Visual Studio 2019 I had a similar issue when I wanted to run tests (MSTest directly from VS). In my case I only had an x64 native DLL and I received this error message. First, I thought it is because Visual Studio runs as x86 but this page helped me to solve the issue:

Run unit test as a 64-bit process

It says

  1. Set your projects to Any CPU
  2. Explicitly define processor architecture

I did both (I explicitly set x64) and then my tests started to work.

Set processor architecture explicitly to x64

AngularJS Multiple ng-app within a page

To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap()

HTML

<!-- Automatic Initialization -->
<div ng-app="myFirstModule">
    ...
</div>
<!-- Need To Manually Bootstrap All Other Modules -->
<div id="module2">
    ...
</div>

JS

angular.
  bootstrap(document.getElementById("module2"), ['mySecondModule']);

The reason for this is that only one AngularJS application can be automatically bootstrapped per HTML document. The first ng-app found in the document will be used to define the root element to auto-bootstrap as an application.

In other words, while it is technically possible to have several applications per page, only one ng-app directive will be automatically instantiated and initialized by the Angular framework.

How to open a new file in vim in a new window

You can do so from within vim and use its own windows or tabs.

One way to go is to utilize the built-in file explorer; activate it via :Explore, or :Texplore for a tabbed interface (which I find most comfortable).

:Texplore (and :Sexplore) will also guard you from accidentally exiting the current buffer (editor) on :q once you're inside the explorer.

To toggle between open tabs when using tab pages use gt or gT (next tab and previous tab, respectively).

See also Using tab pages on the vim wiki.

login to remote using "mstsc /admin" with password

Same problem but @Angelo answer didn't work for me, because I'm using same server with different credentials. I used the approach below and tested it on Windows 10.

cmdkey /add:server01 /user:<username> /pass:<password>

Then used mstsc /v:server01 to connect to the server.

The point is to use names instead of ip addresses to avoid conflict between credentials. If you don't have a DNS server locally accessible try c:\windows\system32\drivers\etc\hosts file.

Converting characters to integers in Java

From the Javadoc for Character#getNumericValue:

If the character does not have a numeric value, then -1 is returned. If the character has a numeric value that cannot be represented as a nonnegative integer (for example, a fractional value), then -2 is returned.

The character + does not have a numeric value, so you're getting -1.

Update:

The reason that primitive conversion is giving you 43 is that the the character '+' is encoded as the integer 43.

How do I turn a C# object into a JSON string in .NET?

Wooou! Really better using a JSON framework :)

Here is my example using Json.NET (http://james.newtonking.com/json):

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;

namespace com.blogspot.jeanjmichel.jsontest.model
{
    public class Contact
    {
        private Int64 id;
        private String name;
        List<Address> addresses;

        public Int64 Id
        {
            set { this.id = value; }
            get { return this.id; }
        }

        public String Name
        {
            set { this.name = value; }
            get { return this.name; }
        }

        public List<Address> Addresses
        {
            set { this.addresses = value; }
            get { return this.addresses; }
        }

        public String ToJSONRepresentation()
        {
            StringBuilder sb = new StringBuilder();
            JsonWriter jw = new JsonTextWriter(new StringWriter(sb));

            jw.Formatting = Formatting.Indented;
            jw.WriteStartObject();
            jw.WritePropertyName("id");
            jw.WriteValue(this.Id);
            jw.WritePropertyName("name");
            jw.WriteValue(this.Name);

            jw.WritePropertyName("addresses");
            jw.WriteStartArray();

            int i;
            i = 0;

            for (i = 0; i < addresses.Count; i++)
            {
                jw.WriteStartObject();
                jw.WritePropertyName("id");
                jw.WriteValue(addresses[i].Id);
                jw.WritePropertyName("streetAddress");
                jw.WriteValue(addresses[i].StreetAddress);
                jw.WritePropertyName("complement");
                jw.WriteValue(addresses[i].Complement);
                jw.WritePropertyName("city");
                jw.WriteValue(addresses[i].City);
                jw.WritePropertyName("province");
                jw.WriteValue(addresses[i].Province);
                jw.WritePropertyName("country");
                jw.WriteValue(addresses[i].Country);
                jw.WritePropertyName("postalCode");
                jw.WriteValue(addresses[i].PostalCode);
                jw.WriteEndObject();
            }

            jw.WriteEndArray();

            jw.WriteEndObject();

            return sb.ToString();
        }

        public Contact()
        {
        }

        public Contact(Int64 id, String personName, List<Address> addresses)
        {
            this.id = id;
            this.name = personName;
            this.addresses = addresses;
        }

        public Contact(String JSONRepresentation)
        {
            //To do
        }
    }
}

The test:

using System;
using System.Collections.Generic;
using com.blogspot.jeanjmichel.jsontest.model;

namespace com.blogspot.jeanjmichel.jsontest.main
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Address> addresses = new List<Address>();
            addresses.Add(new Address(1, "Rua Dr. Fernandes Coelho, 85", "15º andar", "São Paulo", "São Paulo", "Brazil", "05423040"));
            addresses.Add(new Address(2, "Avenida Senador Teotônio Vilela, 241", null, "São Paulo", "São Paulo", "Brazil", null));

            Contact contact = new Contact(1, "Ayrton Senna", addresses);

            Console.WriteLine(contact.ToJSONRepresentation());
            Console.ReadKey();
        }
    }
}

The result:

{
  "id": 1,
  "name": "Ayrton Senna",
  "addresses": [
    {
      "id": 1,
      "streetAddress": "Rua Dr. Fernandes Coelho, 85",
      "complement": "15º andar",
      "city": "São Paulo",
      "province": "São Paulo",
      "country": "Brazil",
      "postalCode": "05423040"
    },
    {
      "id": 2,
      "streetAddress": "Avenida Senador Teotônio Vilela, 241",
      "complement": null,
      "city": "São Paulo",
      "province": "São Paulo",
      "country": "Brazil",
      "postalCode": null
    }
  ]
}

Now I will implement the constructor method that will receives a JSON string and populates the class' fields.

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

How to print an unsigned char in C?

There are two bugs in this code. First, in most C implementations with signed char, there is a problem in char ch = 212 because 212 does not fit in an 8-bit signed char, and the C standard does not fully define the behavior (it requires the implementation to define the behavior). It should instead be:

unsigned char ch = 212;

Second, in printf("%u",ch), ch will be promoted to an int in normal C implementations. However, the %u specifier expects an unsigned int, and the C standard does not define behavior when the wrong type is passed. It should instead be:

printf("%u", (unsigned) ch);

C# error: Use of unassigned local variable

The compiler only knows that the code is or isn't reachable if you use "return". Think of Environment.Exit() as a function that you call, and the compiler don't know that it will close the application.

Mathematical functions in Swift

As other noted you have several options. If you want only mathematical functions. You can import only Darwin.

import Darwin

If you want mathematical functions and other standard classes and functions. You can import Foundation.

import Foundation

If you want everything and also classes for user interface, it depends if your playground is for OS X or iOS.

For OS X, you need import Cocoa.

import Cocoa

For iOS, you need import UIKit.

import UIKit

You can easily discover your playground platform by opening File Inspector (??1).

Playground Settings - Platform

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

How can I pull from remote Git repository and override the changes in my local repository?

As an addendum, if you want to reapply your changes on top of the remote, you can also try:

git pull --rebase origin master

If you then want to undo some of your changes (but perhaps not all of them) you can use:

git reset SHA_HASH

Then do some adjustment and recommit.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib to include all the .jar files in that directory, it won't. You have to name them explicitly.

jQuery UI dialog box not positioned center screen

My Scenario: I had to scroll down on page to open dialog on a button click, due to window scroll the dialog was not opening vertically center to window, it was going out of view-port.

As Ken has mentioned above , after you have set your modal content execute below statement.

$("selector").dialog('option', 'position', 'center');

If content is pre-loaded before modal opens just execute this in open event, else manipulate DOM in open event and then execute statement.

$( ".selector" ).dialog({
open: function( event, ui ) {
//Do DOM manipulation if needed before executing below statement
$(this).dialog('option', 'position', 'center');
}
});

It worked well for me and the best thing is that you don't include any other plugin or library for it to work.

Difference between frontend, backend, and middleware in web development

Frontend refers to the client-side, whereas backend refers to the server-side of the application. Both are crucial to web development, but their roles, responsibilities and the environments they work in are totally different. Frontend is basically what users see whereas backend is how everything works

Send array with Ajax to PHP script

If you have been trying to send a one dimentional array and jquery was converting it to comma separated values >:( then follow the code below and an actual array will be submitted to php and not all the comma separated bull**it.

Say you have to attach a single dimentional array named myvals.

jQuery('#someform').on('submit', function (e) {
    e.preventDefault();
    var data = $(this).serializeArray();

    var myvals = [21, 52, 13, 24, 75]; // This array could come from anywhere you choose 
    for (i = 0; i < myvals.length; i++) {
        data.push({
            name: "myvals[]", // These blank empty brackets are imp!
            value: myvals[i]
        });
    }

jQuery.ajax({
    type: "post",
    url: jQuery(this).attr('action'),
    dataType: "json",
    data: data, // You have to just pass our data variable plain and simple no Rube Goldberg sh*t.
    success: function (r) {
...

Now inside php when you do this

print_r($_POST);

You will get ..

Array
(
    [someinputinsidetheform] => 023
    [anotherforminput] => 111
    [myvals] => Array
        (
            [0] => 21
            [1] => 52
            [2] => 13
            [3] => 24
            [4] => 75
        )
)

Pardon my language, but there are hell lot of Rube-Goldberg solutions scattered all over the web and specially on SO, but none of them are elegant or solve the problem of actually posting a one dimensional array to php via ajax post. Don't forget to spread this solution.

Does Enter key trigger a click event?

@Component({
  selector: 'key-up3',
  template: `
    <input #box (keyup.enter)="doSomething($event)">
    <p>{{values}}</p>
  `
})
export class KeyUpComponent_v3 {
  doSomething(e) {
    alert(e);
  }
}

This works for me!

How to use curl in a shell script?

#!/bin/bash                                                                                                                                                                                     
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"

# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"

# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer

or:

Execute bash script from URL

javascript node.js next()

This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.

See, for example, the code samples here:

Let's look at the example you posted:

function loadUser(req, res, next) {
  if (req.session.user_id) {
    User.findById(req.session.user_id, function(user) {
      if (user) {
        req.currentUser = user;
        return next();
      } else {
        res.redirect('/sessions/new');
      }
    });
  } else {
    res.redirect('/sessions/new');
  }
}

app.get('/documents.:format?', loadUser, function(req, res) {
  // ...
});

The loadUser function expects a function in its third argument, which is bound to the name next. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser is done (unless a user could not be found).

There's nothing special about the name next in this example; we could have named it anything.

jquery ui Dialog: cannot call methods on dialog prior to initialization

This is also some work around:

$("div[aria-describedby='divDialog'] .ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close").click();

Why do I get an error instantiating an interface?

You cannot instantiate an abstract class or interface. You must inherit it, if its an abstract class, or implement it if it's an interface. e.g.

...
private class User : IUser
{
  ...
}

User u = new User();

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Change background color of R plot

I use abline() with extremely wide vertical lines to fill the plot space:

abline(v = xpoints, col = "grey90", lwd = 80)

You have to create the frame, then the ablines, and then plot the points so they are visible on top. You can even use a second abline() statement to put thin white or black lines over the grey, if desired.

Example:

xpoints = 1:20
y = rnorm(20)
plot(NULL,ylim=c(-3,3),xlim=xpoints)
abline(v=xpoints,col="gray90",lwd=80)
abline(v=xpoints,col="white")
abline(h = 0, lty = 2) 
points(xpoints, y, pch = 16, cex = 1.2, col = "red")

Run cmd commands through Java

You can't run cd this way, because cd isn't a real program; it's a built-in part of the command-line, and all it does is change the command-line's environment. It doesn't make sense to run it in a subprocess, because then you're changing that subprocess's environment — but that subprocess closes immediately, discarding its environment.

To set the current working directory in your actual Java program, you should write:

System.setProperty("user.dir", "C:\\Program Files\\Flowella");

How to define a List bean in Spring?

Import the spring util namespace. Then you can define a list bean as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/util
                    http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<util:list id="myList" value-type="java.lang.String">
    <value>foo</value>
    <value>bar</value>
</util:list>

The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute list-class.

Python - How to cut a string in Python?

>>str = "http://www.domain.com/?s=some&two=20"
>>str.split("&")
>>["http://www.domain.com/?s=some", "two=20"]

How to record phone calls in android?

Below code is working for me to record a outgoing phone call

//Call Recording varibales
private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";

private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
        MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
        AUDIO_RECORDER_FILE_EXT_3GP };

AudioManager audioManager;

//put this methods to outside of oncreate() method

private String getFilename() {
    String filepath = Environment.getExternalStorageDirectory().getPath();
    File file = new File(filepath, AUDIO_RECORDER_FOLDER);

    if (!file.exists()) {
        file.mkdirs();
    }

    return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}

private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        Toast.makeText(CallActivity.this,
                "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
    }
};

private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
    @Override
    public void onInfo(MediaRecorder mr, int what, int extra) {
        Toast.makeText(CallActivity.this,
                "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
                .show();
    }
};

//below part of code to make your device on speaker

    audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE); 
    audioManager.setMode(AudioManager.MODE_IN_CALL);
    audioManager.setSpeakerphoneOn(true);

//below part of code to start recording

recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(output_formats[currentFormat]);
    //recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(getFilename());
    recorder.setOnErrorListener(errorListener);
    recorder.setOnInfoListener(infoListener);

    try {
        recorder.prepare();
        recorder.start();
    } catch (IllegalStateException e) {
         Log.e("REDORDING :: ",e.getMessage());
            e.printStackTrace();
    } catch (IOException e) {
        Log.e("REDORDING :: ",e.getMessage());
        e.printStackTrace();
    }

//For stop recording and keep in mind to set speaker off while call end or stop

audioManager.setSpeakerphoneOn(false);

    try{
        if (null != recorder) {
            recorder.stop();
            recorder.reset();
            recorder.release();

            recorder = null;
        }
    }catch(RuntimeException stopException){

    }

And give permission to manifest file,

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Delete rows containing specific strings in R

You can use this function if it's multiple string df[!grepl("REVERSE|GENJJS", df$Name),]

port forwarding in windows

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

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

Hibernate: get entity by id

Using EntityManager em;

public User getUserById(Long id) {
     return em.getReference(User.class, id);
}

Npm install failed with "cannot run in wd"

OP here, I have learned a lot more about node since I first asked this question. Though Dmitry's answer was very helpful, what ultimately did it for me is to install node with the correct permissions.

I highly recommend not installing node using any package managers, but rather to compile it yourself so that it resides in a local directory with normal permissions.

This article provides a very clear step-by-step instruction of how to do so:

https://www.digitalocean.com/community/tutorials/how-to-install-an-upstream-version-of-node-js-on-ubuntu-12-04

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

Hash String via SHA-256 in Java

Using Java 8

MessageDigest digest = null;
try {
    digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
}
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);        
System.out.println(encoded.toLowerCase());

Gets last digit of a number

Use

int lastDigit = number % 10. 

Read about Modulo operator: http://en.wikipedia.org/wiki/Modulo_operation

Or, if you want to go with your String solution

String charAtLastPosition = temp.charAt(temp.length()-1);

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

What does the question mark in Java generics' type parameter mean?

? extends HasWord

means "A class/interface that extends HasWord." In other words, HasWord itself or any of its children... basically anything that would work with instanceof HasWord plus null.

In more technical terms, ? extends HasWord is a bounded wildcard, covered in Item 31 of Effective Java 3rd Edition, starting on page 139. The same chapter from the 2nd Edition is available online as a PDF; the part on bounded wildcards is Item 28 starting on page 134.

Update: PDF link was updated since Oracle removed it a while back. It now points to the copy hosted by the Queen Mary University of London's School of Electronic Engineering and Computer Science.

Update 2: Lets go into a bit more detail as to why you'd want to use wildcards.

If you declare a method whose signature expect you to pass in List<HasWord>, then the only thing you can pass in is a List<HasWord>.

However, if said signature was List<? extends HasWord> then you could pass in a List<ChildOfHasWord> instead.

Note that there is a subtle difference between List<? extends HasWord> and List<? super HasWord>. As Joshua Bloch put it: PECS = producer-extends, consumer-super.

What this means is that if you are passing in a collection that your method pulls data out from (i.e. the collection is producing elements for your method to use), you should use extends. If you're passing in a collection that your method adds data to (i.e. the collection is consuming elements your method creates), it should use super.

This may sound confusing. However, you can see it in List's sort command (which is just a shortcut to the two-arg version of Collections.sort). Instead of taking a Comparator<T>, it actually takes a Comparator<? super T>. In this case, the Comparator is consuming the elements of the List in order to reorder the List itself.

Deploying website: 500 - Internal server error

I recently got into same problem, the disk space was full on the server. Clearing some space has resolved the issue.

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

prevent iphone default keyboard when focusing an <input>

So here is my solution (similar to John Vance's answer):

First go here and get a function to detect mobile browsers.

http://detectmobilebrowsers.com/

They have a lot of different ways to detect if you are on mobile, so find one that works with what you are using.

Your HTML page (pseudo code):

If Mobile Then
    <input id="selling-date" type="date" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />
else
    <input id="selling-date" type="text" class="date-picker" readonly="readonly" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />

JQuery:

$( ".date-picker" ).each(function() {
    var min = $( this ).attr("min");
    var max = $( this ).attr("max");
    $( this ).datepicker({ 
        dateFormat: "yy-mm-dd",  
        minDate: min,  
        maxDate: max  
    });
});

This way you can still use native date selectors in mobile while still setting the min and max dates either way.

The field for non mobile should be read only because if a mobile browser like chrome for ios "requests desktop version" then they can get around the mobile check and you still want to prevent the keyboard from showing up.

However if the field is read only it could look to a user like they cant change the field. You could fix this by changing the CSS to make it look like it isn't read only (ie change border-color to black) but unless you are changing the CSS for all input tags you will find it hard to keep the look consistent across browsers.

To get arround that I just add a calendar image button to the date picker. Just change your JQuery code a bit:

$( ".date-picker" ).each(function() {
    var min = $( this ).attr("min");
    var max = $( this ).attr("max");
    $( this ).datepicker({ 
        dateFormat: "yy-mm-dd",  
        minDate: min,  
        maxDate: max,
        showOn: "both",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        buttonText: "Select date"
    });
});

Note: you will have to find a suitable image.

Which font is used in Visual Studio Code Editor and how to change fonts?

On Windows, the default settings are as follow (I never installed Monaco nor Menlo)

{
    "editor.fontFamily": "Consolas",
    "editor.fontSize": 14,
    "editor.lineHeight": 19
}

Settings fontSize to 12 and lineHeight to 16 closely approximate Visual Studio set to Consolas with 10pt size. I could not get an exact match (VS Code font is slightly bolder) but close enough.

How do I install Python 3 on an AWS EC2 instance?

On Debian derivatives such as Ubuntu, use apt. Check the apt repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo apt-get install python3

On Red Hat and derivatives, use yum. Check the yum repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo yum install python36

On SUSE and derivatives, use zypper. Check the repository for the versions of Python available to you. Then. run a command similar to the following, substituting the correct package name:

sudo zypper install python3

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"

Apparently the differences between these date formats are as follow:

DT_DATE A date structure that consists of year, month, day, and hour.

DT_DBDATE A date structure that consists of year, month, and day.

DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction

By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector('attributeValue').value='new value'");

How to check whether Kafka Server is running?

You can install Kafkacat tool on your machine

For example on Ubuntu You can install it using

apt-get install kafkacat

once kafkacat is installed then you can use following command to connect it

kafkacat -b <your-ip-address>:<kafka-port> -t test-topic
  • Replace <your-ip-address> with your machine ip
  • <kafka-port> can be replaced by the port on which kafka is running. Normally it is 9092

once you run the above command and if kafkacat is able to make the connection then it means that kafka is up and running

How can I convert a hex string to a byte array?

I think this may work.

public static byte[] StrToByteArray(string str)
    {
        Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
        for (int i = 0; i <= 255; i++)
            hexindex.Add(i.ToString("X2"), (byte)i);

        List<byte> hexres = new List<byte>();
        for (int i = 0; i < str.Length; i += 2)            
            hexres.Add(hexindex[str.Substring(i, 2)]);

        return hexres.ToArray();
    }

How to display alt text for an image in chrome

Yes it's an issue in webkit and also reported in chromium: http://code.google.com/p/chromium/issues/detail?id=773 It's there since 2008... and still not fixed!!

I'm using a piece of javacsript and jQuery to make my way around this.

function showAlt(){$(this).replaceWith(this.alt)};
function addShowAlt(selector){$(selector).error(showAlt).attr("src", $(selector).src)};
addShowAlt("img");

If you only want one some images:

addShowAlt("#myImgID");

Getting Django admin url for an object

You can use the URL resolver directly in a template, there's no need to write your own filter. E.g.

{% url 'admin:index' %}

{% url 'admin:polls_choice_add' %}

{% url 'admin:polls_choice_change' choice.id %}

{% url 'admin:polls_choice_changelist' %}

Ref: Documentation

Java Code for calculating Leap Year

public static void main(String[] args)
{

String strDate="Feb 2013";
        String[] strArray=strDate.split("\\s+");        

        Calendar cal = Calendar.getInstance();
        cal.setTime(new SimpleDateFormat("MMM").parse(strArray[0].toString()));
        int monthInt = cal.get(Calendar.MONTH);
        monthInt++;
        cal.set(Calendar.YEAR, Integer.parseInt(strArray[1]));          
        strDate=strArray[1].toString()+"-"+monthInt+"-"+cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        System.out.println(strDate);    



}

Half circle with CSS (border, outline only)

Below is a minimal code to achieve the effect.

This also works responsively since the border-radius is in percentage.

_x000D_
_x000D_
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
_x000D_
_x000D_

List all liquibase sql types

I've found the liquibase.database.typeconversion.core.AbstractTypeConverter class. It lists all types that can be used:

protected DataType getDataType(String columnTypeString, Boolean autoIncrement, String dataTypeName, String precision, String additionalInformation) {
    // Translate type to database-specific type, if possible
    DataType returnTypeName = null;
    if (dataTypeName.equalsIgnoreCase("BIGINT")) {
        returnTypeName = getBigIntType();
    } else if (dataTypeName.equalsIgnoreCase("NUMBER") || dataTypeName.equalsIgnoreCase("NUMERIC")) {
        returnTypeName = getNumberType();
    } else if (dataTypeName.equalsIgnoreCase("BLOB")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
        returnTypeName = getBooleanType();
    } else if (dataTypeName.equalsIgnoreCase("CHAR")) {
        returnTypeName = getCharType();
    } else if (dataTypeName.equalsIgnoreCase("CLOB")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
        returnTypeName = getCurrencyType();
    } else if (dataTypeName.equalsIgnoreCase("DATE") || dataTypeName.equalsIgnoreCase(getDateType().getDataTypeName())) {
        returnTypeName = getDateType();
    } else if (dataTypeName.equalsIgnoreCase("DATETIME") || dataTypeName.equalsIgnoreCase(getDateTimeType().getDataTypeName())) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
        returnTypeName = getDoubleType();
    } else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
        returnTypeName = getFloatType();
    } else if (dataTypeName.equalsIgnoreCase("INT")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("LONGBLOB")) {
        returnTypeName = getLongBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("SMALLINT")) {
        returnTypeName = getSmallIntType();
    } else if (dataTypeName.equalsIgnoreCase("TEXT")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("TIME") || dataTypeName.equalsIgnoreCase(getTimeType().getDataTypeName())) {
        returnTypeName = getTimeType();
    } else if (dataTypeName.toUpperCase().contains("TIMESTAMP")) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
        returnTypeName = getTinyIntType();
    } else if (dataTypeName.equalsIgnoreCase("UUID")) {
        returnTypeName = getUUIDType();
    } else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
        returnTypeName = getVarcharType();
    } else if (dataTypeName.equalsIgnoreCase("NVARCHAR")) {
        returnTypeName = getNVarcharType();
    } else {
        return new CustomType(columnTypeString,0,2);
    }

Include another JSP file

1.<a href="index.jsp?p=products">Products</a> when user clicks on Products link,you can directly call products.jsp.

I mean u can maintain name of the JSP file same as parameter Value.

<%
 if(request.getParameter("p")!=null)
 { 
   String contextPath="includes/";
   String p = request.getParameter("p");
   p=p+".jsp";
   p=contextPath+p;

%>    

<%@include file="<%=p%>" %>

<% 
 }
%>

or

2.you can maintain external resource file with key,value pairs. like below

products : products.jsp

customer : customers.jsp

you can programatically retrieve the name of JSP file from properies file.

this way you can easily change the name of JSP file

How to create a Date in SQL Server given the Day, Month and Year as Integers

So, you can try this solution:

DECLARE @DAY INT = 25
DECLARE @MONTH INT  = 10 
DECLARE @YEAR INT = 2016
DECLARE @DATE AS DATETIME

SET @DATE = CAST(RTRIM(@YEAR * 10000 + @MONTH * 100 + @DAY) AS DATETIME) 

SELECT REPLACE(CONVERT(VARCHAR(10), @DATE, 102), '.', '-') AS EXPECTDATE

Or you can try this a few lines of code:

DECLARE @DAY INT = 25
DECLARE @MONTH INT  = 10 
DECLARE @YEAR INT = 2016

SELECT CAST(RTRIM(@YEAR * 10000 +'-' +  @MONTH * 100+ '-' + @DAY) AS DATE) AS EXPECTDATE

How set the android:gravity to TextView from Java side in Android

Use this code

        TextView textView = new TextView(YourActivity.this);
        textView.setGravity(Gravity.CENTER | Gravity.TOP);
        textView.setText("some text");

Run C++ in command prompt - Windows

Steps to perform the task:

  1. First, download and install the compiler.

  2. Then, type the C/C++ program and save it.

  3. Then, open the command line and change directory to the particular one where the source file is stored, using cd like so:

    cd C:\Documents and Settings\...
    
  4. Then, to compile, type in the command prompt:

    gcc sourcefile_name.c -o outputfile.exe
    
  5. Finally, to run the code, type:

    outputfile.exe
    

Regex to match string containing two names in any order

The expression in this answer does that for one jack and one james in any order.

Here, we'd explore other scenarios.

METHOD 1: One jack and One james

Just in case, two jack or two james would not be allowed, only one jack and one james would be valid, we can likely design an expression similar to:

^(?!.*\bjack\b.*\bjack\b)(?!.*\bjames\b.*\bjames\b)(?=.*\bjames\b)(?=.*\bjack\b).*$

Here, we would exclude those instances using these statements:

(?!.*\bjack\b.*\bjack\b)

and,

(?!.*\bjames\b.*\bjames\b)

RegEx Demo 1

We can also simplify that to:

^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$

RegEx Demo 2


If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Test

_x000D_
_x000D_
const regex = /^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$/gm;
const str = `hi jack here is james
hi james here is jack
hi james jack here is jack james
hi jack james here is james jack
hi jack jack here is jack james
hi james james here is james jack
hi jack jack jack here is james
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
_x000D_
_x000D_
_x000D_


METHOD 2: One jack and One james in a specific order

The expression can be also designed for first a james then a jack, similar to the following one:

^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b.*\bjack\b).*$

RegEx Demo 3

and vice versa:

^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjack\b.*\bjames\b).*$

RegEx Demo 4

How do I write a custom init for a UIView subclass in Swift?

Here is how I do a Subview on iOS in Swift -

class CustomSubview : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        let windowHeight : CGFloat = 150;
        let windowWidth  : CGFloat = 360;

        self.backgroundColor = UIColor.whiteColor();
        self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
        self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);

        //for debug validation
        self.backgroundColor = UIColor.grayColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

How to declare a variable in MySQL?

SET

SET @var_name = value 

OR

SET @var := value

both operators = and := are accepted


SELECT

SELECT col1, @var_name := col2 from tb_name WHERE "conditon";

if multiple record sets found only the last value in col2 is keep (override);

SELECT col1, col2 INTO @var_name, col3 FROM .....

in this case the result of select is not containing col2 values


Ex both methods used

-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations

...
SELECT count(*) INTO @NR FROM a_table WHERE a_condition;
SET NEW.ord_col =  IFNULL( @NR, 0 ) + 1;
...

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I faced a similar problem but in my case I was trying to install Visual C++ Redistributable for Visual Studio 2015 Update 1 on Windows Server 2012 R2. However the root cause should be the same.

In short, you need to install the prerequisites of KB2999226.

In more details, the installation log I got stated that the installation for Windows Update KB2999226 failed. According to the Microsoft website here:

Prerequisites To install this update, you must have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) installed in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or, install Service Pack 2 for Windows Vista and for Windows Server 2008.

After I have installed April 2014 on my Windows Server 2012 R2, I am able to install the Visual C++ Redistributable correctly.

RVM is not a function, selecting rubies with 'rvm use ...' will not work

FWIW- I just ran across this as well, it was in the context of a cancelled selenium run. Perhaps there was a sub-shell being instantiated and left in place. Closing that terminal window and opening a new one was all I needed to do. (macOS Sierra)

Is there an alternative to string.Replace that is case-insensitive?

Kind of a confusing group of answers, in part because the title of the question is actually much larger than the specific question being asked. After reading through, I'm not sure any answer is a few edits away from assimilating all the good stuff here, so I figured I'd try to sum.

Here's an extension method that I think avoids the pitfalls mentioned here and provides the most broadly applicable solution.

public static string ReplaceCaseInsensitiveFind(this string str, string findMe,
    string newValue)
{
    return Regex.Replace(str,
        Regex.Escape(findMe),
        Regex.Replace(newValue, "\\$[0-9]+", @"$$$0"),
        RegexOptions.IgnoreCase);
}

So...

  • This is an extension method @MarkRobinson
  • This doesn't try to skip Regex @Helge (you really have to do byte-by-byte if you want to string sniff like this outside of Regex)
  • Passes @MichaelLiu 's excellent test case, "œ".ReplaceCaseInsensitiveFind("oe", ""), though he may have had a slightly different behavior in mind.

Unfortunately, @HA 's comment that you have to Escape all three isn't correct. The initial value and newValue doesn't need to be.

Note: You do, however, have to escape $s in the new value that you're inserting if they're part of what would appear to be a "captured value" marker. Thus the three dollar signs in the Regex.Replace inside the Regex.Replace [sic]. Without that, something like this breaks...

"This is HIS fork, hIs spoon, hissssssss knife.".ReplaceCaseInsensitiveFind("his", @"he$0r")

Here's the error:

An unhandled exception of type 'System.ArgumentException' occurred in System.dll

Additional information: parsing "The\hisr\ is\ he\HISr\ fork,\ he\hIsr\ spoon,\ he\hisrsssssss\ knife\." - Unrecognized escape sequence \h.

Tell you what, I know folks that are comfortable with Regex feel like their use avoids errors, but I'm often still partial to byte sniffing strings (but only after having read Spolsky on encodings) to be absolutely sure you're getting what you intended for important use cases. Reminds me of Crockford on "insecure regular expressions" a little. Too often we write regexps that allow what we want (if we're lucky), but unintentionally allow more in (eg, Is $10 really a valid "capture value" string in my newValue regexp, above?) because we weren't thoughtful enough. Both methods have value, and both encourage different types of unintentional errors. It's often easy to underestimate complexity.

That weird $ escaping (and that Regex.Escape didn't escape captured value patterns like $0 as I would have expected in replacement values) drove me mad for a while. Programming Is Hard (c) 1842

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

How to read a file in reverse order?

Always use with when working with files as it handles everything for you:

with open('filename', 'r') as f:
    for line in reversed(f.readlines()):
        print line

Or in Python 3:

with open('filename', 'r') as f:
    for line in reversed(list(f.readlines())):
        print(line)

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

T-SQL string replace in Update

The syntax for REPLACE:

REPLACE (string_expression,string_pattern,string_replacement)

So that the SQL you need should be:

UPDATE [DataTable] SET [ColumnValue] = REPLACE([ColumnValue], 'domain2', 'domain1')

How to Convert string "07:35" (HH:MM) to TimeSpan

You can convert the time using the following code.

TimeSpan _time = TimeSpan.Parse("07:35");

But if you want to get the current time of the day you can use the following code:

TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;

The result will be:

03:54:35.7763461

With a object cantain the Hours, Minutes, Seconds, Ticks and etc.

error: expected declaration or statement at end of input in c

For me this problem was caused by a missing ) at the end of an if statement in a function called by the function the error was reported as from. Try scrolling up in the output to find the first error reported by the compiler. Fixing that error may fix this error.

How do I position an image at the bottom of div?

Using flexbox:

HTML:

<div class="wrapper">
    <img src="pikachu.gif"/>
</div>

CSS:

.wrapper {
    height: 300px;
    width: 300px;
    display: flex;
    align-items: flex-end;
}

As requested in some comments on another answer, the image can also be horizontally centred with justify-content: center;

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

<select [(ngModel)]="selectedcarrera" (change)="mostrardatos()" class="form-control" name="carreras">
    <option *ngFor="let x of carreras" [ngValue]="x"> {{x.nombre}} </option>
</select>

In ts

mostrardatos(){

}

How to use underscore.js as a template engine?

with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :

npm install consolidate --save

then you should change the default engine to html template by this:

app.set('view engine', 'html');

register the underscore template engine for the html extension:

app.engine('html', require('consolidate').underscore);

it's done !

Now for load for example an template called 'index.html':

res.render('index', { title : 'my first page'});

maybe you will need to install the underscore module.

npm install underscore --save

I hope this helped you!

Best way to require all files from a directory in ruby?

And what about: require_relative *Dir['relative path']?

XML Schema (XSD) validation tool?

http://www.xmlvalidation.com/

(Be sure to check the " Validate against external XML schema" Box)

Converting camel case to underscore case in ruby

The ruby core itself has no support to convert a string from (upper) camel case to (also known as pascal case) to underscore (also known as snake case).

So you need either to make your own implementation or use an existing gem.

There is a small ruby gem called lucky_case which allows you to convert a string from any of the 10+ supported cases to another case easily:

require 'lucky_case'

# convert to snake case string
LuckyCase.snake_case('CamelCaseString')      # => 'camel_case_string'
# or the opposite way
LuckyCase.pascal_case('camel_case_string')   # => 'CamelCaseString'

You can even monkey patch the String class if you want to:

require 'lucky_case/string'

'CamelCaseString'.snake_case  # => 'camel_case_string'
'CamelCaseString'.snake_case! # => 'camel_case_string' and overwriting original

Have a look at the offical repository for more examples and documentation:

https://github.com/magynhard/lucky_case

Export HTML table to pdf using jspdf

You can also use the jsPDF-AutoTable plugin. You can check out a demo here that uses the following code.

var doc = new jsPDF('p', 'pt');
var elem = document.getElementById("basic-table");
var res = doc.autoTableHtmlToJson(elem);
doc.autoTable(res.columns, res.data);
doc.save("table.pdf");

How to enable local network users to access my WAMP sites?

Put your wamp server onlineenter image description here

and then go to control panel > system and security > windows firewall and turn windows firewall off

now you can access your wamp server from another computer over local network by the network IP of computer which have wamp server installed like http://192.168.2.34/mysite

Convert long/lat to pixel x/y on a given picture

my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823

How to check whether a string is Base64 encoded or not

There are many variants of Base64, so consider just determining if your string resembles the varient you expect to handle. As such, you may need to adjust the regex below with respect to the index and padding characters (i.e. +, /, =).

class String
  def resembles_base64?
    self.length % 4 == 0 && self =~ /^[A-Za-z0-9+\/=]+\Z/
  end
end

Usage:

raise 'the string does not resemble Base64' unless my_string.resembles_base64?

How to trim a string in SQL Server before 2017?

SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer

How do I calculate tables size in Oracle

Correction for partitioned tables:

SELECT owner, table_name, ROUND(sum(bytes)/1024/1024/1024, 2) GB
FROM
(SELECT segment_name table_name, owner, bytes
 FROM dba_segments
 WHERE segment_type IN ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')
 UNION ALL
 SELECT i.table_name, i.owner, s.bytes
 FROM dba_indexes i, dba_segments s
 WHERE s.segment_name = i.index_name
 AND   s.owner = i.owner
 AND   s.segment_type IN ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')
 UNION ALL
 SELECT l.table_name, l.owner, s.bytes
 FROM dba_lobs l, dba_segments s
 WHERE s.segment_name = l.segment_name
 and   s.owner = l.owner
 AND   s.segment_type in ('LOBSEGMENT', 'LOB PARTITION', 'LOB SUBPARTITION')
 UNION ALL
 SELECT l.table_name, l.owner, s.bytes
 FROM dba_lobs l, dba_segments s
 WHERE s.segment_name = l.index_name
 AND   s.owner = l.owner
 AND   s.segment_type = 'LOBINDEX')
WHERE owner in UPPER('&owner')
GROUP BY table_name, owner
HAVING SUM(bytes)/1024/1024 > 10  /* Ignore really small tables */
order by sum(bytes) desc
;

If a folder does not exist, create it

Just write this line:

System.IO.Directory.CreateDirectory("my folder");
  • If the folder does not exist yet, it will be created.
  • If the folder exists already, the line will be ignored.

Reference: Article about Directory.CreateDirectory at MSDN

Of course, you can also write using System.IO; at the top of the source file and then just write Directory.CreateDirectory("my folder"); every time you want to create a folder.

Copy multiple files in Python

If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*") to get a list of all the filenames, loop over the list and use shutil.copy to copy each file.

for filename in glob.glob(os.path.join(source_dir, '*.*')):
    shutil.copy(filename, dest_dir)

Bootstrap 3 Horizontal and Vertical Divider

I made the following little scss mixin to build for all the bootstrap breakpoints...

With it I get .col-xs-divider-left or col-lg-divider-right etc.

Note: this uses v4-alpha bootstrap syntax...

@import 'variables';

$divider-height: 100%;

@mixin make-column-dividers($breakpoints: $grid-breakpoints) {
    // Common properties for all breakpoints
    %col-divider {
        position: absolute;
        content: " ";
        top: (100% - $divider-height)/2;
        height: $divider-height;
        width: $hr-border-width;
        background-color: $hr-border-color;
    }
    @each $breakpoint in map-keys($breakpoints) {
        .col-#{$breakpoint}-divider-right:before {
            @include media-breakpoint-up($breakpoint) {
                @extend %col-divider;
                right: 0;
            }
        }
        .col-#{$breakpoint}-divider-left:before {
            @include media-breakpoint-up($breakpoint) {
                @extend %col-divider;
                left: 0;
            }
        }
    }
}

Get full path of the files in PowerShell

Here's a shorter one:

(Get-ChildItem C:\MYDIRECTORY -Recurse).fullname > filename.txt

What is "string[] args" in Main class for?

The args parameter stores all command line arguments which are given by the user when you run the program.

If you run your program from the console like this:

program.exe there are 4 parameters

Your args parameter will contain the four strings: "there", "are", "4", and "parameters"

Here is an example of how to access the command line arguments from the args parameter: example

How to get row from R data.frame

Try:

> d <- data.frame(a=1:3, b=4:6, c=7:9)

> d
  a b c
1 1 4 7
2 2 5 8
3 3 6 9

> d[1, ]
  a b c
1 1 4 7

> d[1, ]['a']
  a
1 1

Copy rows from one table to another, ignoring duplicates

Something like this?:

INSERT INTO destTable
SELECT s.* FROM srcTable s
LEFT JOIN destTable d ON d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...
WHERE d.Key1 IS NULL

Has anyone gotten HTML emails working with Twitter Bootstrap?

The trick here is that you don't want to include the whole bootstrap. The issue is that email clients will ignore the media queries and process all the print styles which have a lot of !important statements.

Instead, you need to only include the specific parts of bootstrap that you need. My email.css.scss file looks like this:

@import "bootstrap-sprockets";
@import "bootstrap/variables";
@import "bootstrap/mixins";
@import "bootstrap/scaffolding";
@import "bootstrap/type";
@import "bootstrap/buttons";
@import "bootstrap/alerts";

@import 'bootstrap/normalize';
@import 'bootstrap/tables';

Upgrading PHP on CentOS 6.5 (Final)

I managed to install php54w according to Simon's suggestion, but then my sites stopped working perhaps because of an incompatibility with php-mysql or some other module. Even frantically restoring the old situation was not amusing: for anyone in my own situation the sequence is:

sudo yum remove php54w
sudo yum remove php54w-common
sudo yum install php-common
sudo yum install php-mysql
sudo yum install php

It would be nice if someone submitted the full procedure to update all the php packet. That was my production server and my heart is still rapidly beating.

Android TextView Justify Text

For html formating you don't need to call the Webkit, you could use Html.fromHtml(text) to do the job.

Source : http://developer.android.com/guide/topics/resources/string-resource.html

Display Python datetime without time

For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:

date = datetime.datetime.utcnow()

start_of_day = date - datetime.timedelta(
    hours=date.hour, 
    minutes=date.minute, 
    seconds=date.second, 
    microseconds=date.microsecond
)

end_of_day = start_of_day + datetime.timedelta(
    hours=23, 
    minutes=59, 
    seconds=59
)

Example output:

>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)

laravel foreach loop in controller

Is sku just a property of the Product model? If so:

$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();

foreach ($products as $product ) {
  // Access $product->sku here...
}

Or is sku a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.

What does '<?=' mean in PHP?

It's a shorthand for this:

<?php echo $a; ?>

They're called short tags; see example #2 in the documentation.

how to increase java heap memory permanently?

Please note that increasing the Java heap size following an java.lang.OutOfMemoryError: Java heap space is quite often just a short term solution.

This means that even if you increase the default Java heap size from 512 MB to let's say 2048 MB, you may still get this error at some point if you are dealing with a memory leak. The main question to ask is why are you getting this OOM error at the first place? Is it really a Xmx value too low or just a symptom of another problem?

When developing a Java application, it is always crucial to understand its static and dynamic memory footprint requirement early on, this will help prevent complex OOM problems later on. Proper sizing of JVM Xms & Xmx settings can be achieved via proper application profiling and load testing.

Best way to find if an item is in a JavaScript array?

[ ].has(obj)

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
{
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        }
        return false;                       
    },
    // writable:false,
    // enumerable:false
})

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

the use of 2nd arg (flag) forces comparation by value instead of reference

comparing raw objects

[o1].has(o2,true) // true if every level value is same

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

For more information about .scrollHeight property refer to the docs:

The Element.scrollHeight read-only attribute is a measurement of the height of an element's content, including content not visible on the screen due to overflow. The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar. It includes the element padding but not its margin.

How to select distinct query using symfony2 doctrine query builder?

you could write

select DISTINCT f from t;

as

select f from t group by f;

thing is, I am just currently myself getting into Doctrine, so I cannot give you a real answer. but you could as shown above, simulate a distinct with group by and transform that into Doctrine. if you want add further filtering then use HAVING after group by.

Get current time in milliseconds in Python?

If you're concerned about measuring elapsed time, you should use the monotonic clock (python 3). This clock is not affected by system clock updates like you would see if an NTP query adjusted your system time, for example.

>>> import time
>>> millis = round(time.monotonic() * 1000)

It provides a reference time in seconds that can be used to compare later to measure elapsed time.

java.io.IOException: Broken pipe

You may have not set the output file.

HTML5 Canvas vs. SVG vs. div

I agree with Simon Sarris's conclusions:

I have compared some visualization in Protovis (SVG) to Processingjs (Canvas) which display > 2000 points and processingjs is much faster than protovis.

Handling events with SVG is of course much easer because you can attach them to the objects. In Canvas you have to do it manually (check mouse position, etc) but for simple interaction it shouldn't be hard.

There is also the dojo.gfx library of the dojo toolkit. It provides an abstraction layer and you can specify the renderer (SVG, Canvas, Silverlight). That might be also an viable choice although I don't know how much overhead the additional abstraction layer adds but it makes it easy to code interactions and animations and is renderer-agnostic.

Here are some interesting benchmarks:

Leaflet changing Marker color

I found the SVG marker/icon to be best one yet. It is very flexible and allows any color you like. You can customize the entire icon without much of a hassle:

function createIcon(markerColor) {
  /* ...Code ommitted ... */

  return new L.DivIcon.SVGIcon({
            color: markerColor,
            iconSize: [15,30],
            circleRatio: 0.35
  });
}

Laravel Eloquent where field is X or null

You could merge two queries together:

$merged = $query_one->merge($query_two);

How to include a font .ttf using CSS?

You can use font face like this:

@font-face {
  font-family:"Name-Of-Font";
  src: url("yourfont.ttf") format("truetype");
}

Extracting date from a string in Python

Using python-dateutil:

In [1]: import dateutil.parser as dparser

In [18]: dparser.parse("monkey 2010-07-10 love banana",fuzzy=True)
Out[18]: datetime.datetime(2010, 7, 10, 0, 0)

Invalid dates raise a ValueError:

In [19]: dparser.parse("monkey 2010-07-32 love banana",fuzzy=True)
# ValueError: day is out of range for month

It can recognize dates in many formats:

In [20]: dparser.parse("monkey 20/01/1980 love banana",fuzzy=True)
Out[20]: datetime.datetime(1980, 1, 20, 0, 0)

Note that it makes a guess if the date is ambiguous:

In [23]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True)
Out[23]: datetime.datetime(1980, 10, 1, 0, 0)

But the way it parses ambiguous dates is customizable:

In [21]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True, dayfirst=True)
Out[21]: datetime.datetime(1980, 1, 10, 0, 0)

Asyncio.gather vs asyncio.wait

I also noticed that you can provide a group of coroutines in wait() by simply specifying the list:

result=loop.run_until_complete(asyncio.wait([
        say('first hello', 2),
        say('second hello', 1),
        say('third hello', 4)
    ]))

Whereas grouping in gather() is done by just specifying multiple coroutines:

result=loop.run_until_complete(asyncio.gather(
        say('first hello', 2),
        say('second hello', 1),
        say('third hello', 4)
    ))

Can you get a Windows (AD) username in PHP?

Check the AUTH_USER request variable. This will be empty if your web app allows anonymous access, but if your server's using basic or Windows integrated authentication, it will contain the username of the authenticated user.

In an Active Directory domain, if your clients are running Internet Explorer and your web server/filesystem permissions are configured properly, IE will silently submit their domain credentials to your server and AUTH_USER will be MYDOMAIN\user.name without the users having to explicitly log in to your web app.

How to initialize java.util.date to empty

Instance of java.util.Date stores a date. So how can you store nothing in it or have it empty? It can only store references to instances of java.util.Date. If you make it null means that it is not referring any instance of java.util.Date.

You have tried date2=""; what you mean to do by this statement you want to reference the instance of String to a variable that is suppose to store java.util.Date. This is not possible as Java is Strongly Typed Language.

Edit

After seeing the comment posted to the answer of LastFreeNickname

I am having a form that the date textbox should be by default blank in the textbox, however while submitting the data if the user didn't enter anything, it should accept it

I would suggest you could check if the textbox is empty. And if it is empty, then you could store default date in your variable or current date or may be assign it null as shown below:

if(textBox.getText() == null || textBox.getText().equals(""){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

Also I can assume since you are asking user to enter a date in a TextBox, you are using a DateFormat to parse the text that is entered in the TextBox. If this is the case you could simply call the dateFormat.parse() which throws a ParseException if the format in which the date was written is incorrect or is empty string. Here in the catch block you could put the above statements as show below:

try{
    date2 = dateFormat.parse(textBox.getText());
}catch(ParseException e){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

Inserting a Python datetime.datetime object into MySQL

If you're just using a python datetime.date (not a full datetime.datetime), just cast the date as a string. This is very simple and works for me (mysql, python 2.7, Ubuntu). The column published_date is a MySQL date field, the python variable publish_date is datetime.date.

# make the record for the passed link info
sql_stmt = "INSERT INTO snippet_links (" + \
    "link_headline, link_url, published_date, author, source, coco_id, link_id)" + \
    "VALUES(%s, %s, %s, %s, %s, %s, %s) ;"

sql_data = ( title, link, str(publish_date), \
             author, posted_by, \
             str(coco_id), str(link_id) )

try:
    dbc.execute(sql_stmt, sql_data )
except Exception, e:
    ...

How to read files and stdout from a running Docker container

Sharing files between a docker container and the host system, or between separate containers is best accomplished using volumes.

Having your app running in another container is probably your best solution since it will ensure that your whole application can be well isolated and easily deployed. What you're trying to do sounds very close to the setup described in this excellent blog post, take a look!

Microsoft.ACE.OLEDB.12.0 provider is not registered

See my post on a similar Stack Exchange thread https://stackoverflow.com/a/21455677/1368849

I had version 15, not 12 installed, which I found out by running this PowerShell code...

(New-Object system.data.oledb.oledbenumerator).GetElements() | select SOURCES_NAME, SOURCES_DESCRIPTION

...which gave me this result (I've removed other data sources for brevity)...

SOURCES_NAME              SOURCES_DESCRIPTION                                                                       
------------              -------------------                                                                       
Microsoft.ACE.OLEDB.15.0  Microsoft Office 15.0 Access Database Engine OLE DB Provider

Importing a long list of constants to a Python file

As an alternative to using the import approach described in several answers, have a look a the configparser module.

The ConfigParser class implements a basic configuration file parser language which provides a structure similar to what you would find on Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

I had the same problem then i fixed it by following code!

  text = (EditText)findViewById(R.id.TextVoiceeditText); 
  text.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

You can convert your Delete method as POST as;

 [HttpPost]
 public void Delete(YourDomainModel itemToDelete)
 {
 }

SelectSingleNode returning null for known good xml node path using XPath

I strongly suspect the problem is to do with namespaces. Try getting rid of the namespace and you'll be fine - but obviously that won't help in your real case, where I'd assume the document is fixed.

I can't remember offhand how to specify a namespace in an XPath expression, but I'm sure that's the problem.

EDIT: Okay, I've remembered how to do it now. It's not terribly pleasant though - you need to create an XmlNamespaceManager for it. Here's some sample code that works with your sample document:

using System;
using System.Xml;

public class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
        namespaces.AddNamespace("ns", "urn:hl7-org:v3");
        doc.Load("test.xml");
        XmlNode idNode = doc.SelectSingleNode("/My_RootNode/ns:id", namespaces);
        string msgID = idNode.Attributes["extension"].Value;
        Console.WriteLine(msgID);
    }
}

Can you use @Autowired with static fields?

@Autowired can be used with setters so you could have a setter modifying an static field.

Just one final suggestion... DON'T

How to join two sets in one line without using "|"

You can just unpack both sets into one like this:

>>> set_1 = {1, 2, 3, 4}
>>> set_2 = {3, 4, 5, 6}
>>> union = {*set_1, *set_2}
>>> union
{1, 2, 3, 4, 5, 6}

The * unpacks the set. Unpacking is where an iterable (e.g. a set or list) is represented as every item it yields. This means the above example simplifies to {1, 2, 3, 4, 3, 4, 5, 6} which then simplifies to {1, 2, 3, 4, 5, 6} because the set can only contain unique items.

How can I convert string to datetime with format specification in JavaScript?

To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822, if you use yyyy-mm-dd parse may do a mistakes.

How can I see the current value of my $PATH variable on OS X?

You need to use the command echo $PATH to display the PATH variable or you can just execute set or env to display all of your environment variables.

By typing $PATH you tried to run your PATH variable contents as a command name.

Bash displayed the contents of your path any way. Based on your output the following directories will be searched in the following order:

/usr/local/share/npm/bin
/Library/Frameworks/Python.framework/Versions/2.7/bin
/usr/local/bin
/usr/local/sbin
~/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/opt/X11/bin
/usr/local/git/bin

To me this list appears to be complete.

SQL - ORDER BY 'datetime' DESC

Try:

SELECT post_datetime 
FROM post 
WHERE type = 'published' 
ORDER BY post_datetime DESC 
LIMIT 3

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

Making div content responsive

Not a lot to go on there, but I think what you're looking for is to flip the width and max-width values:

#container2 {
  width: 90%;
  max-width: 960px;
  /* etc, etc... */
}

That'll give you a container that's 90% of the width of the available space, up to a maximum of 960px, but that's dependent on its container being resizable itself. Responsive design is a whole big ball of wax though, so this doesn't even scratch the surface.

Get HTML code using JavaScript with a URL

Edit: doesnt work yet...

Add this to your JS:

var src = fetch('https://page.com')

It saves the source of page.com to variable 'src'

Import MySQL database into a MS SQL Server

Run:

mysqldump -u root -p your_target_DB --compatible=mssql > MSSQL_Compatible_Data.sql

Do you want to see a process bar?

pv mysqldump -u root -p your_target_DB --compatible=mssql > MSSQL_Compatible_Data.sql

Java 8 lambdas, Function.identity() or t->t

In your example there is no big difference between str -> str and Function.identity() since internally it is simply t->t.

But sometimes we can't use Function.identity because we can't use a Function. Take a look here:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);

this will compile fine

int[] arrayOK = list.stream().mapToInt(i -> i).toArray();

but if you try to compile

int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();

you will get compilation error since mapToInt expects ToIntFunction, which is not related to Function. Also ToIntFunction doesn't have identity() method.

Using generic std::function objects with member functions in one class

A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.

Because your std::function signature specifies that your function doesn't take any arguments (<void(void)>), you must bind the first (and the only) argument.

std::function<void(void)> f = std::bind(&Foo::doSomething, this);

If you want to bind a function with parameters, you need to specify placeholders:

using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);

Or, if your compiler supports C++11 lambdas:

std::function<void(int,int)> f = [=](int a, int b) {
    this->doSomethingArgs(a, b);
}

(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)

How to run (not only install) an android application using .apk file?

First to install your app:

adb install -r path\ProjectName.apk

The great thing about the -r is it works even if it wasn’t already installed.

To launch MainActivity, so you can launch it like:

adb shell am start -n com.other.ProjectName/.MainActivity

Android Device not recognized by adb

It may sound silly but in my case the USB cable was too long (even if good quality). It worked with my tablet but not with the phone. To check this, if you run on Linux run lsusb to make sure that your device is at least officially connect to the usb port.

Change image source with JavaScript

I know this question is old, but for the one's what are new, here is what you can do:

HTML

<img id="demo" src="myImage.png">

<button onclick="myFunction()">Click Me!</button>

JAVASCRIPT

function myFunction() {
document.getElementById('demo').src = "myImage.png";
}

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Finally, I got a solution!

My Context is:- I want disconnect socket connection when activity destroyed, I tried to finish() activity but it didn't work me, its keep connection live somewhere.

so I use android.os.Process.killProcess(android.os.Process.myPid()); its kill my activity and i used android:excludeFromRecents="true" for remove from recent activity .

AngularJS Error: $injector:unpr Unknown Provider

also one of the popular reasons maybe you miss to include the service file in your page

<script src="myservice.js"></script>

Split string into string array of single characters

Simple!!
one line:

 var res = test.Select(x => new string(x, 1)).ToArray();

Convert a PHP object to an associative array

Also you can use The Symfony Serializer Component

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$array = json_decode($serializer->serialize($object, 'json'), true);

Laravel 5.2 not reading env file

Tried almost all of the above. Ended up doing

chmod 666 .env

which worked. This problem seems to keep cropping up on the app I inherited however, this most recent time was after adding a .env.testing. Running Laravel 5.8

Deprecated Java HttpClient - How hard can it be?

I would suggest using the below method if you are trying to read the json data only.

URL requestUrl=new URL(url);
URLConnection con = requestUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
int cp;
try {
    while((cp=rd.read())!=-1){
    sb.append((char)cp);
  }
 catch(Exception e){
 }
 String json=sb.toString();

Cannot load properties file from resources directory

I think you need to put it under src/main/resources and load it as follows:

props.load(new FileInputStream("src/main/resources/myconf.properties"));

The way you are trying to load it will first check in base folder of your project. If it is in target/classes and you want to load it from there do the following:

props.load(new FileInputStream("target/classes/myconf.properties"));

How to parse SOAP XML?

First, we need to filter the XML so as to parse that change objects become array

//catch xml
$xmlElement = file_get_contents ('php://input');
//change become array
$Data = (array)simplexml_load_string($xmlElement);
//and see
print_r($Data);

How to correct TypeError: Unicode-objects must be encoded before hashing?

You must have to define encoding format like utf-8, Try this easy way,

This example generates a random number using the SHA256 algorithm:

>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'

How do I remove blue "selected" outline on buttons?

You can remove this by adding !important to your outline.

button{
 outline: none !important;
}

Spring Boot access static resources missing scr/main/resources

I use spring boot, so i can simple use:

File file = ResourceUtils.getFile("classpath:myfile.xml");

How to get summary statistics by group

While some of the other approaches work, this is pretty close to what you were doing and only uses base r. If you know the aggregate command this may be more intuitive.

with( df , aggregate( dt , by=list(group) , FUN=summary)  )

How to change the window title of a MATLAB plotting figure?

First you must create an empty figure with the following command.

figure('name','Title of the window here');

By doing this, the newly created figure becomes you active figure. Immediately after calling a plot() command, it will print your plotting onto this figure. So your window will have a title.

This is the code you must use:

figure('name','Title of the window here');

hold on

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');

hold off

title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');

Right way to split an std::string into a vector<string>

i made this custom function that will convert the line to vector

#include <iostream>
#include <vector>
#include <ctime>
#include <string>

using namespace std;

int main(){

    string line;
    getline(cin, line);
    int len = line.length();
    vector<string> subArray;

    for (int j = 0, k = 0; j < len; j++) {
        if (line[j] == ' ') {
            string ch = line.substr(k, j - k);
            k = j+1;
            subArray.push_back(ch);
        }
        if (j == len - 1) {
            string ch = line.substr(k, j - k+1);
            subArray.push_back(ch);
        }
    }

    return 0;
}

How can I split a text file using PowerShell?

My requirement was a bit different. I often work with Comma Delimited and Tab Delimited ASCII files where a single line is a single record of data. And they're really big, so I need to split them into manageable parts (whilst preserving the header row).

So, I reverted back to my classic VBScript method and bashed together a small .vbs script that can be run on any Windows computer (it gets automatically executed by the WScript.exe script host engine on Window).

The benefit of this method is that it uses Text Streams, so the underlying data isn't loaded into memory (or, at least, not all at once). The result is that it's exceptionally fast and it doesn't really need much memory to run. The test file I just split using this script on my i7 was about 1 GB in file size, had about 12 million lines of text and was split into 25 part files (each with about 500k lines each) – the processing took about 2 minutes and it didn’t go over 3 MB memory used at any point.

The caveat here is that it relies on the text file having "lines" (meaning each record is delimited with a CRLF) as the Text Stream object uses the "ReadLine" function to process a single line at a time. But hey, if you're working with TSV or CSV files, it's perfect.

Option Explicit

Private Const INPUT_TEXT_FILE = "c:\bigtextfile.txt"  
Private Const REPEAT_HEADER_ROW = True                
Private Const LINES_PER_PART = 500000                 

Dim oFileSystem, oInputFile, oOutputFile, iOutputFile, iLineCounter, sHeaderLine, sLine, sFileExt, sStart

sStart = Now()

sFileExt = Right(INPUT_TEXT_FILE,Len(INPUT_TEXT_FILE)-InstrRev(INPUT_TEXT_FILE,".")+1)
iLineCounter = 0
iOutputFile = 1

Set oFileSystem = CreateObject("Scripting.FileSystemObject")
Set oInputFile = oFileSystem.OpenTextFile(INPUT_TEXT_FILE, 1, False)
Set oOutputFile = oFileSystem.OpenTextFile(Replace(INPUT_TEXT_FILE, sFileExt, "_" & iOutputFile & sFileExt), 2, True)

If REPEAT_HEADER_ROW Then
    iLineCounter = 1
    sHeaderLine = oInputFile.ReadLine()
    Call oOutputFile.WriteLine(sHeaderLine)
End If

Do While Not oInputFile.AtEndOfStream
    sLine = oInputFile.ReadLine()
    Call oOutputFile.WriteLine(sLine)
    iLineCounter = iLineCounter + 1
    If iLineCounter Mod LINES_PER_PART = 0 Then
        iOutputFile = iOutputFile + 1
        Call oOutputFile.Close()
        Set oOutputFile = oFileSystem.OpenTextFile(Replace(INPUT_TEXT_FILE, sFileExt, "_" & iOutputFile & sFileExt), 2, True)
        If REPEAT_HEADER_ROW Then
            Call oOutputFile.WriteLine(sHeaderLine)
        End If
    End If
Loop

Call oInputFile.Close()
Call oOutputFile.Close()
Set oFileSystem = Nothing

Call MsgBox("Done" & vbCrLf & "Lines Processed:" & iLineCounter & vbCrLf & "Part Files: " & iOutputFile & vbCrLf & "Start Time: " & sStart & vbCrLf & "Finish Time: " & Now())

How to "add existing frameworks" in Xcode 4?

The frameworks directory is as follow in my computer: /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/System/Library/Frameworks

not the directory

/Developer/SDKs/MacOSXversion.sdk/System/Library/Frameworks

How to get the device's IMEI/ESN programmatically in android?

Try this(need to get first IMEI always)

TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(LoginActivity.this,Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {

         return;
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (mTelephony.getPhoneCount() == 2) {
                    IME = mTelephony.getImei(0);
                }else{
                    IME = mTelephony.getImei();
                }
            }else{
                if (mTelephony.getPhoneCount() == 2) {
                    IME = mTelephony.getDeviceId(0);
                } else {
                    IME = mTelephony.getDeviceId();
                }
            }
        } else {
            IME = mTelephony.getDeviceId();
        }

SQL Server : error converting data type varchar to numeric

I think the problem is not in sub-query but in WHERE clause of outer query. When you use

WHERE account_code between 503100 and 503105

SQL server will try to convert every value in your Account_code field to integer to test it in provided condition. Obviously it will fail to do so if there will be non-integer characters in some rows.

Do you get charged for a 'stopped' instance on EC2?

Short answer - no.

You will only be charged for the time that your instance is up and running, in hour increments. If you are using other services in conjunction you may be charged for those but it would be separate from your server instance.

How to add to an NSDictionary

When ever the array is declared, then only we have to add the key-value's in NSDictionary like

NSDictionary *normalDict = [[NSDictionary alloc]initWithObjectsAndKeys:@"Value1",@"Key1",@"Value2",@"Key2",@"Value3",@"Key3",nil];

we cannot add or remove the key values in this NSDictionary

Where as in NSMutableDictionary we can add the objects after intialization of array also by using this method

NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc]init];'
[mutableDict setObject:@"Value1" forKey:@"Key1"];
[mutableDict setObject:@"Value2" forKey:@"Key2"];
[mutableDict setObject:@"Value3" forKey:@"Key3"];

for removing the key value we have to use the following code

[mutableDict removeObject:@"Value1" forKey:@"Key1"];

Hadoop/Hive : Loading data from .csv on a local machine

if you have a hive setup you can put the local dataset directly using Hive load command in hdfs/s3.

You will need to use "Local" keyword when writing your load command.

Syntax for hiveload command

LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]

Refer below link for more detailed information. https://cwiki.apache.org/confluence/display/Hive/LanguageManual%20DML#LanguageManualDML-Loadingfilesintotables

C# loop - break vs. continue

break causes the program counter to jump out of the scope of the innermost loop

for(i = 0; i < 10; i++)
{
    if(i == 2)
        break;
}

Works like this

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto BREAK;
}
BREAK:;

continue jumps to the end of the loop. In a for loop, continue jumps to the increment expression.

for(i = 0; i < 10; i++)
{
    if(i == 2)
        continue;

    printf("%d", i);
}

Works like this

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto CONTINUE;

    printf("%d", i);

    CONTINUE:;
}

How can I reorder my divs using only CSS?

Little late to the party, but you can also do this:

<div style="height: 500px; width: 500px;">

<div class="bottom" style="height: 250px; width: 500px; background: red; margin-top: 250px;"></div>

<div class="top" style="height: 250px; width: 500px; background: blue; margin-top: -500px;"></div>

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

You'll have to pass your arguments as reference types.

#First create the variables (note you have to set them to something)
$global:var1 = $null
$global:var2 = $null
$global:var3 = $null

#The type of the reference argument should be of type [REF]
function foo ($a, $b, [REF]$c)
{
    # add $a and $b and set the requested global variable to equal to it
    # Note how you modify the value.
    $c.Value = $a + $b
}

#You can then call it like this:
foo 1 2 [REF]$global:var3

How do I update a model value in JavaScript in a Razor view?

This should work

function updatePostID(val)
{
    document.getElementById('PostID').value = val;

    //and probably call document.forms[0].submit();
}

Then have a hidden field or other control for the PostID

@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)

jQuery scroll to ID from different page

I made a reusable plugin that can do this... I left the binding to events outside the plugin itself because I feel it is too intrusive for such a little helper....

jQuery(function ($) {

    /**
     * This small plugin will scrollTo a target, smoothly
     *
     * First argument = time to scroll to the target
     * Second argument = set the hash in the current url yes or no
     */
    $.fn.smoothScroll = function(t, setHash) {
        // Set time to t variable to if undefined 500 for 500ms transition
        t = t || 500;
        setHash = (typeof setHash == 'undefined') ? true : setHash;

        // Return this as a proper jQuery plugin should
        return this.each(function() {
            $('html, body').animate({
                scrollTop: $(this).offset().top
            }, t);

            // Lets set the hash to the current ID since if an event was prevented this doesn't get done
            if (this.id && setHash) {
                window.location.hash = this.id;
            }
        });
    };

});

Now next, we can onload just do this, check for a hash and if its there try to use it directly as a selector for jQuery. Now I couldn't easily test this at the time but I made similar stuff for production sites not long ago, if this doesn't immediatly work let me know and I'll look into the solution I got there.

(script should be within an onload section)

if (window.location.hash) {
    window.scrollTo(0,0);
    $(window.location.hash).smoothScroll();
}

Next we bind the plugin to onclick of anchors which only contain a hash in their href attribute.

(script should be within an onload section)

$('a[href^="#"]').click(function(e) {
    e.preventDefault();

    $($(this).attr('href')).smoothScroll();
});

Since jQuery doesn't do anything if the match itself fails we have a nice fallback for when a target on a page can't be found yay \o/

Update

Alternative onclick handler to scroll to the top when theres only a hash:

$('a[href^="#"]').click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');

    // In this case we have only a hash, so maybe we want to scroll to the top of the page?
    if(href.length === 1) { href = 'body' }

    $(href).smoothScroll();
});

Here is also a simple jsfiddle that demonstrates the scrolling within page, onload is a little hard to set up...

http://jsfiddle.net/sg3s/bZnWN/

Update 2

So you might get in trouble with the window already scrolling to the element onload. This fixes that: window.scrollTo(0,0); it just scrolls the page to the left top. Added it to the code snippet above.

Calling a javascript function recursively

I know this is an old question, but I thought I'd present one more solution that could be used if you'd like to avoid using named function expressions. (Not saying you should or should not avoid them, just presenting another solution)

  var fn = (function() {
    var innerFn = function(counter) {
      console.log(counter);

      if(counter > 0) {
        innerFn(counter-1);
      }
    };

    return innerFn;
  })();

  console.log("running fn");
  fn(3);

  var copyFn = fn;

  console.log("running copyFn");
  copyFn(3);

  fn = function() { console.log("done"); };

  console.log("fn after reassignment");
  fn(3);

  console.log("copyFn after reassignment of fn");
  copyFn(3);

Datetime BETWEEN statement not working in SQL Server

You don't have any error in either of your queries. My guess is the following:

  • No records exists between 2013-10-17' and '2013-10-18'
  • the records the second query returns you exist after '2013-10-18'

Excel VBA function to print an array to the workbook

A more elegant way is to assign the whole array at once:

Sub PrintArray(Data, SheetName, StartRow, StartCol)

    Dim Rng As Range

    With Sheets(SheetName)
        Set Rng = .Range(.Cells(StartRow, StartCol), _
            .Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
            UBound(Data, 2) - LBound(Data, 2) + StartCol))
    End With
    Rng.Value2 = Data

End Sub

But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

    **Divide a list to lists of n size**

    import java.util.AbstractList;
    import java.util.ArrayList;
    import java.util.List;

    public final class PartitionUtil<T> extends AbstractList<List<T>> {

        private final List<T> list;
        private final int chunkSize;

        private PartitionUtil(List<T> list, int chunkSize) {
            this.list = new ArrayList<>(list);
            this.chunkSize = chunkSize;
        }

        public static <T> PartitionUtil<T> ofSize(List<T> list, int chunkSize) {
            return new PartitionUtil<>(list, chunkSize);
        }

        @Override
        public List<T> get(int index) {
            int start = index * chunkSize;
            int end = Math.min(start + chunkSize, list.size());

            if (start > end) {
                throw new IndexOutOfBoundsException("Index " + index + " is out of the list range <0," + (size() - 1) + ">");
            }

            return new ArrayList<>(list.subList(start, end));
        }

        @Override
        public int size() {
            return (int) Math.ceil((double) list.size() / (double) chunkSize);
        }
    }





Function call : 
              List<List<String>> containerNumChunks = PartitionUtil.ofSize(list, 999)

more details: https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/

Call asynchronous method in constructor?

Try to replace this:

myLongList.ItemsSource = writings;

with this

Dispatcher.BeginInvoke(() => myLongList.ItemsSource = writings);

Regex for Comma delimited list

I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:

"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"

I think this is an elegant solution, with a trick that avoids a lot of regex complexity:

if (string.IsNullOrEmpty(encodedValues))
{
    return null;
}
else
{
    var retVal = new Dictionary<int, string>();
    var reFields = new Regex(@"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
    foreach (Match match in reFields.Matches(encodedValues + ","))
    {
        var id = match.Groups[1].Value;
        var value = match.Groups[2].Value;
        retVal[int.Parse(id)] = value.Replace(",,", ",");
    }
    return retVal;
}

I think it can be adapted to the original question with an expression like @"([0-9]+),\s?" and parse on Groups[0].

I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!

Nginx reverse proxy causing 504 Gateway Timeout

Had the same problem. Turned out it was caused by iptables connection tracking on the upstream server. After removing --state NEW,ESTABLISHED,RELATED from the firewall script and flushing with conntrack -F the problem was gone.

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Note to under

connetionString =@"server=XXX;Trusted_Connection=yes;database=yourDB;";

Note: XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...

you can replace 'server' with 'Data Source'

too you can replace 'database' with 'Initial Catalog'

Sample:

 connetionString =@"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";

Unable to compile class for JSP

<pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>       
                <version>2.2</version>
            </plugin>
        </plugins>

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

importing external ".txt" file in python

The "import" keyword is for attaching python definitions that are created external to the current python program. So in your case, where you just want to read a file with some text in it, use:

text = open("words.txt", "rb").read()

Why do multiple-table joins produce duplicate rows?

If one of the tables M, S, D, or H has more than one row for a given Id (if just the Id column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).

References:

Related Question on MSDN Forum

How can I write an anonymous function in Java?

Here's an example of an anonymous inner class.

System.out.println(new Object() {
    @Override public String toString() {
        return "Hello world!";
    }
}); // prints "Hello world!"

This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object and @Override its toString() method.

See also


Anonymous inner classes are very handy when you need to implement an interface which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator<T> for sorting.

Here's an example of how you can sort a String[] based on String.length().

import java.util.*;
//...

String[] arr = { "xxx", "cd", "ab", "z" };
Arrays.sort(arr, new Comparator<String>() {
    @Override public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }           
});
System.out.println(Arrays.toString(arr));
// prints "[z, cd, ab, xxx]"

Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String lengths).

See also

.NET NewtonSoft JSON deserialize map to a different property name

Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".

    /// <summary>
    /// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not 
    /// let the JsonProperty control everything.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
    {
        private Dictionary<string, string> PropertyMappings { get; set; }

        public IgnoreJsonPropertyResolver()
        {
            this.PropertyMappings = new Dictionary<string, string>();
            var properties = ReflectionHelper<T>.GetGetProperties(false)();
            foreach (var propertyInfo in properties)
            {
                var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
                if (jsonProperty != null)
                {
                    PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
                }
            }
        }

        protected override string ResolvePropertyName(string propertyName)
        {
            string resolvedName = null;
            var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
            return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
        }
    }

Usage:

        var settings = new JsonSerializerSettings();
        settings.DateFormatString = "YYYY-MM-DD";
        settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
        var model = new PlanViewModel() {Amount = 100};
        var strModel = JsonConvert.SerializeObject(model,settings);

Model:

public class PlanViewModel
{

    /// <summary>
    ///     The customer is charged an amount over an interval for the subscription.
    /// </summary>
    [JsonProperty(PropertyName = "RecurringPrice")]
    public double Amount { get; set; }

    /// <summary>
    ///     Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
    ///     months or years depending on the value for interval_unit.
    /// </summary>
    public int Interval { get; set; } = 1;

    /// <summary>
    ///     Number of free trial days that can be granted when a customer is subscribed to this plan.
    /// </summary>
    public int TrialPeriod { get; set; } = 30;

    /// <summary>
    /// This indicates a one-time fee charged upfront while creating a subscription for this plan.
    /// </summary>
    [JsonProperty(PropertyName = "SetupFee")]
    public double SetupAmount { get; set; } = 0;


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "TypeId")]
    public string Type { get; set; }

    /// <summary>
    /// Billing Frequency
    /// </summary>
    [JsonProperty(PropertyName = "BillingFrequency")]
    public string Period { get; set; }


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "PlanUseType")]
    public string Purpose { get; set; }
}

CSS display:table-row does not expand when width is set to 100%

If you're using display:table-row etc., then you need proper markup, which includes a containing table. Without it your original question basically provides the equivalent bad markup of:

<tr style="width:100%">
    <td>Type</td>
    <td style="float:right">Name</td>
</tr>

Where's the table in the above? You can't just have a row out of nowhere (tr must be contained in either table, thead, tbody, etc.)

Instead, add an outer element with display:table, put the 100% width on the containing element. The two inside cells will automatically go 50/50 and align the text right on the second cell. Forget floats with table elements. It'll cause so many headaches.

markup:

<div class="view-table">
    <div class="view-row">
        <div class="view-type">Type</div>
        <div class="view-name">Name</div>                
    </div>
</div>

CSS:

.view-table
{
    display:table;
    width:100%;
}
.view-row,
{
    display:table-row;
}
.view-row > div
{
    display: table-cell;
}
.view-name 
{
    text-align:right;
}

How to checkout a specific Subversion revision from the command line?

Any reason for using TortoiseProc instead of just the normal svn command line?

I'd use:

svn checkout svn://somepath@1234 working-directory

(to get revision 1234)

Convert a Unicode string to a string in Python (containing extra symbols)

If you have a Unicode string, and you want to write this to a file, or other serialised form, you must first encode it into a particular representation that can be stored. There are several common Unicode encodings, such as UTF-16 (uses two bytes for most Unicode characters) or UTF-8 (1-4 bytes / codepoint depending on the character), etc. To convert that string into a particular encoding, you can use:

>>> s= u'£10'
>>> s.encode('utf8')
'\xc2\x9c10'
>>> s.encode('utf16')
'\xff\xfe\x9c\x001\x000\x00'

This raw string of bytes can be written to a file. However, note that when reading it back, you must know what encoding it is in and decode it using that same encoding.

When writing to files, you can get rid of this manual encode/decode process by using the codecs module. So, to open a file that encodes all Unicode strings into UTF-8, use:

import codecs
f = codecs.open('path/to/file.txt','w','utf8')
f.write(my_unicode_string)  # Stored on disk as UTF-8

Do note that anything else that is using these files must understand what encoding the file is in if they want to read them. If you are the only one doing the reading/writing this isn't a problem, otherwise make sure that you write in a form understandable by whatever else uses the files.

In Python 3, this form of file access is the default, and the built-in open function will take an encoding parameter and always translate to/from Unicode strings (the default string object in Python 3) for files opened in text mode.

Remove a character at a certain position in a string - javascript

Hi starbeamrainbowlabs ,

You can do this with the following:

var oldValue = "pic quality, hello" ;
var newValue =  "hello";
var oldValueLength = oldValue.length ;
var newValueLength = newValue.length ;
var from = oldValue.search(newValue) ;
var to = from + newValueLength ;
var nes = oldValue.substr(0,from) + oldValue.substr(to,oldValueLength);
console.log(nes);

I tested this in my javascript console so you can also check this out Thanks

How to find largest objects in a SQL Server database?

You may also use the following code:

USE AdventureWork
GO
CREATE TABLE #GetLargest 
(
  table_name    sysname ,
  row_count     INT,
  reserved_size VARCHAR(50),
  data_size     VARCHAR(50),
  index_size    VARCHAR(50),
  unused_size   VARCHAR(50)
)

SET NOCOUNT ON

INSERT #GetLargest

EXEC sp_msforeachtable 'sp_spaceused ''?'''

SELECT 
  a.table_name,
  a.row_count,
  COUNT(*) AS col_count,
  a.data_size
  FROM #GetLargest a
     INNER JOIN information_schema.columns b
     ON a.table_name collate database_default
     = b.table_name collate database_default
       GROUP BY a.table_name, a.row_count, a.data_size
       ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESC

DROP TABLE #GetLargest

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What does __FILE__ mean in Ruby?

__FILE__ is the filename with extension of the file containing the code being executed.

In foo.rb, __FILE__ would be "foo.rb".

If foo.rb were in the dir /home/josh then File.dirname(__FILE__) would return /home/josh.

getting the table row values with jquery

$(document).ready(function () {
        $("#tbl_Customer tbody tr .companyname").click(function () {

            var comapnyname = $(this).closest(".trclass").find(".companyname").text();
            var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
            var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
            var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
            var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
           // var clickedCell = $(this);
            alert(comapnyname);
            alert(CompanyAddress);
            alert(CompanyEmail);
            alert(CompanyContactNumber);
            alert(CompanyContactPerson);

            //alert(clickedCell.text());
        });
    });

Find by key deep in a nested array

If you're already using Underscore, use _.find()

_.find(yourList, function (item) {
    return item.id === 1;
});

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

Inline styling would work in any case

  <p-column field="Quantity" header="Qté" [style]="{'width':'48px'}">