Programs & Examples On #Writer

an abstract class, interface or naming convention which is used to state that the given object is used to write data to a file, stream, device or other destination

append new row to old csv file python

I prefer this solution using the csv module from the standard library and the with statement to avoid leaving the file open.

The key point is using 'a' for appending when you open the file.

import csv   
fields=['first','second','third']
with open(r'name', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(fields)

If you are using Python 2.7 you may experience superfluous new lines in Windows. You can try to avoid them using 'ab' instead of 'a' this will, however, cause you TypeError: a bytes-like object is required, not 'str' in python and CSV in Python 3.6. Adding the newline='', as Natacha suggests, will cause you a backward incompatibility between Python 2 and 3.

Java Compare Two Lists

I found a very basic example of List comparison at List Compare This example verifies the size first and then checks the availability of the particular element of one list in another.

HTTP authentication logout via PHP

There's a lot of great - complex - answers here. In my particular case i found a clean and simple fix for the logout. I have yet to test in Edge. On my page that I have logged in to, I have placed a logout link similar to this:

<a href="https://MyDomainHere.net/logout.html">logout</a>

And in the head of that logout.html page (which is also protected by the .htaccess) I have a page refresh similar to this:

<meta http-equiv="Refresh" content="0; url=https://logout:[email protected]/" />

Where you would leave the words "logout" in place to clear the username and password cached for the site.

I will admit that if multiple pages needed to be able to be directly logged in to from the beginning, each of those points of entry would need their own corresponding logout.html page. Otherwise you could centralize the logout by introducing an additional gatekeeper step into the process before the actual login prompt, requiring entry of a phrase to reach a destination of login.

Mysql database sync between two databases

SymmetricDS is the answer. It supports multiple subscribers with one direction or bi-directional asynchronous data replication. It uses web and database technologies to replicate tables between relational databases, in near real time if desired.

Comprehensive and robust Java API to suit your needs.

Conversion from Long to Double in Java

I think it is good for you.

BigDecimal.valueOf([LONG_VALUE]).doubleValue()

How about this code? :D

What does the construct x = x || y mean?

Basically it checks if the value before the || evaluates to true, if yes, it takes this value, if not, it takes the value after the ||.

Values for which it will take the value after the || (as far as i remember):

  • undefined
  • false
  • 0
  • '' (Null or Null string)

Pass variables from servlet to jsp

It will fail to work when:

  1. You are redirecting the response to a new request by response.sendRedirect("page.jsp"). The newly created request object will of course not contain the attributes anymore and they will not be accessible in the redirected JSP. You need to forward rather than redirect. E.g.

    request.setAttribute("name", "value");
    request.getRequestDispatcher("page.jsp").forward(request, response);
    
  2. You are accessing it the wrong way or using the wrong name. Assuming that you have set it using the name "name", then you should be able to access it in the forwarded JSP page as follows:

    ${name}
    

How to split a string, but also keep the delimiters?

Another candidate solution using a regex. Retains token order, correctly matches multiple tokens of the same type in a row. The downside is that the regex is kind of nasty.

package javaapplication2;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaApplication2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String num = "58.5+variable-+98*78/96+a/78.7-3443*12-3";

        // Terrifying regex:
        //  (a)|(b)|(c) match a or b or c
        // where
        //   (a) is one or more digits optionally followed by a decimal point
        //       followed by one or more digits: (\d+(\.\d+)?)
        //   (b) is one of the set + * / - occurring once: ([+*/-])
        //   (c) is a sequence of one or more lowercase latin letter: ([a-z]+)
        Pattern tokenPattern = Pattern.compile("(\\d+(\\.\\d+)?)|([+*/-])|([a-z]+)");
        Matcher tokenMatcher = tokenPattern.matcher(num);

        List<String> tokens = new ArrayList<>();

        while (!tokenMatcher.hitEnd()) {
            if (tokenMatcher.find()) {
                tokens.add(tokenMatcher.group());
            } else {
                // report error
                break;
            }
        }

        System.out.println(tokens);
    }
}

Sample output:

[58.5, +, variable, -, +, 98, *, 78, /, 96, +, a, /, 78.7, -, 3443, *, 12, -, 3]

Accessing certain pixel RGB value in openCV

The low-level way would be to access the matrix data directly. In an RGB image (which I believe OpenCV typically stores as BGR), and assuming your cv::Mat variable is called frame, you could get the blue value at location (x, y) (from the top left) this way:

frame.data[frame.channels()*(frame.cols*y + x)];

Likewise, to get B, G, and R:

uchar b = frame.data[frame.channels()*(frame.cols*y + x) + 0];    
uchar g = frame.data[frame.channels()*(frame.cols*y + x) + 1];
uchar r = frame.data[frame.channels()*(frame.cols*y + x) + 2];

Note that this code assumes the stride is equal to the width of the image.

Input type "number" won't resize

Seem like the input type number does not support size attribute or it's not compatible along browsers, you can set it through CSS instead:

input[type=number]{
    width: 80px;
} 

Updated Fiddle

How can I apply a border only inside a table?

If you are doing what I believe you are trying to do, you'll need something a little more like this:

table {
  border-collapse: collapse;
}
table td, table th {
  border: 1px solid black;
}
table tr:first-child th {
  border-top: 0;
}
table tr:last-child td {
  border-bottom: 0;
}
table tr td:first-child,
table tr th:first-child {
  border-left: 0;
}
table tr td:last-child,
table tr th:last-child {
  border-right: 0;
}

jsFiddle Demo

The problem is that you are setting a 'full border' around all the cells, which make it appear as if you have a border around the entire table.

Cheers.

EDIT: A little more info on those pseudo-classes can be found on quirksmode, and, as to be expected, you are pretty much S.O.L. in terms of IE support.

HTML Agility pack - parsing tables

I know this is a pretty old question but this was my solution that helped with visualizing the table so you can create a class structure. This is also using the HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
var table = doc.DocumentNode.SelectSingleNode("//table");
var tableRows = table.SelectNodes("tr");
var columns = tableRows[0].SelectNodes("th/text()");
for (int i = 1; i < tableRows.Count; i++)
{
    for (int e = 0; e < columns.Count; e++)
    {
        var value = tableRows[i].SelectSingleNode($"td[{e + 1}]");
        Console.Write(columns[e].InnerText + ":" + value.InnerText);
    }
Console.WriteLine();
}

How to make link not change color after visited?

If you want to set to a new color or prevent the change of the color of a specific link after visiting it, add inside the tag of that link:

<a style="text-decoration:none; color:#ff0000;" href="link.html">test link</a>

Above the color is #ff0000 but you can make it anything you'd like.

Java Scanner class reading strings

use sc.nextLine(); two time so that we can read the last line of string

sc.nextLine() sc.nextLine()

How do I get a YouTube video thumbnail from the YouTube API?

What Asaph said is right. However, not every YouTube video contains all nine thumbnails. Also, the thumbnails' image sizes depends on the video (the numbers below are based on one). There are some thumbnails guaranteed to exist:

Width | Height | URL
------|--------|----
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/1.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/2.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/3.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/default.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq1.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq2.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq3.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mqdefault.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/0.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq1.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq2.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq3.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hqdefault.jpg

Additionally, the some other thumbnails may or may not exist. Their presence is probably based on whether the video is high-quality.

Width | Height | URL
------|--------|----
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sd1.jpg
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sd2.jpg
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sd3.jpg
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sddefault.jpg
1280  | 720    | https://i.ytimg.com/vi/<VIDEO ID>/hq720.jpg
1920  | 1080   | https://i.ytimg.com/vi/<VIDEO ID>/maxresdefault.jpg

You can find JavaScript and PHP scripts to retrieve thumbnails and other YouTube information in:

You can also use the YouTube Video Information Generator tool to get all the information about a YouTube video by submitting a URL or video id.

jquery fill dropdown with json data

Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/ URL. Upon success, it removes all items from dropdown list with id = OfferTransModel_ItemID and then it fills it with new items based on AJAX call's result:

if (productgrpid != 0) {    
    $.ajax({
        type: "POST",
        url: "/Ajax/_AjaxGetItemListHelp/",
        data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
        contentType: "application/json",              
        dataType: "json",
        success: function (data) {
            $("#OfferTransModel_ItemID").empty();

            $.each(data, function () {
                $("#OfferTransModel_ItemID").append($("<option>                                                      
                </option>").val(this['ITEMID']).html(this['ITEMDESC']));
            });
        }
    });
}

Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID and ITEMDESC elements. For example:

{
    {
        "ITEMID":"13",
        "ITEMDESC":"About"
    },
    {
        "ITEMID":"21",
        "ITEMDESC":"Contact"
    }
}

The OfferTransModel_ItemID listbox is populated with above data and its code should look like:

<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
    <option value="13">About</option>
    <option value="21">Contact</option>
</select>

When user selects About, form submits 13 as value for this field and 21 when user selects Contact and so on.

Fell free to modify above code if your server returns URL in a different format.

Purpose of returning by const value?

It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:

myFunc() = Object(...);

That would work nicely if myFunc returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.

RecyclerView - Get view at particular position

You can use below

mRecyclerview.getChildAt(pos);

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

In ONLINE mode the new index is built while the old index is accessible to reads and writes. any update on the old index will also get applied to the new index. An antimatter column is used to track possible conflicts between the updates and the rebuild (ie. delete of a row which was not yet copied). See Online Index Operations. When the process is completed the table is locked for a brief period and the new index replaces the old index. If the index contains LOB columns, ONLINE operations are not supported in SQL Server 2005/2008/R2.

In OFFLINE mode the table is locked upfront for any read or write, and then the new index gets built from the old index, while holding a lock on the table. No read or write operation is permitted on the table while the index is being rebuilt. Only when the operation is done is the lock on the table released and reads and writes are allowed again.

Note that in SQL Server 2012 the restriction on LOBs was lifted, see Online Index Operations for indexes containing LOB columns.

Any way to make plot points in scatterplot more transparent in R?

When creating the colors, you may use rgb and set its alpha argument:

plot(1:10, col = rgb(red = 1, green = 0, blue = 0, alpha = 0.5),
     pch = 16, cex = 4)
points((1:10) + 0.4, col = rgb(red = 0, green = 0, blue = 1, alpha = 0.5),
       pch = 16, cex = 4)

enter image description here

Please see ?rgb for details.

Make multiple-select to adjust its height to fit options without scroll bar

I had this requirement recently and used other posts from this question to create this script:

$("select[multiple]").each(function() {
  $(this).css("height","100%")
    .attr("size",this.length);
})

System.web.mvc missing

Add the reference again from ./packages/Microsoft.AspNet.Mvc.[version]/lib/net45/System.Web.Mvc.dll

Is there such a thing as min-font-size and max-font-size?

You can do it by using a formula and including the viewport width.

font-size: calc(7px + .5vw);

This sets the minimum font size at 7px and amplifies it by .5vw depending on the viewport width.

Good luck!

How to parse XML using vba

Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,"")
Cell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,"")

And the result line E1 will have your parsed value:

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: 24.365<X><Y>78.68</Y></PointN>
Cell E1: 24.365

Can you call Directory.GetFiles() with multiple filters?

There is also a descent solution which seems not to have any memory or performance overhead and be quite elegant:

string[] filters = new[]{"*.jpg", "*.png", "*.gif"};
string[] filePaths = filters.SelectMany(f => Directory.GetFiles(basePath, f)).ToArray();

Difference between size and length methods?

size() is a method specified in java.util.Collection, which is then inherited by every data structure in the standard library. length is a field on any array (arrays are objects, you just don't see the class normally), and length() is a method on java.lang.String, which is just a thin wrapper on a char[] anyway.

Perhaps by design, Strings are immutable, and all of the top-level Collection subclasses are mutable. So where you see "length" you know that's constant, and where you see "size" it isn't.

Is there a "goto" statement in bash?

No, there is not; see §3.2.4 "Compound Commands" in the Bash Reference Manual for information about the control structures that do exist. In particular, note the mention of break and continue, which aren't as flexible as goto, but are more flexible in Bash than in some languages, and may help you achieve what you want. (Whatever it is that you want . . .)

Confirm Password with jQuery Validate

It works if id value and name value are different:

<input type="password" class="form-control"name="password" id="mainpassword">
password: {     required: true,     } , 
cpassword: {required: true, equalTo: '#mainpassword' },

Setting default values for columns in JPA

Neither JPA nor Hibernate annotations support the notion of a default column value. As a workaround to this limitation, set all default values just before you invoke a Hibernate save() or update() on the session. This closely as possible (short of Hibernate setting the default values) mimics the behaviour of the database which sets default values when it saves a row in a table.

Unlike setting the default values in the model class as this alternative answer suggests, this approach also ensures that criteria queries that use an Example object as a prototype for the search will continue to work as before. When you set the default value of a nullable attribute (one that has a non-primitive type) in a model class, a Hibernate query-by-example will no longer ignore the associated column where previously it would ignore it because it was null.

Child element click event trigger the parent click event

You need to use event.stopPropagation()

Live Demo

$('#childDiv').click(function(event){
    event.stopPropagation();
    alert(event.target.id);
});?

event.stopPropagation()

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

NOW() function in PHP

Not besides the date function:

date("Y-m-d H:i:s");

What is the LD_PRELOAD trick?

You can override symbols in the stock libraries by creating a library with the same symbols and specifying the library in LD_PRELOAD.

Some people use it to specify libraries in nonstandard locations, but LD_LIBRARY_PATH is better for that purpose.

C# with MySQL INSERT parameters

comm.Parameters.Add("person", "Myname");

Getting command-line password input in Python

Here is my code based off the code offered by @Ahmed ALaa

Features:

  • Works for passwords up to 64 characters
  • Accepts backspace input
  • Outputs * character (DEC: 42 ; HEX: 0x2A) instead of the input character

Demerits:

  • Works on Windows only

The function secure_password_input() returns the password as a string when called. It accepts a Password Prompt string, which will be displayed to the user to type the password

def secure_password_input(prompt=''):
    p_s = ''
    proxy_string = [' '] * 64
    while True:
        sys.stdout.write('\x0D' + prompt + ''.join(proxy_string))
        c = msvcrt.getch()
        if c == b'\r':
            break
        elif c == b'\x08':
            p_s = p_s[:-1]
            proxy_string[len(p_s)] = " "
        else:
            proxy_string[len(p_s)] = "*"
            p_s += c.decode()

    sys.stdout.write('\n')
    return p_s

How to check if activity is in foreground or in visible background?

Use the time gap between pause and resume from background to determine whether it is awake from background

In Custom Application

private static boolean isInBackground;
private static boolean isAwakeFromBackground;
private static final int backgroundAllowance = 10000;

public static void activityPaused() {
    isInBackground = true;
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (isInBackground) {
                isAwakeFromBackground = true;
            }
        }
    }, backgroundAllowance);
    Log.v("activity status", "activityPaused");
}

public static void activityResumed() {
    isInBackground = false;
    if(isAwakeFromBackground){
        // do something when awake from background
        Log.v("activity status", "isAwakeFromBackground");
    }
    isAwakeFromBackground = false;
    Log.v("activity status", "activityResumed");
}

In BaseActivity Class

@Override
protected void onResume() {
  super.onResume();
  MyApplication.activityResumed();
}

@Override
protected void onPause() {
  super.onPause();
  MyApplication.activityPaused();
}

Getting a File's MD5 Checksum in Java

Google guava provides a new API. Find the one below :

public static HashCode hash(File file,
            HashFunction hashFunction)
                     throws IOException

Computes the hash code of the file using hashFunction.

Parameters:
    file - the file to read
    hashFunction - the hash function to use to hash the data
Returns:
    the HashCode of all of the bytes in the file
Throws:
    IOException - if an I/O error occurs
Since:
    12.0

Changing specific text's color using NSMutableAttributedString in Swift

You can use this extension I test it over

swift 4.2

import Foundation
import UIKit

extension NSMutableAttributedString {

    convenience init (fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) {
           let rangeOfSubString = (fullString as NSString).range(of: subString)
           let rangeOfFullString = NSRange(location: 0, length: fullString.count)//fullString.range(of: fullString)
           let attributedString = NSMutableAttributedString(string:fullString)
           attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: fullStringColor, range: rangeOfFullString)
           attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: subStringColor, range: rangeOfSubString)

           self.init(attributedString: attributedString)
   }

}

PHP cURL HTTP PUT

You have mixed 2 standard.

The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";

The function http_build_query($filedata) is only for "Content-Type: application/x-www-form-urlencoded", or none.

Force an SVN checkout command to overwrite current files

Try the --force option. svn help checkout gives the details.

LaTeX source code listing like in professional books

For R code I use

\usepackage{listings}
\lstset{
language=R,
basicstyle=\scriptsize\ttfamily,
commentstyle=\ttfamily\color{gray},
numbers=left,
numberstyle=\ttfamily\color{gray}\footnotesize,
stepnumber=1,
numbersep=5pt,
backgroundcolor=\color{white},
showspaces=false,
showstringspaces=false,
showtabs=false,
frame=single,
tabsize=2,
captionpos=b,
breaklines=true,
breakatwhitespace=false,
title=\lstname,
escapeinside={},
keywordstyle={},
morekeywords={}
}

And it looks exactly like this

enter image description here

Access IP Camera in Python OpenCV

I answer my own question reporting what therefore seems to be the most comprehensive overall procedure to Access IP Camera in Python OpenCV.

Given an IP camera:

  • Find your camera IP address
  • Find the port where the IP address is accessed
  • Find the protocol (HTTP/RTSP etc.) specified by the camera provider

Then, if your camera is protected go ahead and find out:

  • your username
  • your password

Then use your data to run the following script:

"""Access IP Camera in Python OpenCV"""

import cv2

stream = cv2.VideoCapture('protocol://IP:port/1')

# Use the next line if your camera has a username and password
# stream = cv2.VideoCapture('protocol://username:password@IP:port/1')  

while True:

    r, f = stream.read()
    cv2.imshow('IP Camera stream',f)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

NOTE: In my original question I specify to being working with Teledyne Dalsa Genie Nano XL Camera. Unfortunately for this kind of cameras this normal way of accessing the IP Camera video stream does not work and the Sapera SDK must be employed in order to grab frames from the device.

Get a random item from a JavaScript array

// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})

// 2. Get first item
var item = items[0]

Shorter:

var item = items.sort(function() {return 0.5 - Math.random()})[0];

mysql update query with sub query

For the impatient:

UPDATE target AS t
INNER JOIN (
  SELECT s.id, COUNT(*) AS count
  FROM source_grouped AS s
  -- WHERE s.custom_condition IS (true)
  GROUP BY s.id
) AS aggregate ON aggregate.id = t.id
SET t.count = aggregate.count

That's @mellamokb's answer, as above, reduced to the max.

How to use .htaccess in WAMP Server?

Click on Wamp icon and open Apache/httpd.conf and search "#LoadModule rewrite_module modules/mod_rewrite.so". Remove # as below and save it

LoadModule rewrite_module modules/mod_rewrite.so

and restart all service.

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

How to throw std::exceptions with variable messages?

Maybe this?

throw std::runtime_error(
    (std::ostringstream()
        << "Could not load config file '"
        << configfile
        << "'"
    ).str()
);

It creates a temporary ostringstream, calls the << operators as necessary and then you wrap that in round brackets and call the .str() function on the evaluated result (which is an ostringstream) to pass a temporary std::string to the constructor of runtime_error.

Note: the ostringstream and the string are r-value temporaries and so go out of scope after this line ends. Your exception object's constructor MUST take the input string using either copy or (better) move semantics.

Additional: I don't necessarily consider this approach "best practice", but it does work and can be used at a pinch. One of the biggest issues is that this method requires heap allocations and so the operator << can throw. You probably don't want that happening; however, if your get into that state your probably have way more issues to worry about!

Convert Go map to json

Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal would work as expected.

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler 
type Num int

func (n *Num) UnmarshalText(text []byte) error {
    i, err := strconv.Atoi(string(text))
    if err != nil {
        return err
    }
    *n = Num(i)
    return nil
}

func (n Num) MarshalText() (text []byte, err error) {
    return []byte(strconv.Itoa(int(n))), nil
}

type Foo struct {
    Number Num    `json:"number"`
    Title  string `json:"title"`
}

func main() {
    datas := make(map[Num]Foo)

    for i := 0; i < 10; i++ {
        datas[Num(i)] = Foo{Number: 1, Title: "test"}
    }

    jsonString, err := json.Marshal(datas)
    if err != nil {
        panic(err)
    }

    fmt.Println(datas)
    fmt.Println(jsonString)

    m := make(map[Num]Foo)
    err = json.Unmarshal(jsonString, &m)
    if err != nil {
        panic(err)
    }

    fmt.Println(m)
}

Output:

map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]

Converting JSON data to Java object

Give boon a try:

https://github.com/RichardHightower/boon

It is wicked fast:

https://github.com/RichardHightower/json-parsers-benchmark

Don't take my word for it... check out the gatling benchmark.

https://github.com/gatling/json-parsers-benchmark

(Up to 4x is some cases, and out of the 100s of test. It also has a index overlay mode that is even faster. It is young but already has some users.)

It can parse JSON to Maps and Lists faster than any other lib can parse to a JSON DOM and that is without Index Overlay mode. With Boon Index Overlay mode, it is even faster.

It also has a very fast JSON lax mode and a PLIST parser mode. :) (and has a super low memory, direct from bytes mode with UTF-8 encoding on the fly).

It also has the fastest JSON to JavaBean mode too.

It is new, but if speed and simple API is what you are looking for, I don't think there is a faster or more minimalist API.

How to strip all non-alphabetic characters from string in SQL Server?

DECLARE @vchVAlue NVARCHAR(255) = 'SWP, Lettering Position 1: 4 ?, 2: 8 ?, 3: 16 ?, 4:  , 5:  , 6:  , Voltage Selector, Solder, 6, Step switch, : w/o fuseholder '


WHILE PATINDEX('%?%' , CAST(@vchVAlue AS VARCHAR(255))) > 0
  BEGIN
    SELECT @vchVAlue = STUFF(@vchVAlue,PATINDEX('%?%' , CAST(@vchVAlue AS VARCHAR(255))),1,' ')
  END 

SELECT @vchVAlue

How to insert strings containing slashes with sed?

add \ before special characters:

s/\?page=one&/page\/one\//g

etc.

How to create number input field in Flutter?

You can specify the number as keyboardType for the TextField using:

keyboardType: TextInputType.number

Check my main.dart file

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      home: new HomePage(),
      theme: new ThemeData(primarySwatch: Colors.blue),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.white,
      body: new Container(
          padding: const EdgeInsets.all(40.0),
          child: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new TextField(
            decoration: new InputDecoration(labelText: "Enter your number"),
            keyboardType: TextInputType.number,
            inputFormatters: <TextInputFormatter>[
    FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
          ),
        ],
      )),
    );
  }
}

enter image description here

How to delete an element from an array in C#

Removing from an array itself is not simple, as you then have to deal with resizing. This is one of the great advantages of using something like a List<int> instead. It provides Remove/RemoveAt in 2.0, and lots of LINQ extensions for 3.0.

If you can, refactor to use a List<> or similar.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Axios get in url works but with second parameter as object it doesn't

On client:

  axios.get('/api', {
      params: {
        foo: 'bar'
      }
    });

On server:

function get(req, res, next) {

  let param = req.query.foo
   .....
}

How to extract epoch from LocalDate and LocalDateTime?

Look at this method to see which fields are supported. You will find for LocalDateTime:

•NANO_OF_SECOND 
•NANO_OF_DAY 
•MICRO_OF_SECOND 
•MICRO_OF_DAY 
•MILLI_OF_SECOND 
•MILLI_OF_DAY 
•SECOND_OF_MINUTE 
•SECOND_OF_DAY 
•MINUTE_OF_HOUR 
•MINUTE_OF_DAY 
•HOUR_OF_AMPM 
•CLOCK_HOUR_OF_AMPM 
•HOUR_OF_DAY 
•CLOCK_HOUR_OF_DAY 
•AMPM_OF_DAY 
•DAY_OF_WEEK 
•ALIGNED_DAY_OF_WEEK_IN_MONTH 
•ALIGNED_DAY_OF_WEEK_IN_YEAR 
•DAY_OF_MONTH 
•DAY_OF_YEAR 
•EPOCH_DAY 
•ALIGNED_WEEK_OF_MONTH 
•ALIGNED_WEEK_OF_YEAR 
•MONTH_OF_YEAR 
•PROLEPTIC_MONTH 
•YEAR_OF_ERA 
•YEAR 
•ERA 

The field INSTANT_SECONDS is - of course - not supported because a LocalDateTime cannot refer to any absolute (global) timestamp. But what is helpful is the field EPOCH_DAY which counts the elapsed days since 1970-01-01. Similar thoughts are valid for the type LocalDate (with even less supported fields).

If you intend to get the non-existing millis-since-unix-epoch field you also need the timezone for converting from a local to a global type. This conversion can be done much simpler, see other SO-posts.

Coming back to your question and the numbers in your code:

The result 1605 is correct
  => (2014 - 1970) * 365 + 11 (leap days) + 31 (in january 2014) + 3 (in february 2014)
The result 71461 is also correct => 19 * 3600 + 51 * 60 + 1

16105L * 86400 + 71461 = 1391543461 seconds since 1970-01-01T00:00:00 (attention, no timezone) Then you can subtract the timezone offset (watch out for possible multiplication by 1000 if in milliseconds).

UPDATE after given timezone info:

local time = 1391543461 secs
offset = 3600 secs (Europe/Oslo, winter time in february)
utc = 1391543461 - 3600 = 1391539861

As JSR-310-code with two equivalent approaches:

long secondsSinceUnixEpoch1 =
  LocalDateTime.of(2014, 2, 4, 19, 51, 1).atZone(ZoneId.of("Europe/Oslo")).toEpochSecond();

long secondsSinceUnixEpoch2 =
  LocalDate
    .of(2014, 2, 4)
    .atTime(19, 51, 1)
    .atZone(ZoneId.of("Europe/Oslo"))
    .toEpochSecond();

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Load external css file like scripts in jquery which is compatible in ie also

Based on your comment under @Raul's answer, I can think of two ways to include a callback:

  1. Have getScript call the file that loads the css.
  2. Load the contents of the css file with AJAX, and append to <style>. Your callback would be the callback from $.get or whatever you use to load the css file contents.

How can I select rows by range?

You can use rownum :

SELECT * FROM table WHERE rownum > 10 and rownum <= 20

Batch / Find And Edit Lines in TXT file

This is the kind of stuff sed was made for (of course, you need sed on your system for that).

sed 's/ex3/ex5/g' input.txt > output.txt

You will either need a Unix system or a Windows Cygwin kind of platform for this.
There is also GnuWin32 for sed. (GnuWin32 installation and usage).

Checking if a variable is an integer in PHP

An integer starting with 0 will cause fatal error as of PHP 7, because it might interpret it as an octal character.

Invalid octal literals

Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.

So you might want to remove leading zeros from your integer, first:

$var = ltrim($var, 0);

Vim multiline editing like in sublimetext?

There are several ways to accomplish that in Vim. I don't know which are most similar to Sublime Text's though.


The first one would be via multiline insert mode. Put your cursor to the second "a" in the first line, press Ctrl-V, select all lines, then press I, and put in a doublequote. Pressing <esc> will repeat the operation on every line.


The second one is via macros. Put the cursor on the first character, and start recording a macro with qa. Go the your right with llll, enter insert mode with a, put down a doublequote, exit insert mode, and go back to the beginning of your row with <home> (or equivalent). Press j to move down one row. Stop recording with q. And then replay the macro with @a. Several times.


Does any of the above approaches work for you?

Get the first element of an array

PHP 5.4+:

array_values($array)[0];

Lightbox to show videos from Youtube and Vimeo?

I've had a LOT of trouble with pretty photo and IE9. I also had issues with fancybox in IE.

For youtube.com, I'm having a lot of luck with CeeBox.

http://catcubed.com/2008/12/23/ceebox-a-thickboxvideobox-mashup/

Calling variable defined inside one function from another function

Everything in python is considered as object so functions are also objects. So you can use this method as well.

def fun1():
    fun1.var = 100
    print(fun1.var)

def fun2():
    print(fun1.var)

fun1()
fun2()

print(fun1.var)

How does MySQL process ORDER BY and LIMIT in a query?

LIMIT is usually applied as the last operation, so the result will first be sorted and then limited to 20. In fact, sorting will stop as soon as first 20 sorted results are found.

What is the default access specifier in Java?

the default access specifier is package.Classes can access the members of other classes in the same package.but outside the package it appears as private

How to get the caller's method name in the called method?

I've come up with a slightly longer version that tries to build a full method name including module and class.

https://gist.github.com/2151727 (rev 9cccbf)

# Public Domain, i.e. feel free to copy/paste
# Considered a hack in Python 2

import inspect

def caller_name(skip=2):
    """Get a name of a caller in the format module.class.method

       `skip` specifies how many levels of stack to skip while getting caller
       name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.

       An empty string is returned if skipped levels exceed stack height
    """
    stack = inspect.stack()
    start = 0 + skip
    if len(stack) < start + 1:
      return ''
    parentframe = stack[start][0]    

    name = []
    module = inspect.getmodule(parentframe)
    # `modname` can be None when frame is executed directly in console
    # TODO(techtonik): consider using __main__
    if module:
        name.append(module.__name__)
    # detect classname
    if 'self' in parentframe.f_locals:
        # I don't know any way to detect call from the object method
        # XXX: there seems to be no way to detect static method call - it will
        #      be just a function call
        name.append(parentframe.f_locals['self'].__class__.__name__)
    codename = parentframe.f_code.co_name
    if codename != '<module>':  # top level usually
        name.append( codename ) # function or a method

    ## Avoid circular refs and frame leaks
    #  https://docs.python.org/2.7/library/inspect.html#the-interpreter-stack
    del parentframe, stack

    return ".".join(name)

maven error: package org.junit does not exist

I fixed this error by inserting these lines of code:

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

into <dependencies> node.

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

Checking if a variable is an integer

If you want to know whether an object is an Integer or something which can meaningfully be converted to an Integer (NOT including things like "hello", which to_i will convert to 0):

result = Integer(obj) rescue false

Test if a property is available on a dynamic variable

In my case, I needed to check for the existence of a method with a specific name, so I used an interface for that

var plugin = this.pluginFinder.GetPluginIfInstalled<IPlugin>(pluginName) as dynamic;
if (plugin != null && plugin is ICustomPluginAction)
{
    plugin.CustomPluginAction(action);
}

Also, interfaces can contain more than just methods:

Interfaces can contain methods, properties, events, indexers, or any combination of those four member types.

From: Interfaces (C# Programming Guide)

Elegant and no need to trap exceptions or play with reflexion...

HtmlEncode from Class Library

Add a reference to System.Web.dll and then you can use the System.Web.HtmlUtility class

How to remove ASP.Net MVC Default HTTP Headers?

Check this blog Don't use code to remove headers. It is unstable according Microsoft

My take on this:

<system.webServer>          
    <httpProtocol>
    <!-- Security Hardening of HTTP response headers -->
    <customHeaders>
        <!--Sending the new X-Content-Type-Options response header with the value 'nosniff' will prevent 
                Internet Explorer from MIME-sniffing a response away from the declared content-type. -->
        <add name="X-Content-Type-Options" value="nosniff" />

        <!-- X-Frame-Options tells the browser whether you want to allow your site to be framed or not. 
                 By preventing a browser from framing your site you can defend against attacks like clickjacking. 
                 Recommended value "x-frame-options: SAMEORIGIN" -->
        <add name="X-Frame-Options" value="SAMEORIGIN" />

        <!-- Setting X-Permitted-Cross-Domain-Policies header to “master-only” will instruct Flash and PDF files that 
                 they should only read the master crossdomain.xml file from the root of the website. 
                 https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
        <add name="X-Permitted-Cross-Domain-Policies" value="master-only" />

        <!-- X-XSS-Protection sets the configuration for the cross-site scripting filter built into most browsers. 
                 Recommended value "X-XSS-Protection: 1; mode=block". -->
        <add name="X-Xss-Protection" value="1; mode=block" />

        <!-- Referrer-Policy allows a site to control how much information the browser includes with navigations away from a document and should be set by all sites. 
                 If you have sensitive information in your URLs, you don't want to forward to other domains 
                 https://scotthelme.co.uk/a-new-security-header-referrer-policy/ -->
        <add name="Referrer-Policy" value="no-referrer-when-downgrade" />

        <!-- Remove x-powered-by in the response header, required by OWASP A5:2017 - Do not disclose web server configuration -->
        <remove name="X-Powered-By" />

        <!-- Ensure the cache-control is public, some browser won't set expiration without that  -->
        <add name="Cache-Control" value="public" />
    </customHeaders>
</httpProtocol>

<!-- Prerequisite for the <rewrite> section
            Install the URL Rewrite Module on the Web Server https://www.iis.net/downloads/microsoft/url-rewrite -->
<rewrite>
    <!-- Remove Server response headers (OWASP Security Measure) -->
    <outboundRules rewriteBeforeCache="true">
        <rule name="Remove Server header">
            <match serverVariable="RESPONSE_Server" pattern=".+" />

            <!-- Use custom value for the Server info -->
            <action type="Rewrite" value="Your Custom Value Here." />
        </rule>
    </outboundRules>
</rewrite>
</system.webServer>

How to set commands output as a variable in a batch file

FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var=%%F
)
ECHO %var%

I always use the USEBACKQ so that if you have a string to insert or a long file name, you can use your double quotes without screwing up the command.

Now if your output will contain multiple lines, you can do this

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ENDLOCAL

How do you beta test an iphone app?

Using testflight :

1) create the ipa file by development certificate

2) upload the ipa file on testflight

3) Now, to identify the device to be tested on , add the device id on apple account and refresh your development certificate. Download the updated certificate and upload it on testflight website. Check the device id you are getting.

4) Now email the ipa file to the testers.

5) While downloading the ipa file, if the testers are not getting any warnings, this means the device token + provisioning profile has been verified. So, the testers can now download the ipa file on device and do the testing job...

Server configuration is missing in Eclipse

Probably, you have some problems with your server's configuration. Follow these steps to remove and create a new one, it might help you.

In Eclipse
1. Window -> Show view -> Servers (If you cannot see it, you might need to choose Others -> Server)
2. From Server view -> Delete the server which has problems.
3. Right click -> New -> Server : to create a new one

In my case, after new server was created, I get rid of this "localhost-config is missing"

Why doesn't margin:auto center an image?

You need to render it as block level;

img {
   display: block;
   width: auto;
   margin: auto;
}

Targeting .NET Framework 4.5 via Visual Studio 2010

From another search. Worked for me!

"You can use Visual Studio 2010 and it does support it, provided your OS supports .NET 4.5.

Right click on your solution to add a reference (as you do). When the dialog box shows, select browse, then navigate to the following folder:

C:\Program Files(x86)\Reference Assemblies\Microsoft\Framework\.Net Framework\4.5

You will find it there."

Marker content (infoWindow) Google Maps

Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:

Each marker gets an "infowindow" entry :

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}

Python, how to check if a result set is empty?

I had a similar problem when I needed to make multiple sql queries. The problem was that some queries did not return the result and I wanted to print that result. And there was a mistake. As already written, there are several solutions.

if cursor.description is None:
    # No recordset for INSERT, UPDATE, CREATE, etc
    pass
else:
    # Recordset for SELECT

As well as:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists

One of the solutions is:

The try and except block lets you handle the error/exceptions. The finally block lets you execute code, regardless of the result of the try and except blocks. So the presented problem can be solved by using it.

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))

output:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************

The example above only presents a simple use as an idea that could help with your solution. Of course, you should also pay attention to other errors, such as the correctness of the query, etc.

Log4net rolling daily filename with date in the file name

Using Log4Net 1.2.13 we use the following configuration settings to allow date time in the file name.

<file type="log4net.Util.PatternString" value="E:/logname-%utcdate{yyyy-MM-dd}.txt" />

Which will provide files in the following convention: logname-2015-04-17.txt

With this it's usually best to have the following to ensure you're holding 1 log per day.

<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />

If size of file is a concern the following allows 500 files of 5MB in size until a new day spawns. CountDirection allows Ascending or Descending numbering of files which are no longer current.

 <maxSizeRollBackups value="500" />
 <maximumFileSize value="5MB" />
 <rollingStyle value="Composite" />
 <datePattern value="yyyyMMdd" />
 <CountDirection value="1"/>
 <staticLogFileName value="true" />

Is there a bash command which counts files?

Lots of answers here, but some don't take into account

  • file names with spaces, newlines, or control characters in them
  • file names that start with hyphens (imagine a file called -l)
  • hidden files, that start with a dot (if the glob was *.log instead of log*
  • directories that match the glob (e.g. a directory called logs that matches log*)
  • empty directories (i.e. the result is 0)
  • extremely large directories (listing them all could exhaust memory)

Here's a solution that handles all of them:

ls 2>/dev/null -Ubad1 -- log* | wc -l

Explanation:

  • -U causes ls to not sort the entries, meaning it doesn't need to load the entire directory listing in memory
  • -b prints C-style escapes for nongraphic characters, crucially causing newlines to be printed as \n.
  • -a prints out all files, even hidden files (not strictly needed when the glob log* implies no hidden files)
  • -d prints out directories without attempting to list the contents of the directory, which is what ls normally would do
  • -1 makes sure that it's on one column (ls does this automatically when writing to a pipe, so it's not strictly necessary)
  • 2>/dev/null redirects stderr so that if there are 0 log files, ignore the error message. (Note that shopt -s nullglob would cause ls to list the entire working directory instead.)
  • wc -l consumes the directory listing as it's being generated, so the output of ls is never in memory at any point in time.
  • -- File names are separated from the command using -- so as not to be understood as arguments to ls (in case log* is removed)

The shell will expand log* to the full list of files, which may exhaust memory if it's a lot of files, so then running it through grep is be better:

ls -Uba1 | grep ^log | wc -l

This last one handles extremely large directories of files without using a lot of memory (albeit it does use a subshell). The -d is no longer necessary, because it's only listing the contents of the current directory.

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

How to get a vCard (.vcf file) into Android contacts from website

I'm running 2.2 and there is no change, reports from others on 2.3 say the same. Android (bug) does not handle a .vcf nor a link to such a file on a web page via port 80, neither via http headers or direct streaming. It just is NOT SUPPORTED AT ALL.

Use "ENTER" key on softkeyboard instead of clicking button

Most updated way to achieve this is:

Add this to your EditText in XML:

android:imeOptions="actionSearch"

Then in your Activity/Fragment:

EditText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
        // Do what you want here
        return@setOnEditorActionListener true
    }
    return@setOnEditorActionListener false
}

What is the HTML tabindex attribute?

Tabbing through controls usually happens sequentially as they appear on the HTML code.

Using tabindex, the tabbing will flow from control with the lowest tabindex to the control with the highest tabindex in tabindex sequential order

What is the C# equivalent of friend?

There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!

Example: To be placed in AssemblyInfo.cs

[assembly: InternalsVisibleTo("OtherAssembly")]

How to style a clicked button in CSS

Unfortunately, there is no :click pseudo selector. If you want to change styling on click, you should use Jquery/Javascript. It certainly is better than the "hack" for pure HTML / CSS. But if you insist...

_x000D_
_x000D_
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
  background: #444;_x000D_
  color: #fff;_x000D_
}
_x000D_
  <label for="input">_x000D_
  <input id="input" type="radio" />_x000D_
  <span>NO JS styling</span>_x000D_
  </label>
_x000D_
_x000D_
_x000D_

Or, if you prefer, you can toggle the styling:

_x000D_
_x000D_
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
  background: #444;_x000D_
  color: #fff;_x000D_
}
_x000D_
  <label for="input">_x000D_
  <input id="input" type="checkbox" />_x000D_
  <span>NO JS styling</span>_x000D_
  </label>
_x000D_
_x000D_
_x000D_

how to find all indexes and their columns for tables, views and synonyms in oracle

Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?

Paste multiple columns together

I benchmarked the answers of Anthony Damico, Brian Diggs and data_steve on a small sample tbl_df and got the following results.

> data <- data.frame('a' = 1:3, 
+                    'b' = c('a','b','c'), 
+                    'c' = c('d', 'e', 'f'), 
+                    'd' = c('g', 'h', 'i'))
> data <- tbl_df(data)
> cols <- c("b", "c", "d")
> microbenchmark(
+     do.call(paste, c(data[cols], sep="-")),
+     apply( data[ , cols ] , 1 , paste , collapse = "-" ),
+     tidyr::unite_(data, "x", cols, sep="-")$x,
+     times=1000
+ )
Unit: microseconds
                                         expr     min      lq      mean  median       uq       max neval
do.call(paste, c(data[cols], sep = "-"))       65.248  78.380  93.90888  86.177  99.3090   436.220  1000
apply(data[, cols], 1, paste, collapse = "-") 223.239 263.044 313.11977 289.514 338.5520   743.583  1000
tidyr::unite_(data, "x", cols, sep = "-")$x   376.716 448.120 556.65424 501.877 606.9315 11537.846  1000

However, when I evaluated on my own tbl_df with ~1 million rows and 10 columns the results were quite different.

> microbenchmark(
+     do.call(paste, c(data[c("a", "b")], sep="-")),
+     apply( data[ , c("a", "b") ] , 1 , paste , collapse = "-" ),
+     tidyr::unite_(data, "c", c("a", "b"), sep="-")$c,
+     times=25
+ )
Unit: milliseconds
                                                       expr        min         lq      mean     median        uq       max neval
do.call(paste, c(data[c("a", "b")], sep="-"))                 930.7208   951.3048  1129.334   997.2744  1066.084  2169.147    25
apply( data[ , c("a", "b") ] , 1 , paste , collapse = "-" )  9368.2800 10948.0124 11678.393 11136.3756 11878.308 17587.617    25
tidyr::unite_(data, "c", c("a", "b"), sep="-")$c              968.5861  1008.4716  1095.886  1035.8348  1082.726  1759.349    25

Session timeout in ASP.NET

Do you have anything in machine.config that might be taking effect? Setting the session timeout in web.config should override any settings in IIS or machine.config, however, if you have a web.config file somewhere in a subfolder in your application, that setting will override the one in the root of your application.

Also, if I remember correctly, the timeout in IIS only affects .asp pages, not .aspx. Are you sure your session code in web.config is correct? It should look something like:

<sessionState
    mode="InProc"
    stateConnectionString="tcpip=127.0.0.1:42424"
    stateNetworkTimeout="60"
    sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
    cookieless="false"
    timeout="60"
/>

How to get the file extension in PHP?

A better method is using strrpos + substr (faster than explode for that) :

$userfile_name = $_FILES['image']['name'];
$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);

But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php

Turning off auto indent when pasting text into vim

Another answer I did not see until now:

:se paste noai

Java Reflection: How to get the name of a variable?

As of Java 8, some local variable name information is available through reflection. See the "Update" section below.

Complete information is often stored in class files. One compile-time optimization is to remove it, saving space (and providing some obsfuscation). However, when it is is present, each method has a local variable table attribute that lists the type and name of local variables, and the range of instructions where they are in scope.

Perhaps a byte-code engineering library like ASM would allow you to inspect this information at runtime. The only reasonable place I can think of for needing this information is in a development tool, and so byte-code engineering is likely to be useful for other purposes too.


Update: Limited support for this was added to Java 8. Parameter (a special class of local variable) names are now available via reflection. Among other purposes, this can help to replace @ParameterName annotations used by dependency injection containers.

ScrollIntoView() causing the whole page to move

var el = document.querySelector("yourElement");
window.scroll({top: el.offsetTop, behavior: 'smooth'});

How do I extract Month and Year in a MySQL date and compare them?

There should also be a YEAR().

As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)

Or you could use multiple comparisons (i.e. years first, then months).

break out of if and foreach

A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.

Example:

// Setup a counter
$ImageCounter = 0;

// Increment through repeater fields
while ( condition ):
  $ImageCounter++;

   // Only print the first while instance
   if ($ImageCounter == 1) {
    echo 'It worked just once';
   }

// Close while statement
endwhile;

File to byte[] in Java

Simple way to do it:

File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);

// int byteLength = fff.length(); 

// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content

byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);

How to disable JavaScript in Chrome Developer Tools?

On OSX, I had to click the triple vertical dots, and uncheck a box in the settings section. Which can also be opened with f1

Determine version of Entity Framework I am using?

Another way to get the EF version you are using is to open the Package Manager Console (PMC) in Visual Studio and type Get-Package at the prompt. The first line with be for EntityFramework and list the version the project has installed.

PM> Get-Package

Id                             Version              Description/Release Notes                                                                                                                                                                                          
--                             -------              -------------------------                                                                                                                                                                                          
EntityFramework                5.0.0                Entity Framework is Microsoft's recommended data access technology for new applications.                                                                                                                           
jQuery                         1.7.1.1              jQuery is a new kind of JavaScript Library....                                           `enter code here`

It displays much more and you may have to scroll back up to find the EF line, but this is the easiest way I know of to find out.

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Ok, I want to provide a small answer to one of the sub-questions that the OP asked that don't seem to be addressed in the existing questions. Caveat, I have not done any testing or code generation, or disassembly, just wanted to share a thought for others to possibly expound upon.

Why does the static change the performance?

The line in question: uint64_t size = atol(argv[1])<<20;

Short Answer

I would look at the assembly generated for accessing size and see if there are extra steps of pointer indirection involved for the non-static version.

Long Answer

Since there is only one copy of the variable whether it was declared static or not, and the size doesn't change, I theorize that the difference is the location of the memory used to back the variable along with where it is used in the code further down.

Ok, to start with the obvious, remember that all local variables (along with parameters) of a function are provided space on the stack for use as storage. Now, obviously, the stack frame for main() never cleans up and is only generated once. Ok, what about making it static? Well, in that case the compiler knows to reserve space in the global data space of the process so the location can not be cleared by the removal of a stack frame. But still, we only have one location so what is the difference? I suspect it has to do with how memory locations on the stack are referenced.

When the compiler is generating the symbol table, it just makes an entry for a label along with relevant attributes, like size, etc. It knows that it must reserve the appropriate space in memory but doesn't actually pick that location until somewhat later in process after doing liveness analysis and possibly register allocation. How then does the linker know what address to provide to the machine code for the final assembly code? It either knows the final location or knows how to arrive at the location. With a stack, it is pretty simple to refer to a location based one two elements, the pointer to the stackframe and then an offset into the frame. This is basically because the linker can't know the location of the stackframe before runtime.

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

try this:

$names = array('Jesse', 'joey', 'jelnny', 'justine');
$names = new ArrayObject($names);

echo '<pre>';
print_r($names);

vs this:

$names = array('Jesse', 'joey', 'jelnny', 'justine');
$names = new ArrayObject($names);

//echo '<pre>';
print_r($names);

and it shows what the PRE does very neatly

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

Here it is! - SP 25 works on Visual Studio 2019, SP 21 on Visual Studio 2017

SAP released SAP Crystal Reports, developer version for Microsoft Visual Studio

You can get it here (click "Installation package for Visual Studio IDE")

To integrate “SAP Crystal Reports, developer version for Microsoft Visual Studio” you must run the Install Executable. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.

New In SP25 Release

Visual Studio 2019, Addressed incidents, Win10 1809, Security update

How to pass url arguments (query string) to a HTTP request on Angular?

Version 5+

With Angular 5 and up, you DON'T have to use HttpParams. You can directly send your json object as shown below.

let data = {limit: "2"};
this.httpClient.get<any>(apiUrl, {params: data});

Please note that data values should be string, ie; { params: {limit: "2"}}

Version 4.3.x+

Use HttpParams, HttpClient from @angular/common/http

import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get<any>(apiUrl, {params: params});

Also, try stringifying your nested object using JSON.stringify().

How do I load an org.w3c.dom.Document from XML in a string?

Whoa there!

There's a potentially serious problem with this code, because it ignores the character encoding specified in the String (which is UTF-8 by default). When you call String.getBytes() the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!

Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:

import java.io.StringReader;
import org.xml.sax.InputSource;
…
        return builder.parse(new InputSource(new StringReader(xml)));

It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.

"unmappable character for encoding" warning in Java

Most of the time this compile error comes when unicode(UTF-8 encoded) file compiling

javac -encoding UTF-8 HelloWorld.java

and also You can add this compile option to your IDE ex: Intellij idea
(File>settings>Java Compiler) add as additional command line parameter

enter image description here

-encoding : encoding Set the source file encoding name, such as EUC-JP and UTF-8.. If -encoding is not specified, the platform default converter is used. (DOC)

Execute action when back bar button of UINavigationController is pressed

I was able to achieve this with the following :

Swift 3

override func didMoveToParentViewController(parent: UIViewController?) {
   super.didMoveToParentViewController(parent)

   if parent == nil {
      println("Back Button pressed.")
      delegate?.goingBack()
   }           
}

Swift 4

override func didMove(toParent parent: UIViewController?) {
    super.didMove(toParent: parent)

    if parent == nil {
        debugPrint("Back Button pressed.")
    }
}

No need of custom back button.

Set ANDROID_HOME environment variable in mac

try with this after add ANDROID_HOME on your Environment Variable, work well on my mac

flutter config --android-sdk ANDROID_HOME

What is the difference between char * const and const char *?

First one is a syntax error. Maybe you meant the difference between

const char * mychar

and

char * const mychar

In that case, the first one is a pointer to data that can't change, and the second one is a pointer that will always point to the same address.

Using Java 8's Optional with Stream::flatMap

A slightly shorter version using reduce:

things.stream()
  .map(this::resolve)
  .reduce(Optional.empty(), (a, b) -> a.isPresent() ? a : b );

You could also move the reduce function to a static utility method and then it becomes:

  .reduce(Optional.empty(), Util::firstPresent );

Swipe ListView item From right to left show delete button

Define a ViewPager in your layout .xml:

<android.support.v4.view.ViewPager
    android:id="@+id/example_pager"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/abc_action_bar_default_height" />

And then, in your activity / fragment, set a custom pager adapter:

In an activity:

protected void onCreate(Bundle savedInstanceState) {
    PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
    ViewPager pager = (ViewPager) findViewById(R.id.example_pager);

    pager.setAdapter(adapter);
    // pager.setOnPageChangeListener(this); // You can set a page listener here
    pager.setCurrentItem(0);
}

In a fragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_layout, container, false);

    if (view != null) {
        PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
        ViewPager pager = (ViewPager) view.findViewById(R.id.example_pager);

        pager.setAdapter(adapter);
        // pager.setOnPageChangeListener(this); // You can set a page listener here
        pager.setCurrentItem(0);
    }

    return view;
}

Create our custom pager class:

// setup your PagerAdapter which extends FragmentPagerAdapter
class PagerAdapter extends FragmentPagerAdapter {
    public static final int NUM_PAGES = 2;
    private CustomFragment[] mFragments = new CustomFragment[NUM_PAGES];
    public PagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }
    @ Override
    public int getCount() {
        return NUM_PAGES;
    }
    @ Override
    public Fragment getItem(int position) {
        if (mFragments[position] == null) {
               // this calls the newInstance from when you setup the ListFragment
            mFragments[position] = new CustomFragment();
        }
        return mFragments[position];
    }
}

SSRS the definition of the report is invalid

This occurred for me due to changing the names of certain dataset fields within BIDS that were being referenced by parameters. I forgot to go into the parameters and reassign a default value (the default value of the parameter didn't automatically change to the newly renamed dataset field. Instead .

Difference between CR LF, LF and CR line break types?

This is a good summary I found:

The Carriage Return (CR) character (0x0D, \r) moves the cursor to the beginning of the line without advancing to the next line. This character is used as a new line character in Commodore and Early Macintosh operating systems (OS-9 and earlier).

The Line Feed (LF) character (0x0A, \n) moves the cursor down to the next line without returning to the beginning of the line. This character is used as a new line character in UNIX based systems (Linux, Mac OSX, etc)

The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. It moves the cursor both down to the next line and to the beginning of that line. This character is used as a new line character in most other non-Unix operating systems including Microsoft Windows, Symbian OS and others.

Source

Return Boolean Value on SQL Select Statement

Given that commonly 1 = true and 0 = false, all you need to do is count the number of rows, and cast to a boolean.

Hence, your posted code only needs a COUNT() function added:

SELECT CAST(COUNT(1) AS BIT) AS Expr1
FROM [User]
WHERE (UserID = 20070022)

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

In which conda environment is Jupyter executing?

As mentioned in the comments, conda support for jupyter notebooks is needed to switch kernels. Seems like this support is now available through conda itself (rather than relying on pip). http://docs.continuum.io/anaconda/user-guide/tasks/use-jupyter-notebook-extensions/

conda install nb_conda

which brings three other handy extensions in addition to Notebook Conda Kernels.

How to add an empty column to a dataframe?

Starting with v0.16.0, DF.assign() could be used to assign new columns (single/multiple) to a DF. These columns get inserted in alphabetical order at the end of the DF.

This becomes advantageous compared to simple assignment in cases wherein you want to perform a series of chained operations directly on the returned dataframe.

Consider the same DF sample demonstrated by @DSM:

df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
df
Out[18]:
   A  B
0  1  2
1  2  3
2  3  4

df.assign(C="",D=np.nan)
Out[21]:
   A  B C   D
0  1  2   NaN
1  2  3   NaN
2  3  4   NaN

Note that this returns a copy with all the previous columns along with the newly created ones. In order for the original DF to be modified accordingly, use it like : df = df.assign(...) as it does not support inplace operation currently.

How can I sort a List alphabetically?

descending alphabet:

List<String> list;
...
Collections.sort(list);
Collections.reverse(list);

ASP.NET MVC 3 - redirect to another action

return RedirectToAction("ActionName", "ControllerName");

Is there Selected Tab Changed Event in the standard WPF Tab Control

That is the correct event. Maybe it's not wired up correctly?

<TabControl SelectionChanged="TabControl_SelectionChanged">
    <TabItem Header="One"/>
    <TabItem Header="2"/>
    <TabItem Header="Three"/>
</TabControl>

in the codebehind....

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    int i = 34;
}

if I set a breakpoint on the i = 34 line, it ONLY breaks when i change tabs, even when the tabs have child elements and one of them is selected.

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

Apple lifted the restrictions on non-Objective C/C/C++ apps -- you just can't load code that isn't in the app bundle.

MonoTouch lets you use .NET languages -- C# is directly supported, but if you have Windows, you can make assemblies in any .NET language and use it.

There are rumors that Apple is going to support other languages directly -- I keep hearing ruby, but they are just rumors.

I think Lua is being used for game logic on a lot of apps.

EDIT (in 2018): Generally you can use any language that you can get to compile for iOS or even install language interpreters. The main thing you cannot do is load code from the Internet that wasn't in the app bundle.

People do this all of the time anyway (see React Native apps loading JavaScript from servers), but, technically, it's not allowed. The main thing that will get you attention from Apple if you make some kind of App Store that loads whole App-like things.

EDIT (in 2020): from @Pylot in comments: I know this is a long time ago, but now at least technically you can load code that isn’t embedded in the app, as you can write with JavaScript using the webview. Not staying your answer is wrong or anything, I definitely agree with you. but I was looking for something and found this post on the way. Figured if anyone sees this it might help them out.

How do I get the last four characters from a string in C#?

Use a generic Last<T>. That will work with ANY IEnumerable, including string.

public static IEnumerable<T> Last<T>(this IEnumerable<T> enumerable, int nLastElements)
{
    int count = Math.Min(enumerable.Count(), nLastElements);
    for (int i = enumerable.Count() - count; i < enumerable.Count(); i++)
    {
        yield return enumerable.ElementAt(i);
    }
}

And a specific one for string:

public static string Right(this string str, int nLastElements)
{
    return new string(str.Last(nLastElements).ToArray());
}

syntax error, unexpected T_VARIABLE

There is no semicolon at the end of that instruction causing the error.

EDIT

Like RiverC pointed out, there is no semicolon at the end of the previous line!

require ("scripts/connect.php") 

EDIT

It seems you have no-semicolons whatsoever.

http://php.net/manual/en/language.basic-syntax.instruction-separation.php

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

I would just do:

private static Timer timer;
 private static void Main()
 {
   timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
   Console.ReadLine();
 }

  private static void OnCallBack()
  {
    timer.Dispose();
    Thread.Sleep(3000); //doing some long operation
    timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
  }

And ignore the period parameter, since you're attempting to control the periodicy yourself.


Your original code is running as fast as possible, since you keep specifying 0 for the dueTime parameter. From Timer.Change:

If dueTime is zero (0), the callback method is invoked immediately.

In Python, how to check if a string only contains certain characters?

A different approach, because in my case I needed to also check whether it contained certain words (like 'test' in this example), not characters alone:

input_string = 'abc test'
input_string_test = input_string
allowed_list = ['a', 'b', 'c', 'test', ' ']

for allowed_list_item in allowed_list:
    input_string_test = input_string_test.replace(allowed_list_item, '')

if not input_string_test:
    # test passed

So, the allowed strings (char or word) are cut from the input string. If the input string only contained strings that were allowed, it should leave an empty string and therefore should pass if not input_string.

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Use a service api.

URL: https://fcm.googleapis.com/fcm/send

Method Type: POST

Headers:

Content-Type: application/json
Authorization: key=your api key

Body/Payload:

{ "notification": {
    "title": "Your Title",
    "text": "Your Text",
     "click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
  },
    "data": {
    "keyname": "any value " //you can get this data as extras in your activity and this data is optional
    },
  "to" : "to_id(firebase refreshedToken)"
} 

And with this in your app you can add below code in your activity to be called:

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

Also check the answer on Firebase onMessageReceived not called when app in background

Getting session value in javascript

If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".

Example for VB:

<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>  

How do I perform an insert and return inserted identity with Dapper?

I see answer for sql server, well here it is for MySql using a transaction


    Dim sql As String = "INSERT INTO Empleado (nombres, apepaterno, apematerno, direccion, colonia, cp, municipio, estado, tel, cel, correo, idrol, relojchecadorid, relojchecadorid2, `activo`,`extras`,`rfc`,`nss`,`curp`,`imagen`,sueldoXHra, IMSSCotiza, thumb) VALUES (@nombres, @apepaterno, @apematerno, @direccion, @colonia, @cp, @municipio, @estado, @tel, @cel, @correo, @idrol, @relojchecadorid, @relojchecadorid2, @activo, @extras, @rfc, @nss, @curp, @imagen,@sueldoXHra,@IMSSCotiza, @thumb)"
    
            Using connection As IDbConnection = New MySqlConnection(getConnectionString())
                connection.Open()
                Using transaction = connection.BeginTransaction
                    Dim res = connection.Execute(sql, New With {reg.nombres, reg.apepaterno, reg.apematerno, reg.direccion, reg.colonia, reg.cp, reg.municipio, reg.estado, reg.tel, reg.cel, reg.correo, reg.idrol, reg.relojchecadorid, reg.relojchecadorid2, reg.activo, reg.extras, reg.rfc, reg.nss, reg.curp, reg.imagen, reg.thumb, reg.sueldoXHra, reg.IMSSCotiza}, commandTimeout:=180, transaction:=transaction)
                    lastInsertedId = connection.ExecuteScalar("SELECT LAST_INSERT_ID();", transaction:=transaction)
                    If res > 0 Then 
transaction.Commit()
return true
end if
                    
                End Using
            End Using

getElementById returns null?

It can be caused by:

  1. Invalid HTML syntax (some tag is not closed or similar error)
  2. Duplicate IDs - there are two HTML DOM elements with the same ID
  3. Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?

Please, post your code.

How to write to file in Ruby?

For those of us that learn by example...

Write text to a file like this:

IO.write('/tmp/msg.txt', 'hi')

BONUS INFO ...

Read it back like this

IO.read('/tmp/msg.txt')

Frequently, I want to read a file into my clipboard ***

Clipboard.copy IO.read('/tmp/msg.txt')

And other times, I want to write what's in my clipboard to a file ***

IO.write('/tmp/msg.txt', Clipboard.paste)

*** Assumes you have the clipboard gem installed

See: https://rubygems.org/gems/clipboard

Return list from async/await method

Works for me:

List<Item> list = Task.Run(() => manager.GetList()).Result;

in this way it is not necessary to mark the method with async in the call.

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

Open a link in browser with java button?

try {
    Desktop.getDesktop().browse(new URL("http://www.google.com").toURI());
} catch (Exception e) {}

note: you have to include necessary imports from java.net

How to create a timeline with LaTeX?

There is timeline.sty floating around.

The syntax is simpler than using tikz:

%%% In LaTeX:
%%% \begin{timeline}{length}(start,stop)
%%%   .
%%%   .
%%%   .
%%% \end{timeline}
%%%
%%% in plain TeX
%%% \timeline{length}(start,stop)
%%%   .
%%%   .
%%%   .
%%% \endtimeline
%%% in between the two, we may have:
%%% \item{date}{description}
%%% \item[sortkey]{date}{description}
%%% \optrule
%%%
%%% the options to timeline are:
%%%      length The amount of vertical space that the timeline should
%%%                use.
%%%      (start,stop) indicate the range of the timeline. All dates or
%%%                sortkeys should lie in the range [start,stop]
%%%
%%% \item without the sort key expects date to be a number (such as a
%%%      year).
%%% \item with the sort key expects the sort key to be a number; date
%%%      can be anything. This can be used for log scale time lines
%%%      or dates that include months or days.
%%% putting \optrule inside of the timeline environment will cause a
%%%      vertical rule to be drawn down the center of the timeline.

I've used python's datetime.data.toordinal to convert dates to 'sort keys' in the context of the package.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

Error message looks like this

Error message => ORA-00001: unique constraint (schema.unique_constraint_name) violated

ORA-00001 occurs when: "a query tries to insert a "duplicate" row in a table". It makes an unique constraint to fail, consequently query fails and row is NOT added to the table."

Solution:

Find all columns used in unique_constraint, for instance column a, column b, column c, column d collectively creates unique_constraint and then find the record from source data which is duplicate, using following queries:

-- to find <<owner of the table>> and <<name of the table>> for unique_constraint

select *
from DBA_CONSTRAINTS
where CONSTRAINT_NAME = '<unique_constraint_name>';

Then use Justin Cave's query (pasted below) to find all columns used in unique_constraint:

  SELECT column_name, position
  FROM all_cons_columns
  WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

    -- to find duplicates

    select column a, column b, column c, column d
    from table
    group by column a, column b, column c, column d
    having count (<any one column used in constraint > ) > 1;

you can either delete that duplicate record from your source data (which was a select query in my particular case, as I experienced it with "Insert into select") or modify to make it unique or change the constraint.

How to use ng-repeat for dictionaries in AngularJs?

In Angular 7, the following simple example would work (assuming dictionary is in a variable called d):

my.component.ts:

keys: string[] = [];  // declaration of class member 'keys'
// component code ...

this.keys = Object.keys(d);

my.component.html: (will display list of key:value pairs)

<ul *ngFor="let key of keys">
    {{key}}: {{d[key]}}
</ul>

'profile name is not valid' error when executing the sp_send_dbmail command

profile name is not valid [SQLSTATE 42000] (Error 14607)

This happened to me after I copied job script from old SQL server to new SQL server. In SSMS, under Management, the Database Mail profile name was different in the new SQL Server. All I had to do was update the name in job script.

How to update only one field using Entity Framework?

public async Task<bool> UpdateDbEntryAsync(TEntity entity, params Expression<Func<TEntity, object>>[] properties)
{
    try
    {
        this.Context.Set<TEntity>().Attach(entity);
        EntityEntry<TEntity> entry = this.Context.Entry(entity);
        entry.State = EntityState.Modified;
        foreach (var property in properties)
            entry.Property(property).IsModified = true;
        await this.Context.SaveChangesAsync();
        return true;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

How do I add a ToolTip to a control?

Drag a tooltip control from the toolbox onto your form. You don't really need to give it any properties other than a name. Then, in the properties of the control you wish to have a tooltip on, look for a new property with the name of the tooltip control you just added. It will by default give you a tooltip when the cursor hovers the control.

Show and hide divs at a specific time interval using jQuery

Heres a another take on this problem, using recursion and without using mutable variables. Also, im not using setInterval so theres no cleanup that has to be done.

Having this HTML

<section id="testimonials">
    <h2>My testimonial spinner</h2>
    <div class="testimonial">
      <p>First content</p>
    </div>
    <div class="testimonial">
      <p>Second content</p>
    </div>
    <div class="testimonial">
       <p>Third content</p>
    </div>
</section>

Using ES2016

Here you call the function recursively and update the arguments.

  const testimonials = $('#testimonials')
      .children()
      .filter('div.testimonial');

  const showTestimonial = index => {

    testimonials.hide();
    $(testimonials[index]).fadeIn();

    return index === testimonials.length
      ? showTestimonial(0)
      : setTimeout(() => { showTestimonial(index + 1); }, 10000);
   }

showTestimonial(0); // id of the first element you want to show.

upstream sent too big header while reading response header from upstream

This is still the highest SO-question on Google when searching for this error, so let's bump it.

When getting this error and not wanting to deep-dive into the NGINX settings immediately, you might want to check your outputs to the debug console. In my case I was outputting loads of text to the FirePHP / Chromelogger console, and since this is all sent as a header, it was causing the overflow.

It might not be needed to change the webserver settings if this error is caused by just sending insane amounts of log messages.

How to symbolicate crash log Xcode?

There is an easier way using Xcode (without using command line tools and looking up addresses one at a time)

  1. Take any .xcarchive file. If you have one from before you can use that. If you don't have one, create one by running the Product > Archive from Xcode.

  2. Right click on the .xcarchive file and select 'Show Package Contents'

  3. Copy the dsym file (of the version of the app that crashed) to the dSYMs folder

  4. Copy the .app file (of the version of the app that crashed) to the Products > Applications folder

  5. Edit the Info.plist and edit the CFBundleShortVersionString and CFBundleVersion under the ApplicationProperties dictionary. This will help you identify the archive later

  6. Double click the .xcarchive to import it to Xcode. It should open Organizer.

  7. Go back to the crash log (in Devices window in Xcode)

  8. Drag your .crash file there (if not already present)

  9. The entire crash log should now be symbolicated. If not, then right click and select 'Re-symbolicate crash log'

How to convert timestamps to dates in Bash?

In this answer I copy Dennis Williamson's answer and modify it slightly to allow a vast speed increase when piping a column of many timestamps to the script. For example, piping 1000 timestamps to the original script with xargs -n1 on my machine took 6.929s as opposed to 0.027s with this modified version:

#!/bin/bash
LANG=C
if [[ -z "$1" ]]
then
    if [[ -p /dev/stdin ]]    # input from a pipe
    then
        cat - | gawk '{ print strftime("%c", $1); }'
    else
        echo "No timestamp given." >&2
        exit
    fi
else
    date -d @$1 +%c
fi

Changing upload_max_filesize on PHP

I got this to work using a .user.ini file in the same directory as my index.php script that loads my app. Here are the contents:

upload_max_filesize = "20M"
post_max_size = "25M"

This is the recommended solution for Heroku.

How many socket connections can a web server handle?

Note that HTTP doesn't typically keep TCP connections open for any longer than it takes to transmit the page to the client; and it usually takes much more time for the user to read a web page than it takes to download the page... while the user is viewing the page, he adds no load to the server at all.

So the number of people that can be simultaneously viewing your web site is much larger than the number of TCP connections that it can simultaneously serve.

Difference between a View's Padding and Margin

Below image will let you understand the padding and margin-

enter image description here

OperationalError, no such column. Django

You did not migrated all changes you made in model. so 1) python manage.py makemigrations 2) python manage.py migrate 3) python manag.py runserver it works 100%

How to find the difference in days between two dates?

The bash way - convert the dates into %y%m%d format and then you can do this straight from the command line:

echo $(( ($(date --date="031122" +%s) - $(date --date="021020" +%s) )/(60*60*24) ))

How to add "class" to host element?

You can simply add @HostBinding('class') class = 'someClass'; inside your @Component class.

Example:

@Component({
   selector: 'body',
   template: 'app-element'       
})
export class App implements OnInit {

  @HostBinding('class') class = 'someClass';

  constructor() {}      

  ngOnInit() {}
}

How to debug when Kubernetes nodes are in 'Not Ready' state

I was having similar issue because of a different reason:

Error:

cord@node1:~$ kubectl get nodes
NAME    STATUS     ROLES    AGE     VERSION
node1   Ready      master   17h     v1.13.5
node2   Ready      <none>   17h     v1.13.5
node3   NotReady   <none>   9m48s   v1.13.5

cord@node1:~$ kubectl describe node node3
Name:               node3
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  Ready            False   Thu, 18 Apr 2019 01:15:46 -0400   Thu, 18 Apr 2019 01:03:48 -0400   KubeletNotReady              runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Addresses:
  InternalIP:  192.168.2.6
  Hostname:    node3

cord@node3:~$ journalctl -u kubelet

Apr 18 01:24:50 node3 kubelet[54132]: W0418 01:24:50.649047   54132 cni.go:149] Error loading CNI config list file /etc/cni/net.d/10-calico.conflist: error parsing configuration list: no 'plugins' key
Apr 18 01:24:50 node3 kubelet[54132]: W0418 01:24:50.649086   54132 cni.go:203] Unable to update cni config: No valid networks found in /etc/cni/net.d
Apr 18 01:24:50 node3 kubelet[54132]: E0418 01:24:50.649402   54132 kubelet.go:2192] Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Apr 18 01:24:55 node3 kubelet[54132]: W0418 01:24:55.650816   54132 cni.go:149] Error loading CNI config list file /etc/cni/net.d/10-calico.conflist: error parsing configuration list: no 'plugins' key
Apr 18 01:24:55 node3 kubelet[54132]: W0418 01:24:55.650845   54132 cni.go:203] Unable to update cni config: No valid networks found in /etc/cni/net.d
Apr 18 01:24:55 node3 kubelet[54132]: E0418 01:24:55.651056   54132 kubelet.go:2192] Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Apr 18 01:24:57 node3 kubelet[54132]: I0418 01:24:57.248519   54132 setters.go:72] Using node IP: "192.168.2.6"

Issue:

My file: 10-calico.conflist was incorrect. Verified it from a different node and from sample file in the same directory "calico.conflist.template".

Resolution:

Changing the file, "10-calico.conflist" and restarting the service using "systemctl restart kubelet", resolved my issue:

NAME    STATUS   ROLES    AGE   VERSION
node1   Ready    master   18h   v1.13.5
node2   Ready    <none>   18h   v1.13.5
node3   Ready    <none>   48m   v1.13.5

What HTTP traffic monitor would you recommend for Windows?

I use Wireshark in most cases, but I have found Fiddler to be less of a hassle when dealing with encrypted data.

Declaration of Methods should be Compatible with Parent Methods in PHP

if you wanna keep OOP form without turning any error off, you can also:

class A
{
    public function foo() {
        ;
    }
}
class B extends A
{
    /*instead of : 
    public function foo($a, $b, $c) {*/
    public function foo() {
        list($a, $b, $c) = func_get_args();
        // ...

    }
}

How to use putExtra() and getExtra() for string data

first Screen.java

text=(TextView)findViewById(R.id.tv1);
edit=(EditText)findViewById(R.id.edit);
button=(Button)findViewById(R.id.bt1);

button.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        String s=edit.getText().toString();

        Intent ii=new Intent(MainActivity.this, newclass.class);
        ii.putExtra("name", s);
        startActivity(ii);
    }
});

Second Screen.java

public class newclass extends Activity
{
    private TextView Textv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent);
        Textv = (TextView)findViewById(R.id.tv2);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {
            String j =(String) b.get("name");
            Textv.setText(j);
        }
    }
}

Making a Windows shortcut start relative to where the folder is?

Easiest Solution:> Enviroment Variables handy little critters.

If the other person is to install/uncompress whatever to wherever on their respective system drive (usualy c:).

For demonstration purposes call our app "test.exe" (could be any executable/file doesn't have to be exe) and it is to be installed/uncompressed to folder MYCOMPANY\MYAPP\

Then just make a shortcut that uses %SystemDrive%\MYCOMPANY\MYAPP\test.exe as target and %SystemDrive%\MYCOMPANY\MYAPP\ as start in.

So now you would like to deploy it. Using an app like "WinRAR".

Easy way is using self-extraction zip file, neatly packaged as an ".exe" I would use one for my shortcut and another for the app. There is ways to make one self-extraction zip file that extracts different files to different directories, but i haven't played with it yet.

Another way is to make a selfextract for the shorcut, embed it inside the selfextract for the app and then apply a run once script,being that you know where the file is going to be. etc.

If you want to enable the installer to use custom installation/uncompress directories, then rather have a look at NSIS a scriptable install system.

Play around it's fun, hope my info helped.

Are querystring parameters secure in HTTPS (HTTP + SSL)?

remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.

http://en.wikipedia.org/wiki/File:IP_stack_connections.svg

that's the long way of saying, "Yes!"

Remove Safari/Chrome textinput/textarea glow

I just needed to remove this effect from my text input fields, and I couldn't get the other techniques to work quite right, but this is what works for me;

input[type="text"], input[type="text"]:focus{
            outline: 0;
            border:none;
            box-shadow:none;

    }

Tested in Firefox and in Chrome.

How to find the statistical mode?

A small modification to Ken Williams' answer, adding optional params na.rm and return_multiple.

Unlike the answers relying on names(), this answer maintains the data type of x in the returned value(s).

stat_mode <- function(x, return_multiple = TRUE, na.rm = FALSE) {
  if(na.rm){
    x <- na.omit(x)
  }
  ux <- unique(x)
  freq <- tabulate(match(x, ux))
  mode_loc <- if(return_multiple) which(freq==max(freq)) else which.max(freq)
  return(ux[mode_loc])
}

To show it works with the optional params and maintains data type:

foo <- c(2L, 2L, 3L, 4L, 4L, 5L, NA, NA)
bar <- c('mouse','mouse','dog','cat','cat','bird',NA,NA)

str(stat_mode(foo)) # int [1:3] 2 4 NA
str(stat_mode(bar)) # chr [1:3] "mouse" "cat" NA
str(stat_mode(bar, na.rm=T)) # chr [1:2] "mouse" "cat"
str(stat_mode(bar, return_mult=F, na.rm=T)) # chr "mouse"

Thanks to @Frank for simplification.

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

How can I scroll up more (increase the scroll buffer) in iTerm2?

There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal or you can just pump up number of lines that you want to have in history in the same place.

Read response headers from API response - Angular 5 + TypeScript

In my case in the POST response I want to have the authorization header because I was having the JWT Token in it. So what I read from this post is the header I we want should be added as an Expose Header from the back-end. So what I did was added the Authorization header to my Exposed Header like this in my filter class.

response.addHeader("Access-Control-Expose-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, X-Custom-header");
response.addHeader(HEADER_STRING, TOKEN_PREFIX + token); // HEADER_STRING == Authorization

And at my Angular Side

In the Component.

this.authenticationService.login(this.f.email.value, this.f.password.value)
  .pipe(first())
  .subscribe(
    (data: HttpResponse<any>) => {
      console.log(data.headers.get('authorization'));
    },
    error => {
      this.loading = false;
    });

At my Service Side.

return this.http.post<any>(Constants.BASE_URL + 'login', {username: username, password: password},
  {observe: 'response' as 'body'})
  .pipe(map(user => {
       return user;
  }));

How to enable C++17 compiling in Visual Studio?

Visual studio 2019 version:

The drop down menu was moved to:

  • Right click on project (not solution)
  • Properties (or Alt + Enter)
  • From the left menu select Configuration Properties
  • General
  • In the middle there is an option called "C++ Language Standard"
  • Next to it is the drop down menu
  • Here you can select Default, ISO C++ 14, 17 or latest

Instagram API: How to get all user media?

Use the best recursion function for getting all posts of users.

<?php
    set_time_limit(0);
    function getPost($url,$i) 
    {
        static $posts=array();  
        $json=file_get_contents($url);
        $data = json_decode($json);
        $ins_links=array();
        $page=$data->pagination;
        $pagearray=json_decode(json_encode($page),true);
        $pagecount=count($pagearray);

        foreach( $data->data as $user_data )
        {
            $posts[$i++]=$user_data->link;
        }

        if($pagecount>0)
            return getPost($page->next_url,$i);
        else
            return $posts;
    }
    $posts=getPost("https://api.instagram.com/v1/users/CLIENT-ACCOUNT-NUMBER/media/recent?client_id=CLIENT-ID&count=33",0);

    print_r($posts);

?>

How do you add a scroll bar to a div?

Css class to have a nice Div with scroll

.DivToScroll{   
    background-color: #F5F5F5;
    border: 1px solid #DDDDDD;
    border-radius: 4px 0 4px 0;
    color: #3B3C3E;
    font-size: 12px;
    font-weight: bold;
    left: -1px;
    padding: 10px 7px 5px;
}

.DivWithScroll{
    height:120px;
    overflow:scroll;
    overflow-x:hidden;
}

Check a collection size with JSTL

<c:if test="${companies.size() > 0}">

</c:if>

This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt instead of >.

<c:if test="${companies.size() gt 0}">

</c:if>

If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length() function then. From the documentation:

length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.

Put this at the top of JSP page to allow the fn namespace:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Or if you're using JSPX or Facelets:

<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">

And use like this in your page:

<p>The length of the companies collection is: ${fn:length(companies)}</p>

So to test with length of a collection:

<c:if test="${fn:length(companies) gt 0}">

</c:if>

Alternatively, for this specific case you can also simply use the EL empty operator:

<c:if test="${not empty companies}">

</c:if>

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

How to scroll the page when a modal dialog is longer than the screen?

simple way you can do this by adding this css So, you just added this to CSS:

.modal-body {
position: relative;
padding: 20px;
height: 200px;
overflow-y: scroll;
}

and it's working!

Loop over html table and get checked checkboxes (JQuery)

use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
 $('#out').append(this.id);
});

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

Changing all files' extensions in a folder with one command on Windows

In my case I had a directory with 800+ files ending with .StoredProcedure.sql (they were scripted with SSMS).

The solutions posted above didn't work. But I came up with this:

(Based on answers to batch programming - get relative path of file)

@echo off
setlocal enabledelayedexpansion
for %%f in (*) do (
  set B=%%f
  set B=!B:%CD%\=!
  ren "!B!" "!B:.StoredProcedure=!"
)

The above script removes the substring .StoredProcedure from the filename. I'm sure it can be adapted to cover more cases, ask for input and be overall more generic.

Clicking the back button twice to exit an activity

Some Improvements in Sudheesh B Nair's answer, i have noticed it will wait for handler even while pressing back twice immediately, so cancel handler as shown below. I have cancled toast also to prevent it to display after app exit.

 boolean doubleBackToExitPressedOnce = false;
        Handler myHandler;
        Runnable myRunnable;
        Toast myToast;

    @Override
        public void onBackPressed() {
            if (doubleBackToExitPressedOnce) {
                myHandler.removeCallbacks(myRunnable);
                myToast.cancel();
                super.onBackPressed();
                return;
            }

            this.doubleBackToExitPressedOnce = true;
            myToast = Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT);
            myToast.show();

            myHandler = new Handler();

            myRunnable = new Runnable() {

                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            };
            myHandler.postDelayed(myRunnable, 2000);
        }

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

use labelpad parameter:

pl.xlabel("...", labelpad=20)

or set it after:

ax.xaxis.labelpad = 20

How to retrieve Request Payload

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).

... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)

UPDATE

Also docs say that:

The encode option should only be set to true when a root is defined

So, probably, writer's root config is required.

SELECT only rows that contain only alphanumeric characters in MySQL

There is also this:

select m from table where not regexp_like(m, '^[0-9]\d+$')

which selects the rows that contains characters from the column you want (which is m in the example but you can change).

Most of the combinations don't work properly in Oracle platforms but this does. Sharing for future reference.

node.js shell command execution

There's a variable conflict in your run_cmd function:

  var me = this;
  child.stdout.on('data', function(me, data) {
    // me is overriden by function argument
    cb(me, data);
  });

Simply change it to this:

  var me = this;
  child.stdout.on('data', function(data) {
    // One argument only!
    cb(me, data);
  });

In order to see errors always add this:

  child.stderr.on('data', function(data) {
      console.log( data );
  });

EDIT You're code fails because you are trying to run dir which is not provided as a separate standalone program. It is a command in cmd process. If you want to play with filesystem use native require( 'fs' ).

Alternatively ( which I do not recommend ) you can create a batch file which you can then run. Note that OS by default fires batch files via cmd.

Extracting jar to specified directory

There is no such option available in jar command itself. Look into the documentation:

-C dir Temporarily changes directories (cd dir) during execution of the jar command while processing the following inputfiles argument. Its operation is intended to be similar to the -C option of the UNIX tar utility. For example: jar uf foo.jar -C classes bar.class changes to the classes directory and add the bar.class from that directory to foo.jar. The following command, jar uf foo.jar -C classes . -C bin xyz.class changes to the classes directory and adds to foo.jar all files within the classes directory (without creating a classes directory in the jar file), then changes back to the original directory before changing to the bin directory to add xyz.class to foo.jar. If classes holds files bar1 and bar2, then here's what the jar file contains using jar tf foo.jar: META-INF/

META-INF/MANIFEST.MF

bar1

bar2

xyz.class

.gitignore and "The following untracked working tree files would be overwritten by checkout"

It seems like you want the files ignored but they have already been commited. .gitignore has no effect on files that are already in the repo so they need to be removed with git rm --cached. The --cached will prevent it from having any effect on your working copy and it will just mark as removed the next time you commit. After the files are removed from the repo then the .gitignore will prevent them from being added again.

But you have another problem with your .gitignore, you are excessively using wildcards and its causing it to match less than you expect it to. Instead lets change the .gitignore and try this.

.bundle
.DS_Store
db/*.sqlite3
log/*.log
tmp/
public/system/images/
public/system/avatars/

PHP function to generate v4 UUID

Inspired by broofa's answer here.

preg_replace_callback('/[xy]/', function ($matches)
{
  return dechex('x' == $matches[0] ? mt_rand(0, 15) : (mt_rand(0, 15) & 0x3 | 0x8));
}
, 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');

Or if unable to use anonymous functions.

preg_replace_callback('/[xy]/', create_function(
  '$matches',
  'return dechex("x" == $matches[0] ? mt_rand(0, 15) : (mt_rand(0, 15) & 0x3 | 0x8));'
)
, 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');

Gridview get Checkbox.Checked value

You want an independent for loop for all the rows in grid view, then refer the below link

http://nikhilsreeni.wordpress.com/asp-net/checkbox/

Select all checkbox in Gridview

CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
    cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);

    cb.Checked = ((CheckBox)sender).Checked;
}

Select checked rows to a dataset; For gridview multiple edit

CheckBox cb = default(CheckBox);

foreach (GridViewRow row in grdforumcomments.Rows)
{
    cb = (CheckBox)row.FindControl("cbsel");
    if (cb.Checked)
    {
        drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
        drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
        drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
    }
}

Initialise a list to a specific length in Python

In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n to pre-allocate the length you want.

Slides available as PPT or via Google

The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.

Adding a parameter to the URL with JavaScript

You can use one of these:

Example:

var url = new URL("http://foo.bar/?x=1&y=2");

// If your expected result is "http://foo.bar/?x=1&y=2&x=42"
url.searchParams.append('x', 42);

// If your expected result is "http://foo.bar/?x=42&y=2"
url.searchParams.set('x', 42);

How to align texts inside of an input?

Here you go:

_x000D_
_x000D_
input[type=text] { text-align:right }
_x000D_
<form>_x000D_
    <input type="text" name="name" value="">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

Starting of Tomcat failed from Netbeans

I had the same problem but none of the answers above worked. The solution for me was to restore the Manager web application that is bundled with Tomcat.

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

Thanks to Joachim answer, I use the code to clear all back stack entry finally.

// In your FragmentActivity use getSupprotFragmentManager() to get the FragmentManager.

// Clear all back stack.
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
for (int i = 0; i < backStackCount; i++) {

    // Get the back stack fragment id.
    int backStackId = getSupportFragmentManager().getBackStackEntryAt(i).getId();

    getSupportFragmentManager().popBackStack(backStackId, 
        FragmentManager.POP_BACK_STACK_INCLUSIVE);

} /* end of for */

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

If using Nginx and getting a similar problem, then this might help:

Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.

If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

I was facing same issue. I tried everything possible for a day, but nothing worked. The dependency which was causing problem was using lower compile sdk, target sdk and min sdk. I created library module for the project, copied all the sources and matched the sdk versions with application sdk versions. And finally it worked like a charm.

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

How to enumerate an enum

LINQ Generic Way:

    public static Dictionary<int, string> ToList<T>() where T : struct =>
        ((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(value => Convert.ToInt32(value), value => value.ToString());

Usage:

        var enums = ToList<Enum>();

How to grep and replace

Here is what I would do:

find /path/to/dir -type f -iname "*filename*" -print0 | xargs -0 sed -i '/searchstring/s/old/new/g'

this will look for all files containing filename in the file's name under the /path/to/dir, than for every file found, search for the line with searchstring and replace old with new.

Though if you want to omit looking for a specific file with a filename string in the file's name, than simply do:

find /path/to/dir -type f -print0 | xargs -0 sed -i '/searchstring/s/old/new/g'

This will do the same thing above, but to all files found under /path/to/dir.

Can you have multiline HTML5 placeholder text in a <textarea>?

I find that if you use a lot of spaces, the browser will wrap it properly. Don't worry about using an exact number of spaces, just throw a lot in there, and the browser should properly wrap to the first non space character on the next line.

<textarea name="address" placeholder="1313 Mockingbird Ln         Saginaw, MI 45100"></textarea>

How to read data from a zip file without having to unzip the entire file

In such case you will need to parse zip local header entries. Each file, stored in zip file, has preceding Local File Header entry, which (normally) contains enough information for decompression, Generally, you can make simple parsing of such entries in stream, select needed file, copy header + compressed file data to other file, and call unzip on that part (if you don't want to deal with the whole Zip decompression code or library).

java.lang.ClassNotFoundException on working app

In my case I had to add android:name=".activity.SkeletonAppActivity" instead of android:name=".SkeletonAppActivity" in the manifest file for the main activity. SkeletonAppActivity was in a different package from the application class. Good luck!

Java: how to use UrlConnection to post request with authorization?

I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:

// HTTP POST request
private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:

static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

The encode function translates the string into application/x-www-form-urlencoded.

Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.

For this particular scenario, the following should work:

String data = "product[title]=" + title +
                "&product[content]=" + content + 
                "&product[price]=" + price.toString() +
                "&tags=" + tags;

Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.

Getting year in moment.js

The year() function just retrieves the year component of the underlying Date object, so it returns a number.

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

How do I get the Git commit count?

The following command prints the total number of commits on the current branch.

git shortlog -s -n  | awk '{ sum += $1; } END { print sum; }' "$@"

It is made up of two parts:

  1. Print the total logs number grouped by author (git shortlog -s -n)

    Example output

      1445  John C
      1398  Tom D
      1376  Chrsitopher P
       166  Justin T
       166  You
    
  2. Sum up the total commit number of each author, i.e. the first argument of each line, and print the result out (awk '{ sum += $1; } END { print sum; }' "$@")

    Using the same example as above it will sum up 1445 + 1398 + 1376 + 166 + 166. Therefore the output will be:

      4,551
    

Why should you use strncpy instead of strcpy?

The strncpy() function is the safer one: you have to pass the maximum length the destination buffer can accept. Otherwise it could happen that the source string is not correctly 0 terminated, in which case the strcpy() function could write more characters to destination, corrupting anything which is in the memory after the destination buffer. This is the buffer-overrun problem used in many exploits

Also for POSIX API functions like read() which does not put the terminating 0 in the buffer, but returns the number of bytes read, you will either manually put the 0, or copy it using strncpy().

In your example code, index is actually not an index, but a count - it tells how many characters at most to copy from source to destination. If there is no null byte among the first n bytes of source, the string placed in destination will not be null terminated

node.js - how to write an array to file

We can simply write the array data to the filesystem but this will raise one error in which ',' will be appended to the end of the file. To handle this below code can be used:

var fs = require('fs');

var file = fs.createWriteStream('hello.txt');
file.on('error', function(err) { Console.log(err) });
data.forEach(value => file.write(`${value}\r\n`));
file.end();

\r\n

is used for the new Line.

\n

won't help. Please refer this

How to save password when using Subversion from the console

None of these wonderful answers worked for me on a fresh install of Ubuntu. Instead, a clue from this answer did the trick for me.

I had to allow "simple" password store by setting this empty in ~/.subversion/config:

password-stores =

There was no existing setting, so being empty is significant.

This was in addition to:

store-passwords = yes

in ~/.subversion/servers.

What does principal end of an association means in 1:1 relationship in Entity framework

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

Java Round up Any Number

The easiest way to do this is just: You will receive a float or double and want it to convert it to the closest round up then just do System.out.println((int)Math.ceil(yourfloat)); it'll work perfectly