Programs & Examples On #For attribute

What does "for" attribute do in HTML <label> tag?

It labels whatever input is the parameter for the for attribute.

_x000D_
_x000D_
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
_x000D_
_x000D_

IBOutlet and IBAction

IBAction and IBOutlet are macros defined to denote variables and methods that can be referred to in Interface Builder.

IBAction resolves to void and IBOutlet resolves to nothing, but they signify to Xcode and Interface builder that these variables and methods can be used in Interface builder to link UI elements to your code.

If you're not going to be using Interface Builder at all, then you don't need them in your code, but if you are going to use it, then you need to specify IBAction for methods that will be used in IB and IBOutlet for objects that will be used in IB.

make arrayList.toArray() return more specific types

A shorter version of converting List to Array of specific type (for example Long):

Long[] myArray = myList.toArray(Long[]::new);

How to get started with Windows 7 gadgets

I have started writing one tutorial for everyone on this topic, see making gadgets for Windows 7.

bash script read all the files in directory

You can go without the loop:

find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \; 

HTH

How to downgrade tensorflow, multiple versions possible?

You can try to use the options of --no-cache-dir together with -I to overwrite the cache of the previous version and install the new version. For example:

pip3 install --no-cache-dir -I tensorflow==1.1

Then use the following command to check the version of tensorflow:

python3 -c ‘import tensorflow as tf; print(tf.__version__)’

It should show the right version got installed.

Archive the artifacts in Jenkins

In Jenkins 2.60.3 there is a way to delete build artifacts (not the archived artifacts) in order to save hard drive space on the build machine. In the General section, check "Discard old builds" with strategy "Log Rotation" and then go into its Advanced options. Two more options will appear related to keeping build artifacts for the job based on number of days or builds.

The settings that work for me are to enter 1 for "Max # of builds to keep with artifacts" and then to have a post-build action to archive the artifacts. This way, all artifacts from all builds will be archived, all information from builds will be saved, but only the last build will keep its own artifacts.

Discard old builds options

Set Text property of asp:label in Javascript PROPER way

Use the following code

<span id="sptext" runat="server"></span>

Java Script

document.getElementById('<%=sptext'%>).innerHTML='change text';

C#

sptext.innerHTML

Please initialize the log4j system properly. While running web service

If you are using Logger.getLogger(ClassName.class) then place your log4j.properties file in your class path:

yourproject/javaresoures/src/log4j.properties (Put inside src folder)

SQL Error with Order By in Subquery

For a simple count like the OP is showing, the Order by isn't strictly needed. If they are using the result of the subquery, it may be. I am working on a similiar issue and got the same error in the following query:

-- I want the rows from the cost table with an updateddate equal to the max updateddate:

    SELECT * FROM #Costs Cost
    INNER JOIN
    (
        SELECT Entityname, costtype, MAX(updatedtime) MaxUpdatedTime
        FROM #HoldCosts cost
        GROUP BY Entityname, costtype
        ORDER BY Entityname, costtype  -- *** This causes an error***
    ) CostsMax
        ON  Costs.Entityname = CostsMax.entityname
        AND Costs.Costtype = CostsMax.Costtype
        AND Costs.UpdatedTime = CostsMax.MaxUpdatedtime
    ORDER BY Costs.Entityname, Costs.costtype

-- *** To accomplish this, there are a few options:

-- Add an extraneous TOP clause, This seems like a bit of a hack:

    SELECT * FROM #Costs Cost
    INNER JOIN
    (
        SELECT TOP 99.999999 PERCENT Entityname, costtype, MAX(updatedtime) MaxUpdatedTime
        FROM #HoldCosts cost
        GROUP BY Entityname, costtype
        ORDER BY Entityname, costtype  
    ) CostsMax
        ON Costs.Entityname = CostsMax.entityname
        AND Costs.Costtype = CostsMax.Costtype
        AND Costs.UpdatedTime = CostsMax.MaxUpdatedtime
    ORDER BY Costs.Entityname, Costs.costtype

-- **** Create a temp table to order the maxCost

    SELECT Entityname, costtype, MAX(updatedtime) MaxUpdatedTime
    INTO #MaxCost
    FROM #HoldCosts cost
    GROUP BY Entityname, costtype
    ORDER BY Entityname, costtype  

    SELECT * FROM #Costs Cost
    INNER JOIN #MaxCost CostsMax
        ON Costs.Entityname = CostsMax.entityname
        AND Costs.Costtype = CostsMax.Costtype
        AND Costs.UpdatedTime = CostsMax.MaxUpdatedtime
    ORDER BY Costs.Entityname, costs.costtype

Other possible workarounds could be CTE's or table variables. But each situation requires you to determine what works best for you. I tend to look first towards a temp table. To me, it is clear and straightforward. YMMV.

Create a symbolic link of directory in Ubuntu

This is the behavior of ln if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx to be the symlink, you should remove that directory first and run that same command.

return query based on date

You can also try:

{
    "dateProp": { $gt: new Date('06/15/2016').getTime() }
}

How to set gradle home while importing existing project in Android studio

For Mac OS, you can use the following -

  1. /usr/local/opt/gradle/libexec/ or more generically - path/to/gradle/libexec/ - this is recommended. (the first path is what's achieved after installing gradle via Homebrew)
  2. /path/to/android/studio/plugins/gradle - I don't recommend this because this version of Gradle might be out of date, and Android Studio itself might say it's incompatible.

How to manually install an artifact in Maven 2?

All the posted answers rightfully discuss this from a strictly maven perspective. My issues was in doing this install for maven using Netbeans as my primary IDE. I found the below article helpful.

Credit to the following netbeans forum article: http://forums.netbeans.org/topic22907.html

  1. In Maven project open "Add dependency" dialog
  2. Make up some groupId, artifactId and version and fill them, OK.
  3. Dependency will be added to the pom.xml and will appear under "Libraries" node of maven project
  4. Right-click Lib node and "manually install artifact", fill the path to the jar. Jar should be installed to local Maven repo with coordinates entered in step 2)

AngularJS is rendering <br> as text not as a newline

I've used like this

function chatSearchCtrl($scope, $http,$sce) {
 // some more my code

// take this 
data['message'] = $sce.trustAsHtml(data['message']);

$scope.searchresults = data;

and in html I did

<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>

thats it I get my <br/> tag rendered

Display a decimal in scientific notation

def formatE_decimal(x, prec=2):
    """ Examples:
    >>> formatE_decimal('0.1613965',10)
    '1.6139650000E-01'
    >>> formatE_decimal('0.1613965',5)
    '1.61397E-01'
    >>> formatE_decimal('0.9995',2)
    '1.00E+00'
    """
    xx=decimal.Decimal(x) if type(x)==type("") else x 
    tup = xx.as_tuple()
    xx=xx.quantize( decimal.Decimal("1E{0}".format(len(tup[1])+tup[2]-prec-1)), decimal.ROUND_HALF_UP )
    tup = xx.as_tuple()
    exp = xx.adjusted()
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in tup[1][1:prec+1])   
    if prec>0:
        return '{sign}{int}.{dec}E{exp:+03d}'.format(sign=sign, int=tup[1][0], dec=dec, exp=exp)
    elif prec==0:
        return '{sign}{int}E{exp:+03d}'.format(sign=sign, int=tup[1][0], exp=exp)
    else:
        return None

Logical operators ("and", "or") in DOS batch

Athul Prakash (age 16 at the time) gave a logical idea for how to implement an OR test by negating the conditions in IF statements and then using the ELSE clause as the location to put the code that requires execution. I thought to myself that there are however two else clauses usually needed since he is suggesting using two IF statements, and so the executed code needs to be written twice. However, if a GOTO is used to skip past the required code, instead of writing ELSE clauses the code for execution only needs to be written once.

Here is a testable example of how I would implement Athul Prakash's negative logic to create an OR.

In my example, someone is allowed to drive a tank if they have a tank licence OR they are doing their military service. Enter true or false at the two prompts and you will be able to see whether the logic allows you to drive a tank.

@ECHO OFF
@SET /p tanklicence=tanklicence:
@SET /p militaryservice=militaryservice:

IF /I NOT %tanklicence%==true IF /I NOT %militaryservice%==true GOTO done

ECHO I am driving a tank with tanklicence set to %tanklicence% and militaryservice set to %militaryservice%

:done

PAUSE

What is the difference between "::" "." and "->" in c++

-> is for pointers to a class instance

. is for class instances

:: is for classnames - for example when using a static member

Delete multiple rows by selecting checkboxes using PHP

 $deleted = $_POST['checkbox'];
 $sql = "DELETE FROM $tbl_name WHERE id IN (".implode(",", $deleted ) . ")";

How to find out mySQL server ip address from phpmyadmin

select * from SHOW VARIABLES WHERE Variable_name = 'hostname';

How to convert Varchar to Int in sql server 2008?

Spaces will not be a problem for cast, however characters like TAB, CR or LF will appear as spaces, will not be trimmed by LTRIM or RTRIM, and will be a problem.

For example try the following:

declare @v1 varchar(21) = '66',
        @v2 varchar(21) = '   66   ',
        @v3 varchar(21) = '66' + char(13) + char(10),
        @v4 varchar(21) = char(9) + '66'

select cast(@v1 as int)   -- ok
select cast(@v2 as int)   -- ok
select cast(@v3 as int)   -- error
select cast(@v4 as int)   -- error

Check your input for these characters and if you find them, use REPLACE to clean up your data.


Per your comment, you can use REPLACE as part of your cast:

select cast(replace(replace(@v3, char(13), ''), char(10), '') as int)

If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR and LF before it is entered.

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

You need to allow transaction to your DAO method. Add,

@Transactional(readOnly = true, propagation=Propagation.NOT_SUPPORTED)

over your dao methods. And @Transactional should be from the package:

org.springframework.transaction.annotation.Transactional

How to center absolute div horizontally using CSS?

This doesn't work in IE8 but might be an option to consider. It is primarily useful if you do not want to specify a width.

.element
{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

How can I align button in Center or right using IONIC framework?

center tag aligns the buttons within it as expected:  

<ion-footer>
    <ion-toolbar>
        <center>
            <button royal>
                Contacts
                <ion-icon name="contact"></ion-icon>
            </button>
            <button secondary>
                Receive
                <ion-icon name="arrow-round-back"></ion-icon>
            </button>
            <button danger>
                Wallet
                <ion-icon name="home"></ion-icon>
            </button>
            <button secondary>
                Send
                <ion-icon name="send"></ion-icon>
            </button>
            <button danger>
                Transactions
                <ion-icon name="archive"></ion-icon>
            </button>
            <button danger>
                About
                <ion-icon name="information-circle"></ion-icon>
            </button>
        </center>
    </ion-toolbar>
</ion-footer>

What is w3wp.exe?

w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.

You can get more information on w3wp.exe here

http://www.processlibrary.com/en/directory/files/w3wp/25761/

'Property does not exist on type 'never'

In my case (I'm using typescript) I was trying to simulate response with fake data where the data is assigned later on. My first attempt was with:

let response = {status: 200, data: []};

and later, on the assignment of the fake data it starts complaining that it is not assignable to type 'never[]'. Then I defined the response like follows and it accepted it..

let dataArr: MyClass[] = [];
let response = {status: 200, data: dataArr};

and assigning of the fake data:

response.data = fakeData;

How does Trello access the user's clipboard?

Something very similar can be seen on http://goo.gl when you shorten the URL.

There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.

When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)

Download/Stream file from URL - asp.net

You could use HttpWebRequest to get the file and stream it back to the client. This allows you to get the file with a url. An example of this that I found ( but can't remember where to give credit ) is

    //Create a stream for the file
    Stream stream = null;

    //This controls how many bytes to read at a time and send to the client
    int bytesToRead = 10000;

    // Buffer to read bytes in chunk size specified above
    byte[] buffer = new Byte[bytesToRead];

    // The number of bytes read
    try
    {
      //Create a WebRequest to get the file
      HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);

      //Create a response for this request
      HttpWebResponse fileResp = (HttpWebResponse) fileReq.GetResponse();

      if (fileReq.ContentLength > 0)
        fileResp.ContentLength = fileReq.ContentLength;

        //Get the Stream returned from the response
        stream = fileResp.GetResponseStream();

        // prepare the response to the client. resp is the client Response
        var resp = HttpContext.Current.Response;

        //Indicate the type of data being sent
        resp.ContentType = "application/octet-stream";

        //Name the file 
        resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

        int length;
        do
        {
            // Verify that the client is connected.
            if (resp.IsClientConnected)
            {
                // Read data into the buffer.
                length = stream.Read(buffer, 0, bytesToRead);

                // and write it out to the response's output stream
                resp.OutputStream.Write(buffer, 0, length);

                // Flush the data
                resp.Flush();

                //Clear the buffer
                buffer = new Byte[bytesToRead];
            }
            else
            {
                // cancel the download if client has disconnected
                length = -1;
            }
        } while (length > 0); //Repeat until no data is read
    }
    finally
    {
        if (stream != null)
        {
            //Close the input stream
            stream.Close();
        }
    }

Function Pointers in Java

To achieve similar functionality you could use anonymous inner classes.

If you were to define a interface Foo:

interface Foo {
    Object myFunc(Object arg);
}

Create a method bar which will receive a 'function pointer' as an argument:

public void bar(Foo foo) {
    // .....
    Object object = foo.myFunc(argValue);
    // .....
}

Finally call the method as follows:

bar(new Foo() {
    public Object myFunc(Object arg) {
        // Function code.
    }
}

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

How can I get the name of an html page in Javascript?

var path = window.location.pathname;
var page = path.split("/").pop();
console.log( page );

Retrieving parameters from a URL

The url you are referring is a query type and I see that the request object supports a method called arguments to get the query arguments. You may also want try self.request.get('def') directly to get your value from the object..

PHP call Class method / function

To answer your question, the current method would be to create the object then call the method:

$functions = new Functions();
$var = $functions->filter($_GET['params']);

Another way would be to make the method static since the class has no private data to rely on:

public static function filter($data){

This can then be called like so:

$var = Functions::filter($_GET['params']);

Lastly, you do not need a class and can just have a file of functions which you include. So you remove the class Functions and the public in the method. This can then be called like you tried:

$var = filter($_GET['params']);

How to remove the default link color of the html hyperlink 'a' tag?

I had this challenge when I was working on a Rails 6 application using Bootstrap 4.

My challenge was that I didn't want this styling to override the default link styling in the application.

So I created a CSS file called custom.css or custom.scss.

And then defined a new CSS rule with the following properties:

.remove_link_colour {
  a, a:hover, a:focus, a:active {
      color: inherit;
      text-decoration: none;
  }
}

Then I called this rule wherever I needed to override the default link styling.

<div class="product-card__buttons">
  <button class="btn btn-success remove_link_colour" type="button"><%= link_to 'Edit', edit_product_path(product) %></button>
  <button class="btn btn-danger remove_link_colour" type="button"><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></button>
</div>

This solves the issue of overriding the default link styling and removes the default colour, hover, focus, and active styling in the buttons only in places where I call the CSS rule.

That's all.

I hope this helps

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:

Request:

GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:

Request:

GET /BigBuckBunny_320x180.mp4
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*

Tips:

You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456

Or:

Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.

Python string class like StringBuilder in C#?

There is no explicit analogue - i think you are expected to use string concatenations(likely optimized as said before) or third-party class(i doubt that they are a lot more efficient - lists in python are dynamic-typed so no fast-working char[] for buffer as i assume). Stringbuilder-like classes are not premature optimization because of innate feature of strings in many languages(immutability) - that allows many optimizations(for example, referencing same buffer for slices/substrings). Stringbuilder/stringbuffer/stringstream-like classes work a lot faster than concatenating strings(producing many small temporary objects that still need allocations and garbage collection) and even string formatting printf-like tools, not needing of interpreting formatting pattern overhead that is pretty consuming for a lot of format calls.

What is git fast-forwarding?

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

In another way,

If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”

There won't be any "merge commit" in fast-forwarding merge.

Center image in div horizontally

text-align: center will only work for horizontal centering. For it to be in the complete center, vertical and horizontal you can do the following :

div
{
    position: relative;
}
div img
{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: [-50% of your image's width];
    margin-top: [-50% of your image's height];
}

iPhone get SSID without private library

UPDATE FOR iOS 10 and up

CNCopySupportedInterfaces is no longer deprecated in iOS 10. (API Reference)

You need to import SystemConfiguration/CaptiveNetwork.h and add SystemConfiguration.framework to your target's Linked Libraries (under build phases).

Here is a code snippet in swift (RikiRiocma's Answer):

import Foundation
import SystemConfiguration.CaptiveNetwork

public class SSID {
    class func fetchSSIDInfo() -> String {
        var currentSSID = ""
        if let interfaces = CNCopySupportedInterfaces() {
            for i in 0..<CFArrayGetCount(interfaces) {
                let interfaceName: UnsafePointer<Void> = CFArrayGetValueAtIndex(interfaces, i)
                let rec = unsafeBitCast(interfaceName, AnyObject.self)
                let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)")
                if unsafeInterfaceData != nil {
                    let interfaceData = unsafeInterfaceData! as Dictionary!
                    currentSSID = interfaceData["SSID"] as! String
                }
            }
        }
        return currentSSID
    }
}

(Important: CNCopySupportedInterfaces returns nil on simulator.)

For Objective-c, see Esad's answer here and below

+ (NSString *)GetCurrentWifiHotSpotName {    
    NSString *wifiName = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info[@"SSID"]) {
            wifiName = info[@"SSID"];
        }
    }
    return wifiName;
}

UPDATE FOR iOS 9

As of iOS 9 Captive Network is deprecated*. (source)

*No longer deprecated in iOS 10, see above.

It's recommended you use NEHotspotHelper (source)

You will need to email apple at [email protected] and request entitlements. (source)

Sample Code (Not my code. See Pablo A's answer):

for(NEHotspotNetwork *hotspotNetwork in [NEHotspotHelper supportedNetworkInterfaces]) {
    NSString *ssid = hotspotNetwork.SSID;
    NSString *bssid = hotspotNetwork.BSSID;
    BOOL secure = hotspotNetwork.secure;
    BOOL autoJoined = hotspotNetwork.autoJoined;
    double signalStrength = hotspotNetwork.signalStrength;
}

Side note: Yup, they deprecated CNCopySupportedInterfaces in iOS 9 and reversed their position in iOS 10. I spoke with an Apple networking engineer and the reversal came after so many people filed Radars and spoke out about the issue on the Apple Developer forums.

RegEx to extract all matches from string using RegExp.exec

This isn't really going to help with your more complex issue but I'm posting this anyway because it is a simple solution for people that aren't doing a global search like you are.

I've simplified the regex in the answer to be clearer (this is not a solution to your exact problem).

var re = /^(.+?):"(.+)"$/
var regExResult = re.exec('description:"aoeu"');
var purifiedResult = purify_regex(regExResult);

// We only want the group matches in the array
function purify_regex(reResult){

  // Removes the Regex specific values and clones the array to prevent mutation
  let purifiedArray = [...reResult];

  // Removes the full match value at position 0
  purifiedArray.shift();

  // Returns a pure array without mutating the original regex result
  return purifiedArray;
}

// purifiedResult= ["description", "aoeu"]

That looks more verbose than it is because of the comments, this is what it looks like without comments

var re = /^(.+?):"(.+)"$/
var regExResult = re.exec('description:"aoeu"');
var purifiedResult = purify_regex(regExResult);

function purify_regex(reResult){
  let purifiedArray = [...reResult];
  purifiedArray.shift();
  return purifiedArray;
}

Note that any groups that do not match will be listed in the array as undefined values.

This solution uses the ES6 spread operator to purify the array of regex specific values. You will need to run your code through Babel if you want IE11 support.

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Assuming you want to replace the newlines with something so that something like this:

the quick brown fox\r\n
jumped over the lazy dog\r\n

doesn't end up like this:

the quick brown foxjumped over the lazy dog

I'd do something like this:

string[] SplitIntoChunks(string text, int size)
{
    string[] chunk = new string[(text.Length / size) + 1];
    int chunkIdx = 0;
    for (int offset = 0; offset < text.Length; offset += size)
    {
        chunk[chunkIdx++] = text.Substring(offset, size);
    }
    return chunk;
}    

string[] GetComments()
{
    var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox; 
    if (cmtTb == null)
    {
        return new string[] {};
    }

    // I assume you don't want to run the text of the two lines together?
    var text = cmtTb.Text.Replace(Environment.Newline, " ");
    return SplitIntoChunks(text, 50);    
}

I apologize if the syntax isn't perfect; I'm not on a machine with C# available right now.

ERROR 1049 (42000): Unknown database

blog_development doesn't exist

You can see this in sql by the 0 rows affected message

create it in mysql with

mysql> create database blog_development

However as you are using rails you should get used to using

$ rake db:create

to do the same task. It will use your database.yml file settings, which should include something like:

development:
  adapter: mysql2
  database: blog_development
  pool: 5

Also become familiar with:

$ rake db:migrate  # Run the database migration
$ rake db:seed     # Run thew seeds file create statements
$ rake db:drop     # Drop the database

What is the difference between lower bound and tight bound?

The basic difference between

Blockquote

asymptotically upper bound and asymptotically tight Asym.upperbound means a given algorythm that can executes with maximum amount of time depending upon the number of inputs ,for eg in sorting algo if all the array (n)elements are in descending order then for ascending them it will take a running time of O(n) which shows upper bound complexity ,but if they are already sorted then it will take ohm(1).so we generally used "O"notation for upper bound complexity.

Asym. tightbound bound shows the for eg(c1g(n)<=f(n)<=c2g(n)) shows the tight bound limit such that the function have the value in between two bound (upper bound and lower bound),giving the average case.

Select N random elements from a List<T> in C#

I would use an extension method.

    public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> elements, int countToTake)
    {
        var random = new Random();

        var internalList = elements.ToList();

        var selected = new List<T>();
        for (var i = 0; i < countToTake; ++i)
        {
            var next = random.Next(0, internalList.Count - selected.Count);
            selected.Add(internalList[next]);
            internalList[next] = internalList[internalList.Count - selected.Count];
        }
        return selected;
    }

Difference between spring @Controller and @RestController annotation

If you use @RestController you cannot return a view (By using Viewresolver in Spring/springboot) and yes @ResponseBody is not needed in this case.

If you use @Controller you can return a view in Spring web MVC.

AngularJS - Animate ng-view transitions

Check this code:

Javascript:

app.config( ["$routeProvider"], function($routeProvider){
    $routeProvider.when("/part1", {"templateUrl" : "part1"});
    $routeProvider.when("/part2", {"templateUrl" : "part2"});
    $routeProvider.otherwise({"redirectTo":"/part1"});
  }]
);

function HomeFragmentController($scope) {
    $scope.$on("$routeChangeSuccess", function (scope, next, current) {
        $scope.transitionState = "active"
    });
}

CSS:

.fragmentWrapper {
    overflow: hidden;
}

.fragment {
    position: relative;
    -moz-transition-property: left;
    -o-transition-property: left;
    -webkit-transition-property: left;
    transition-property: left;
    -moz-transition-duration: 0.1s;
    -o-transition-duration: 0.1s;
    -webkit-transition-duration: 0.1s;
    transition-duration: 0.1s
}

.fragment:not(.active) {
    left: 540px;
}

.fragment.active {
    left: 0px;
}

Main page HTML:

<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>

Partials HTML example:

<div id="part1" class="fragment {{transitionState}}">
</div>

Converting a String to Object

A String is a type of Object. So any method that accepts Object as parameter will surely accept String also. Please provide more of your code if you still do not find a solution.

How To Change DataType of a DataColumn in a DataTable?

You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below.

DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}

How to have jQuery restrict file types on upload?

I try to write working code example, I test it and everything works.

Hare is code:

HTML:

<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, @Model.MaxSize.ToString(),@Html.Raw(Json.Encode(Model.FileExtensionsList)))" />

Javascript:

 //function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
    var val = $(element).val(); //get file value

    var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention 
    if ($.inArray(ext, extentionsArray) == -1) {
        alert('false extension!');
    }

    var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
    if (fileSize > maxSize) {
        alert("Large file");// if Maxsize from Model > real file size alert this
    }
}

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

SDK Manager.exe doesn't work

I was experiencing the UnsatisfiedLinkError on Windows 7 64-bit after installing adt-bundle-windows-x86_64-20130717.zip:

 Exception in thread "main" java.lang.UnsatisfiedLinkError: no swt-win32-3550 or swt-win32 in swt.library.path, java.library.path or the jar file

The root cause was that McAfee has a feature that blocks loading DLL's from the temporary directory. This is a problem because android.bat copies a bunch of JAR and DLL files to a temporary directory and runs the program from there, to make it easy to upgrade the app in-place.

This feature can be disabled, however. You can either disable "Access Protection" altogether or only disable the feature that blocks loading DLLs from temporary folders.

Screenshot showing the McAfee UI where access protection can be disabled Screenshot showing the McAfee UI where you can disable the feature where it blocks loading DLLs from the temp directory

Styling an input type="file" button

Plug-in solutions I found were too heavy-weight, so, I made my own jQuery plug-in called Drolex FileStyle.

This plug-in allows you to style file input fields however you want. Actually, you style div elements to look like a tricked out file input, and the actual file input is automatically overlaid with 0% opacity. No additional HTML is required. Just include the css and js files in the page you want Drolex FileStyle and that's it! Edit the css file to your liking. Don't forget the jQuery library if your page doesn't already have it. If the client does not run JavaScript, then the file input will not be modified by js or css.

Tested to work in Chrome 24, Firefox 18, Internet Explorer 9. Expected to work in previous versions of those and others.

Download: http://web.drolex.net/Drolex-FileStyle.zip

How can I check if an InputStream is empty without reading from it?

How about using inputStreamReader.ready() to find out?

import java.io.InputStreamReader;

/// ...

InputStreamReader reader = new InputStreamReader(inputStream);
if (reader.ready()) {
    // do something
}

// ...

Python - Get Yesterday's date as a string in YYYY-MM-DD format

>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

If you happen to use CRA with default yarn package manager use the following. Worked for me.

yarn remove node-sass 
yarn add [email protected]

How to smooth a curve in the right way?

EDIT: look at this answer. Using np.cumsum is much faster than np.convolve

A quick and dirty way to smooth data I use, based on a moving average box (by convolution):

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.8

def smooth(y, box_pts):
    box = np.ones(box_pts)/box_pts
    y_smooth = np.convolve(y, box, mode='same')
    return y_smooth

plot(x, y,'o')
plot(x, smooth(y,3), 'r-', lw=2)
plot(x, smooth(y,19), 'g-', lw=2)

enter image description here

How to display two digits after decimal point in SQL Server

You can also use below code which helps me:

select convert(numeric(10,2), column_name) as Total from TABLE_NAME

where Total is alias of the field you want.

How to sort a List<Object> alphabetically using Object name field

Using Java 8 Comparator.comparing:

list.sort(Comparator.comparing(Campaign::getName));

Most efficient way to get table row count

If you do not have privilege for "Show Status" then, The best option is to, create two triggers and a new table which keeps the row count of your billion records table.

Example:

TableA >> Billion Records
TableB >> 1 Column and 1 Row

Whenever there is insert query on TableA(InsertTrigger), Increment the row value by 1 TableB
Whenever there is delete query on TableA(DeleteTrigger), Decrement the row value by 1 in TableB

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Here are some supplemental examples to see the raw text that Postman passes in the request. You can see this by opening the Postman console:

enter image description here

form-data

Header

content-type: multipart/form-data; boundary=--------------------------590299136414163472038474

Body

key1=value1key2=value2

x-www-form-urlencoded

Header

Content-Type: application/x-www-form-urlencoded

Body

key1=value1&key2=value2

Raw text/plain

Header

Content-Type: text/plain

Body

This is some text.

Raw json

Header

Content-Type: application/json

Body

{"key1":"value1","key2":"value2"}

How do I access ViewBag from JS

You can achieve the solution, by doing this:

JavaScript:

var myValue = document.getElementById("@(ViewBag.CC)").value;

or if you want to use jQuery, then:

jQuery

var myValue = $('#' + '@(ViewBag.CC)').val();

Converting Java objects to JSON with Jackson

I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.

I used a third-party library to aid in the endeavor: org.codehaus.jackson All of the downloads for this can be found here.

For base JSON functionality, you need to add the following jars to your project's libraries: jackson-mapper-asl and jackson-core-asl

Choose the version your project needs. (Typically you can go with the latest stable build).

Once they are imported in to your project's libraries, add the following import lines to your code:

 import org.codehaus.jackson.JsonGenerationException;
 import org.codehaus.jackson.map.JsonMappingException;
 import org.codehaus.jackson.map.ObjectMapper;

With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service

User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "[email protected]";

ObjectMapper mapper = new ObjectMapper();

try {
    // convert user object to json string and return it 
    return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException  e) {
    // catch various errors
    e.printStackTrace();
}

The result should looks like this: {"firstName":"Sample","lastName":"User","email":"[email protected]"}

How to check in Javascript if one element is contained within another

You can use the contains method

var result = parent.contains(child);

or you can try to use compareDocumentPosition()

var result = nodeA.compareDocumentPosition(nodeB);

The last one is more powerful: it return a bitmask as result.

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

How do I find the current machine's full hostname in C (hostname and domain information)?

My solution:

#ifdef WIN32
    #include <Windows.h>
    #include <tchar.h>
#else
    #include <unistd.h>
#endif

void GetMachineName(char machineName[150])
{
    char Name[150];
    int i=0;

    #ifdef WIN32
        TCHAR infoBuf[150];
        DWORD bufCharCount = 150;
        memset(Name, 0, 150);
        if( GetComputerName( infoBuf, &bufCharCount ) )
        {
            for(i=0; i<150; i++)
            {
                Name[i] = infoBuf[i];
            }
        }
        else
        {
            strcpy(Name, "Unknown_Host_Name");
        }
    #else
        memset(Name, 0, 150);
        gethostname(Name, 150);
    #endif
    strncpy(machineName,Name, 150);
}

What could cause java.lang.reflect.InvocationTargetException?

This will print the exact line of code in the specific method, which when invoked, raised the exception:

try {

    // try code
    ..
    m.invoke(testObject);
    ..

} catch (InvocationTargetException e) {

    // Answer:
    e.getCause().printStackTrace();
} catch (Exception e) {

    // generic exception handling
    e.printStackTrace();
}

How to put a jpg or png image into a button in HTML

You can use some inline CSS like this

<input type="submit" name="submit" style="background: url(images/stack.png); width:100px; height:25px;" />

Should do the magic, also you may wanna do a border:none; to get rid of the standard borders.

Using "like" wildcard in prepared statement

You need to set it in the value itself, not in the prepared statement SQL string.

So, this should do for a prefix-match:

notes = notes
    .replace("!", "!!")
    .replace("%", "!%")
    .replace("_", "!_")
    .replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
        "SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");

or a suffix-match:

pstmt.setString(1, "%" + notes);

or a global match:

pstmt.setString(1, "%" + notes + "%");

Using union and count(*) together in SQL query

select T1.name, count (*)
from (select name from Results 
      union 
      select name from Archive_Results) as T1
group by T1.name order by T1.name

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

I had the same problem, the solution for me is the following.

I had only install the junit.jar file from the web, but this library related with the hacrest-core.jar When I downloaded the hacrest-core.jar file and added it in my project everything works fine.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

I had this same issue and wondered why it didn't happen with a bitbucket repo that was cloned with https. Looking into it a bit I found that the config for the BB repo had a URL that included my username. So I manually edited the config for my GH repo like so and voila, no more username prompt. I'm on Windows.

Edit your_repo_dir/.git/config (remember: .git folder is hidden)

Change:

https://github.com/WEMP/project-slideshow.git

to:

https://*username*@github.com/WEMP/project-slideshow.git

Save the file. Do a git pull to test it.

The proper way to do this is probably by using git bash commands to edit the setting, but editing the file directly didn't seem to be a problem.

Android: failed to convert @drawable/picture into a drawable

file name must contain only abc...xyz 012...789 _ . in Resources folder.

for ex:

my-image.png is False!
MyImage.png is False!
my image.png is False!
...
...

my-xml.xml is False!
MyXml.xml is False!
my xml.xml is False!
...
...

ASP.NET custom error page - Server.GetLastError() is null

Here is my solution..

In Global.aspx:

void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

        //direct user to error page 
        Server.Transfer("~/ErrorPages/Oops.aspx"); 
    }

In Oops.aspx:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadError(Server.GetLastError()); 
    }

    protected void LoadError(Exception objError)
    {
        if (objError != null)
        {
            StringBuilder lasterror = new StringBuilder();

            if (objError.Message != null)
            {
                lasterror.AppendLine("Message:");
                lasterror.AppendLine(objError.Message);
                lasterror.AppendLine();
            }

            if (objError.InnerException != null)
            {
                lasterror.AppendLine("InnerException:");
                lasterror.AppendLine(objError.InnerException.ToString());
                lasterror.AppendLine();
            }

            if (objError.Source != null)
            {
                lasterror.AppendLine("Source:");
                lasterror.AppendLine(objError.Source);
                lasterror.AppendLine();
            }

            if (objError.StackTrace != null)
            {
                lasterror.AppendLine("StackTrace:");
                lasterror.AppendLine(objError.StackTrace);
                lasterror.AppendLine();
            }

            ViewState.Add("LastError", lasterror.ToString());
        }
    }

   protected void btnReportError_Click(object sender, EventArgs e)
    {
        SendEmail();
    }

    public void SendEmail()
    {
        try
        {
            MailMessage msg = new MailMessage("webteam", "webteam");
            StringBuilder body = new StringBuilder();

            body.AppendLine("An unexcepted error has occurred.");
            body.AppendLine();

            body.AppendLine(ViewState["LastError"].ToString());

            msg.Subject = "Error";
            msg.Body = body.ToString();
            msg.IsBodyHtml = false;

            SmtpClient smtp = new SmtpClient("exchangeserver");
            smtp.Send(msg);
        }

        catch (Exception ex)
        {
            lblException.Text = ex.Message;
        }
    }

Dynamically creating keys in a JavaScript associative array

JavaScript does not have associative arrays. It has objects.

The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

It looks like you have an associative array because an Array is also an Object - however you're not actually adding things into the array at all; you're setting fields on the object.

Now that that is cleared up, here is a working solution to your example:

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// Split into key and value
var kvp = cleaned.split('=');

// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.

ModuleNotFoundError: What does it mean __main__ is not a package?

If you have created directory and sub-directory, follow the steps below and please keep in mind all directory must have __init__.py to get it recognized as a directory.

  1. In your script, include import sys and sys.path, you will be able to see all the paths available to Python. You must be able to see your current working directory.

  2. Now import sub-directory and respective module that you want to use using: import subdir.subdir.modulename as abc and now you can use the methods in that module.

enter image description here

As an example, you can see in this screenshot I have one parent directory and two sub-directories and under second sub-directories I have the module CommonFunction. On the right my console shows that after execution of sys.path, I can see my working directory.

Importing Excel files into R, xlsx or xls

This new package looks nice http://cran.r-project.org/web/packages/openxlsx/openxlsx.pdf It doesn't require rJava and is using 'Rcpp' for speed.

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

I was looking for the same behavior using jdbi's BindBeanList and found the syntax is exactly the same as Peter Lang's answer above. In case anybody is running into this question, here's my code:

  @SqlUpdate("INSERT INTO table_one (col_one, col_two) VALUES <beans> ON DUPLICATE KEY UPDATE col_one=VALUES(col_one), col_two=VALUES(col_two)")
void insertBeans(@BindBeanList(value = "beans", propertyNames = {"colOne", "colTwo"}) List<Beans> beans);

One key detail to note is that the propertyName you specify within @BindBeanList annotation is not same as the column name you pass into the VALUES() call on update.

How to vertically align a html radio button to it's label?

there are several way, one i would prefer is using a table in html. you can add two coloum three rows table and place the radio buttons and lable.

<table border="0">

<tr>
  <td><input type="radio" name="sex" value="1"></td>
  <td>radio1</td>

</tr>
<tr>
  <td><input type="radio" name="sex" value="2"></td>
  <td>radio2</td>

</tr>
</table>

How do I setup the InternetExplorerDriver so it works

If you are using RemoteDriver things are different. From http://element34.ca/blog/iedriverserver-webdriver-and-python :

You will need to start the server using a line like

java -jar selenium-server-standalone-2.26.0.jar -Dwebdriver.ie.driver=C:\Temp\IEDriverServer.exe

I found that if the IEDriverServer.exe was in C:\Windows\System32\ or its subfolders, it couldn't be found automatically (even though System32 was in the %PATH%) or explicitly using the -D flag.

Current time formatting with Javascript

function startTime() {
    var today = new Date(),
        h = checkTime(((today.getHours() + 11) % 12 + 1)),
        m = checkTime(today.getMinutes()),
        s = checkTime(today.getSeconds());
    document.getElementById('demo').innerHTML = h + ":" + m + ":" + s;
    t = setTimeout(function () {
        startTime()
    }, 500);
}
startTime();

})();

05:12:00

Delete entire row if cell contains the string X

This is not necessarily a VBA task - This specific task is easiest sollowed with Auto filter.

1.Insert Auto filter (In Excel 2010 click on home-> (Editing) Sort & Filter -> Filter)
2. Filter on the 'Websites' column
3. Mark the 'none' and delete them
4. Clear filter

Working with TIFFs (import, export) in Python using numpy

In case of image stacks, I find it easier to use scikit-image to read, and matplotlib to show or save. I have handled 16-bit TIFF image stacks with the following code.

from skimage import io
import matplotlib.pyplot as plt

# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(mol,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)

Lodash remove duplicates from array

_.unique no longer works for the current version of Lodash as version 4.0.0 has this breaking change. The functionality of _.unique was splitted into _.uniq, _.sortedUniq, _.sortedUniqBy, and _.uniqBy.

You could use _.uniqBy like this:

_.uniqBy(data, function (e) {
  return e.id;
});

...or like this:

_.uniqBy(data, 'id');

Documentation: https://lodash.com/docs#uniqBy


For older versions of Lodash (< 4.0.0 ):

Assuming that the data should be uniqued by each object's id property and your data is stored in data variable, you can use the _.unique() function like this:

_.unique(data, function (e) {
  return e.id;
});

Or simply like this:

_.uniq(data, 'id');

Difference between string and StringBuilder in C#

Major difference:

String is immutable. It means that you can't modify a string at all; the result of modification is a new string. This is not effective if you plan to append to a string.

StringBuilder is mutable. It can be modified in any way and it doesn't require creation of a new instance. When the work is done, ToString() can be called to get the string.

Strings can participate in interning. It means that strings with same contents may have same addresses. StringBuilder can't be interned.

String is the only class that can have a reference literal.

git stash apply version

git Stash list 

List will show all stashed items eg:stash@{0}:,stash@{1}:,..,stash@{n}:

Then select the number n which denotes stash@{n}:

git stash apply n 

for example:

git stash apply 1 

will apply that particular stashed changes to the current branch

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

GET URL parameter in PHP

Use this:

$parameter = $_SERVER['QUERY_STRING'];
echo $parameter;

Or just use:

$parameter = $_GET['link'];
echo $parameter ;

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

Why use HttpClient for Synchronous Connection

If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.

You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.

If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.

The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.

How can I color Python logging output?

Use pyfancy.

Example:

print(pyfancy.RED + "Hello Red!" + pyfancy.END)

Linux command: How to 'find' only text files?

How about this:

$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable'

If you want the filenames without the file types, just add a final sed filter.

$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'

You can filter-out unneeded file types by adding more -e 'type' options to the last grep command.

EDIT:

If your xargs version supports the -d option, the commands above become simpler:

$ grep -rl "needle text" my_folder | xargs -d '\n' -r file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
}

Concatenating null strings in Java

Why must it work?

The JLS 5, Section 15.18.1.1 JLS 8 § 15.18.1 "String Concatenation Operator +", leading to JLS 8, § 5.1.11 "String Conversion", requires this operation to succeed without failure:

...Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

How does it work?

Let's look at the bytecode! The compiler takes your code:

String s = null;
s = s + "hello";
System.out.println(s); // prints "nullhello"

and compiles it into bytecode as if you had instead written this:

String s = null;
s = new StringBuilder(String.valueOf(s)).append("hello").toString();
System.out.println(s); // prints "nullhello"

(You can do so yourself by using javap -c)

The append methods of StringBuilder all handle null just fine. In this case because null is the first argument, String.valueOf() is invoked instead since StringBuilder does not have a constructor that takes any arbitrary reference type.

If you were to have done s = "hello" + s instead, the equivalent code would be:

s = new StringBuilder("hello").append(s).toString();

where in this case the append method takes the null and then delegates it to String.valueOf().

Note: String concatenation is actually one of the rare places where the compiler gets to decide which optimization(s) to perform. As such, the "exact equivalent" code may differ from compiler to compiler. This optimization is allowed by JLS, Section 15.18.1.2:

To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

The compiler I used to determine the "equivalent code" above was Eclipse's compiler, ecj.

When to use dynamic vs. static libraries

If your library is going to be shared among several executables, it often makes sense to make it dynamic to reduce the size of the executables. Otherwise, definitely make it static.

There are several disadvantages of using a dll. There is additional overhead for loading and unloading it. There is also an additional dependency. If you change the dll to make it incompatible with your executalbes, they will stop working. On the other hand, if you change a static library, your compiled executables using the old version will not be affected.

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

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

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

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

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

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

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

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

This topic is very well covered in the documentation.

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

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

Fetch API request timeout?

Using a promise race solution will leave the request hanging and still consume bandwidth in the background and lower the max allowed concurrent request being made while it's still in process.

Instead use the AbortController to actually abort the request, Here is an example

const controller = new AbortController()

// 5 second timeout:
const timeoutId = setTimeout(() => controller.abort(), 5000)

fetch(url, { signal: controller.signal }).then(response => {
  // completed request before timeout fired

  // If you only wanted to timeout the request, not the response, add:
  // clearTimeout(timeoutId)
})

AbortController can be used for other things as well, not only fetch but for readable/writable streams as well. More newer functions (specially promise based ones) will use this more and more. NodeJS have also implemented AbortController into its streams/filesystem as well. I know web bluetooth are looking into it also. Now it can also be used with addEventListener option and have it stop listening when the signal ends

What is the difference between task and thread?

Task is like a operation that you wanna perform , Thread helps to manage those operation through multiple process nodes. task is a lightweight option as Threading can lead to a complex code management
I will suggest to read from MSDN(Best in world) always

Task

Thread

How to write the code for the back button?

In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.

  function redirection()
        {
           <?php $send=$_SERVER['HTTP_REFERER'];?> 
            var redirect_to="<?php echo $send;?>";             
            window.location = redirect_to;

        }

ReactJS Two components communicating

There is such possibility even if they are not Parent - Child relationship - and that's Flux. There is pretty good (for me personally) implementation for that called Alt.JS (with Alt-Container).

For example you can have Sidebar that is dependent on what is set in component Details. Component Sidebar is connected with SidebarActions and SidebarStore, while Details is DetailsActions and DetailsStore.

You could use then AltContainer like that

<AltContainer stores={{
                    SidebarStore: SidebarStore
                }}>
                    <Sidebar/>
</AltContainer>

{this.props.content}

Which would keep stores (well I could use "store" instead of "stores" prop). Now, {this.props.content} CAN BE Details depending on the route. Lets say that /Details redirect us to that view. Details would have for example a checkbox that would change Sidebar element from X to Y if it would be checked.

Technically there is no relationship between them and it would be hard to do without flux. BUT WITH THAT it is rather easy.

Now let's get to DetailsActions. We will create there

class SiteActions {
constructor() {
    this.generateActions(
        'setSiteComponentStore'
    );
}

setSiteComponent(value) {
    this.dispatch({value: value});
}
}

and DetailsStore

class SiteStore {
constructor() {
    this.siteComponents = {
        Prop: true
    };

    this.bindListeners({
        setSiteComponent: SidebarActions.COMPONENT_STATUS_CHANGED
    })
}

setSiteComponent(data) {
    this.siteComponents.Prop = data.value;
}
}

And now, this is the place where magic begin.

As You can see there is bindListener to SidebarActions.ComponentStatusChanged which will be used IF setSiteComponent will be used.

now in SidebarActions

    componentStatusChanged(value){
    this.dispatch({value: value});
}

We have such thing. It will dispatch that object on call. And it will be called if setSiteComponent in store will be used (that you can use in component for example during onChange on Button ot whatever)

Now in SidebarStore we will have

    constructor() {
    this.structures = [];

    this.bindListeners({
        componentStatusChanged: SidebarActions.COMPONENT_STATUS_CHANGED
    })
}

    componentStatusChanged(data) {
    this.waitFor(DetailsStore);

    _.findWhere(this.structures[0].elem, {title: 'Example'}).enabled = data.value;
}

Now here you can see, that it will wait for DetailsStore. What does it mean? more or less it means that this method need to wait for DetailsStoreto update before it can update itself.

tl;dr One Store is listening on methods in a store, and will trigger an action from component action, which will update its own store.

I hope it can help you somehow.

How do I get some variable from another class in Java?

I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.

To run the code in setNum you have to call it. If you don't call it, the default value is 0.

checking memory_limit in PHP

Here is another simpler way to check that.

$memory_limit = return_bytes(ini_get('memory_limit'));
if ($memory_limit < (64 * 1024 * 1024)) {
    // Memory insufficient      
}

/**
* Converts shorthand memory notation value to bytes
* From http://php.net/manual/en/function.ini-get.php
*
* @param $val Memory size shorthand notation string
*/
function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    $val = substr($val, 0, -1);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}

MySQL: How to set the Primary Key on phpMyAdmin?

You can't set the field having data-type "text". Only because of that thing you are getting this error. Try to change the data-type with int

Where can I download Eclipse Android bundle?

The Android Developer pages still state how you can download and use the ADT plugin for Eclipse:

  1. Start Eclipse, then select Help > Install New Software.
  2. Click Add, in the top-right corner.
  3. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location: https://dl-ssl.google.com/android/eclipse/
  4. Click OK.
  5. In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
  6. In the next window, you'll see a list of the tools to be downloaded. Click Next.
  7. Read and accept the license agreements, then click Finish. If you get a security warning saying that the authenticity or validity of the software can't be established, click OK
  8. When the installation completes, restart Eclipse.

Links for the Eclipse ADT Bundle (found using Archive.org's WayBackMachine) I don't know how future-proof these links are. They all worked on February 27th, 2017.


Update (2015-06-29): Google will end development and official support for ADT in Eclipse at the end of this year and recommends switching to Android Studio.

Best way to detect when a user leaves a web page?

Mozilla Developer Network has a nice description and example of onbeforeunload.

If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):

window.addEventListener('beforeunload', function(e) {
  var myPageIsDirty = ...; //you implement this logic...
  if(myPageIsDirty) {
    //following two lines will cause the browser to ask the user if they
    //want to leave. The text of this dialog is controlled by the browser.
    e.preventDefault(); //per the standard
    e.returnValue = ''; //required for Chrome
  }
  //else: user is allowed to leave without a warning dialog
});

How to get jQuery to wait until an effect is finished?

if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.

newline in <td title="">

The jquery colortip plugin also supports <br> tags in the title attribute, you might want to look into that one.

Best way to write to the console in PowerShell

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

The important thing to note here is that the mime type is not the same as the file extension. Sometimes, however, they have the same value.

https://www.iana.org/assignments/media-types/media-types.xhtml includes a list of registered Mime types, though there is nothing stopping you from making up your own, as long as you are at both the sending and the receiving end. Here is where Microsoft comes in to the picture.

Where there is a lot of confusion is the fact that operating systems have their own way of identifying file types by using the tail end of the file name, referred to as the extension. In modern operating systems, the whole name is one long string, but in more primitive operating systems, it is treated as a separate attribute.

The OS which caused the confusion is MSDOS, which had limited the extension to 3 characters. This limitation is inherited to this day in devices, such as SD cards, which still store data in the same way.

One side effect of this limitation is that some file extensions, such as .gif match their Mime Type, image/gif, while others are compromised. This includes image/jpeg whose extension is shortened to .jpg. Even in modern Windows, where the limitation is lifted, Microsoft never let the past go, and so the file extension is still the shortened version.

Given that that:

  1. File Extensions are not File Types
  2. Historically, some operating systems had serious file name limitations
  3. Some operating systems will just go ahead and make up their own rules

The short answer is:

  • Technically, there is no such thing as image/jpg, so the answer is that it is not the same as image/jpeg
  • That won’t stop some operating systems and software from treating it as if it is the same

While we’re at it …

Legacy versions of Internet Explorer took the liberty of uploading jpeg files with the Mime Type of image/pjpeg, which, of course, just means more work for everybody else. They also uploaded png files as image/x-png.

Inverse of matrix in R

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

Getter and Setter declaration in .NET

Just to clarify, in your 3rd example _myProperty isn't actually a property. It's a field with get and set methods (and as has already been mentioned the get and set methods should specify return types).

In C# the 3rd method should be avoided in most situations. You'd only really use it if the type you wanted to return was an array, or if the get method did a lot of work rather than just returning a value. The latter isn't really necessary but for the purpose of clarity a property's get method that does a lot of work is misleading.

How do I restrict an input to only accept numbers?

DECIMAL

directive('decimal', function() {
                return {
                    require: 'ngModel',
                    restrict: 'A',
                    link: function(scope, element, attr, ctrl) {
                        function inputValue(val) {
                            if (val) {
                                var digits = val.replace(/[^0-9.]/g, '');

                                if (digits.split('.').length > 2) {
                                    digits = digits.substring(0, digits.length - 1);
                                }

                                if (digits !== val) {
                                    ctrl.$setViewValue(digits);
                                    ctrl.$render();
                                }
                                return parseFloat(digits);
                            }
                            return "";
                        }
                        ctrl.$parsers.push(inputValue);
                    }
                };
            });

DIGITS

directive('entero', function() {
            return {
                require: 'ngModel',
                restrict: 'A',
                link: function(scope, element, attr, ctrl) {
                    function inputValue(val) {
                        if (val) {
                            var value = val + ''; //convert to string
                            var digits = value.replace(/[^0-9]/g, '');

                            if (digits !== value) {
                                ctrl.$setViewValue(digits);
                                ctrl.$render();
                            }
                            return parseInt(digits);
                        }
                        return "";
                    }
                    ctrl.$parsers.push(inputValue);
                }
            };
        });

angular directives for validate numbers

How to scroll to top of the page in AngularJS?

Ideally we should do it from either controller or directive as per applicable. Use $anchorScroll, $location as dependency injection.

Then call this two method as

$location.hash('scrollToDivID');
$anchorScroll();

Here scrollToDivID is the id where you want to scroll.

Assumed you want to navigate to a error message div as

<div id='scrollToDivID'>Your Error Message</div>

For more information please see this documentation

How can I check MySQL engine type for a specific table?

If you're using MySQL Workbench, right-click a table and select alter table.

In that window you can see your table Engine and also change it.

How can I concatenate a string and a number in Python?

You would have to convert the int into a string.

# This program calculates a workers gross pay

hours = float(raw_input("Enter hours worked: \n"))

rate = float(raw_input("Enter your hourly rate of pay: \n"))

gross = hours * rate

print "Your gross pay for working " +str(hours)+ " at a rate of " + str(rate) + " hourly is $"  + str(gross)

Convert data.frame column format from character to factor

Unless you need to identify the columns automatically, I found this to be the simplest solution:

df$name <- as.factor(df$name)

This makes column name in dataframe df a factor.

Check if a user has scrolled to the bottom

Google Chrome gives the full height of the page if you call $(window).height()

Instead, use window.innerHeight to retrieve the height of your window. Necessary check should be:

if($(window).scrollTop() + window.innerHeight > $(document).height() - 50) {
    console.log("reached bottom!");
}

How to change Android version and code version number?

Press Ctrl+Alt+Shift+S in android studio or go to File > Project Structure... Select app on left side and select falvors tab on right side on default config change version code , name and etc... enter image description here

Sending command line arguments to npm script

You could also do that:

In package.json:

"scripts": {
    "cool": "./cool.js"
}

In cool.js:

 console.log({ myVar: process.env.npm_config_myVar });

In CLI:

npm --myVar=something run-script cool

Should output:

{ myVar: 'something' }

Update: Using npm 3.10.3, it appears that it lowercases the process.env.npm_config_ variables? I'm also using better-npm-run, so I'm not sure if this is vanilla default behavior or not, but this answer is working. Instead of process.env.npm_config_myVar, try process.env.npm_config_myvar

JavaScript open in a new window, not tab

I just tried this with IE (11) and Chrome (54.0.2794.1 canary SyzyASan):

window.open(url, "_blank", "x=y")

... and it opened in a new window.

Which means that Clint pachl had it right when he said that providing any one parameter will cause the new window to open.

-- and apparently it doesn't have to be a legitimate parameter!

(YMMV - as I said, I only tested it in two places...and the next upgrade might invalidate the results, any way)

ETA: I just noticed, though - in IE, the window has no decorations.

Equivalent to 'app.config' for a library (DLL)

I am currently creating plugins for a retail software brand, which are actually .net class libraries. As a requirement, each plugin needs to be configured using a config file. After a bit of research and testing, I compiled the following class. It does the job flawlessly. Note that I haven't implemented local exception handling in my case because, I catch exceptions at a higher level.

Some tweaking maybe needed to get the decimal point right, in case of decimals and doubles, but it works fine for my CultureInfo...

static class Settings
{
    static UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
    static Configuration myDllConfig = ConfigurationManager.OpenExeConfiguration(uri.Path);
    static AppSettingsSection AppSettings = (AppSettingsSection)myDllConfig.GetSection("appSettings");
    static NumberFormatInfo nfi = new NumberFormatInfo() 
    { 
        NumberGroupSeparator = "", 
        CurrencyDecimalSeparator = "." 
    };

    public static T Setting<T>(string name)
    {
        return (T)Convert.ChangeType(AppSettings.Settings[name].Value, typeof(T), nfi);
    }
}

App.Config file sample

<add key="Enabled" value="true" />
<add key="ExportPath" value="c:\" />
<add key="Seconds" value="25" />
<add key="Ratio" value="0.14" />

Usage:

  somebooleanvar = Settings.Setting<bool>("Enabled");
  somestringlvar = Settings.Setting<string>("ExportPath");
  someintvar =     Settings.Setting<int>("Seconds");
  somedoublevar =  Settings.Setting<double>("Ratio");

Credits to Shadow Wizard & MattC

How to prepend a string to a column value in MySQL?

  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column1) where 1
  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column2) where 1
  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column2, 'newtring2') where 1

We can concat same column or also other column of the table.

Node.js - Maximum call stack size exceeded

If you don't want to implement your own wrapper, you can use a queue system, e.g. async.queue, queue.

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

Check that you have both ngModel and name attributes in your select. Also Select is a form component and not the entire form so more logical declaration of local reference will be:-

<div class="form-group">
    <label for="actionType">Action Type</label>
    <select
            ngControl="actionType" 
      ===>  #actionType="ngModel"
            ngModel    // You can go with 1 or 2 way binding as well
            name="actionType"
            id="actionType" 
            class="form-control" 
            required>
            <option value=""></option>
            <option *ngFor="let actionType of actionTypes" value="{{ actionType.label }}">
                {{ actionType.label }}
            </option>
        </select> 
    </div>

One more Important thing is make sure you import either FormsModule in the case of template driven approach or ReactiveFormsModule in the case of Reactive approach. Or you can import both which is also totally fine.

Using ExcelDataReader to read Excel data starting from a particular cell

To be more clear, I will begin at the beginning.

I will rely on the sample code found in https://github.com/ExcelDataReader/ExcelDataReader, but with some modifications to avoid inconveniences.

The following code detects the file format, either xls or xlsx.

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader;

//1. Reading Excel file
if (Path.GetExtension(filePath).ToUpper() == ".XLS")
{
    //1.1 Reading from a binary Excel file ('97-2003 format; *.xls)
    excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else
{
    //1.2 Reading from a OpenXml Excel file (2007 format; *.xlsx)
    excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}

//2. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();

//3. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = false;

Now we can access the file contents in a more convenient way. I use DataTable for this. The following is an example to access a specific cell, and print its value in the console:

DataTable dt = result.Tables[0];
Console.WriteLine(dt.Rows[rowPosition][columnPosition]);

If you do not want to do a DataTable, you can do the same as follows:

Console.WriteLine(result.Tables[0].Rows[rowPosition][columnPosition]);

It is important not try to read beyond the limits of the table, for this you can see the number of rows and columns as follows:

Console.WriteLine(result.Tables[0].Rows.Count);
Console.WriteLine(result.Tables[0].Columns.Count);

Finally, when you're done, you should close the reader and free resources:

//5. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

I hope you find it useful.

(I understand that the question is old, but I make this contribution to enhance the knowledge base, because there is little material about particular implementations of this library).

NuGet auto package restore does not work with MSBuild

UPDATED with latest official NuGet documentation as of v3.3.0

Package Restore Approaches

NuGet offers three approaches to using package restore.


Automatic Package Restore is the NuGet team's recommended approach to Package Restore within Visual Studio, and it was introduced in NuGet 2.7. Beginning with NuGet 2.7, the NuGet Visual Studio extension integrates into Visual Studio's build events and restores missing packages when a build begins. This feature is enabled by default, but developers can opt out if desired.


Here's how it works:

  1. On project or solution build, Visual Studio raises an event that a build is beginning within the solution.
  2. NuGet responds to this event and checks for packages.config files included in the solution.
  3. For each packages.config file found, its packages are enumerated and Checked for exists in the solution's packages folder.
  4. Any missing packages are downloaded from the user's configured (and enabled) package sources, respecting the order of the package sources.
  5. As packages are downloaded, they are unzipped into the solution's packages folder.

If you have Nuget 2.7+ installed; it's important to pick one method for > managing Automatic Package Restore in Visual Studio.

Two methods are available:

  1. (Nuget 2.7+): Visual Studio -> Tools -> Package Manager -> Package Manager Settings -> Enable Automatic Package Restore
  2. (Nuget 2.6 and below) Right clicking on a solution and clicking "Enable Package Restore for this solution".


Command-Line Package Restore is required when building a solution from the command-line; it was introduced in early versions of NuGet, but was improved in NuGet 2.7.

nuget.exe restore contoso.sln

The MSBuild-integrated package restore approach is the original Package Restore implementation and though it continues to work in many scenarios, it does not cover the full set of scenarios addressed by the other two approaches.

How to remove a row from JTable?

In order to remove a row from a JTable, you need to remove the target row from the underlying TableModel. If, for instance, your TableModel is an instance of DefaultTableModel, you can remove a row by doing the following:

((DefaultTableModel)myJTable.getModel()).removeRow(rowToRemove);

SonarQube Exclude a directory

This worked for me:

sonar.exclusions=src/**/wwwroot/**/*.js,src/**/wwwroot/**/*.css

It excludes any .js and .css files under any of the sub directories of a folder "wwwroot" appearing as one of the sub directories of the "src" folder (project root).

Validating an XML against referenced XSD in C#

personally I favor validating without a callback:

public bool ValidateSchema(string xmlPath, string xsdPath)
{
    XmlDocument xml = new XmlDocument();
    xml.Load(xmlPath);

    xml.Schemas.Add(null, xsdPath);

    try
    {
        xml.Validate(null);
    }
    catch (XmlSchemaValidationException)
    {
        return false;
    }
    return true;
}

(see Timiz0r's post in Synchronous XML Schema Validation? .NET 3.5)

Git ignore local file changes

git pull wants you to either remove or save your current work so that the merge it triggers doesn't cause conflicts with your uncommitted work. Note that you should only need to remove/save untracked files if the changes you're pulling create files in the same locations as your local uncommitted files.

Remove your uncommitted changes

Tracked files

git checkout -f

Untracked files

git clean -fd

Save your changes for later

Tracked files

git stash

Tracked files and untracked files

git stash -u

Reapply your latest stash after git pull:

git stash pop

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

C error: undefined reference to function, but it IS defined

Add the "extern" keyword to the function definitions in point.h

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

Swift 3

extension Date {
    
    func toString(template: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: NSLocale.current)
        return formatter.string(from: self)
    }
    
}

Usage

let now = Date()
let nowStr0 = now.toString(template: "EEEEdMMM") // Tuesday, May 9
let nowStr1 = now.toString(template: "yyyy-MM-dd") // 2017-05-09
let nowStr2 = now.toString(template: "HH:mm:ss") // 17:47:09

Play with template to match your needs. Examples and doc here to help you build the template you need.

Note

You may want to cache your DateFormatter if you plan to use it in TableView for instance. To give an idea, looping over 1000 dates took me 0.5 sec using the above toString(template: String) function, compared to 0.05 sec using myFormatter.string(from: Date).

Serializing a list to JSON

public static string JSONSerialize<T>(T obj)
        {
            string retVal = String.Empty;
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(ms, obj);
                var byteArray = ms.ToArray();
                retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
            }
            return retVal;
        }

Check if a value exists in ArrayList

Better to use a HashSet than an ArrayList when you are checking for existence of a value. Java docs for HashSet says: "This class offers constant time performance for the basic operations (add, remove, contains and size)"

ArrayList.contains() might have to iterate the whole list to find the instance you are looking for.

How to add onload event to a div element

Avoid using any interval based methods and use MutationObserver targeting a parent div of dynamically loaded div for better efficiency.

Here's the simple snippet:

HTML:

<div class="parent-static-div">
  <div class="dynamic-loaded-div">
    this div is loaded after DOM ready event
  </div>
</div>

JS:

var observer = new MutationObserver(function (mutationList, obsrvr) {
  var div_to_check = document.querySelector(".dynamic-loaded-div"); //get div by class
  // var div_to_check = document.getElementById('div-id'); //get div by id

  console.log("checking for div...");
  if (div_to_check) {
    console.log("div is loaded now"); // DO YOUR STUFF!
    obsrvr.disconnect(); // stop observing
    return;
  }
});

var parentElement = document.querySelector("parent-static-div"); // use parent div which is already present in DOM to maximise efficiency
// var parentElement = document // if not sure about parent div then just use whole 'document'

// start observing for dynamic div
observer.observe(parentElement, {
  // for properties details: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
  childList: true,
  subtree: true,
});

What is dtype('O'), in pandas?

It means "a python object", i.e. not one of the builtin scalar types supported by numpy.

np.array([object()]).dtype
=> dtype('O')

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

Why does this error occur?

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

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

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

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

So when you write:

var element = array[5];

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

Typically, you would loop over an array like this:

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

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

This, however, will throw an exception:

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

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

How other collections work

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

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

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

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

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

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

Make Axios send cookies in its requests automatically

How do I make Axios send cookies in requests automatically?

set axios.defaults.withCredentials = true;

or for some specific request you can use axios.get(url,{withCredentials:true})

this will give CORS error if your 'Access-Control-Allow-Origin' is set to wildcard(*). Therefore make sure to specify the url of origin of your request

for ex: if your front-end which makes the request runs on localhost:3000 , then set the response header as

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

also set

res.setHeader('Access-Control-Allow-Credentials',true);

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How to set cornerRadius for only top-left and top-right corner of a UIView?

All of the answers already given are really good and valid (especially Yunus idea of using the mask property).

However I needed something a little more complex because my layer could often change sizes which mean I needed to call that masking logic every time and this was a little bit annoying.

I used swift extensions and computed properties to build a real cornerRadii property which takes care of auto updating the mask when layer is layed out.

This was achieved using Peter Steinberg great Aspects library for swizzling.

Full code is here:

extension CALayer {
  // This will hold the keys for the runtime property associations
  private struct AssociationKey {
    static var CornerRect:Int8 = 1    // for the UIRectCorner argument
    static var CornerRadius:Int8 = 2  // for the radius argument
  }

  // new computed property on CALayer
  // You send the corners you want to round (ex. [.TopLeft, .BottomLeft])
  // and the radius at which you want the corners to be round
  var cornerRadii:(corners: UIRectCorner, radius:CGFloat) {
    get {
      let number = objc_getAssociatedObject(self, &AssociationKey.CornerRect)  as? NSNumber ?? 0
      let radius = objc_getAssociatedObject(self, &AssociationKey.CornerRadius)  as? NSNumber ?? 0
      return (corners: UIRectCorner(rawValue: number.unsignedLongValue), radius: CGFloat(radius.floatValue))
    }
    set (v) {
      let radius = v.radius
      let closure:((Void)->Void) = {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: v.corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.CGPath
        self.mask = mask
      }
      let block: @convention(block) Void -> Void = closure
      let objectBlock = unsafeBitCast(block, AnyObject.self)
      objc_setAssociatedObject(self, &AssociationKey.CornerRect, NSNumber(unsignedLong: v.corners.rawValue), .OBJC_ASSOCIATION_RETAIN)
      objc_setAssociatedObject(self, &AssociationKey.CornerRadius, NSNumber(float: Float(v.radius)), .OBJC_ASSOCIATION_RETAIN)
      do { try aspect_hookSelector("layoutSublayers", withOptions: .PositionAfter, usingBlock: objectBlock) }
      catch _ { }
    }
  }
}

I wrote a simple blog post explaining this.

Use ASP.NET MVC validation with jquery ajax?

What you should do is to serialize your form data and send it to the controller action. ASP.NET MVC will bind the form data to the EditPostViewModel object( your action method parameter), using MVC model binding feature.

You can validate your form at client side and if everything is fine, send the data to server. The valid() method will come in handy.

$(function () {

    $("#yourSubmitButtonID").click(function (e) {

        e.preventDefault();
        var _this = $(this);
        var _form = _this.closest("form");

        var isvalid = _form .valid();  // Tells whether the form is valid

        if (isvalid)
        {           
           $.post(_form.attr("action"), _form.serialize(), function (data) {
              //check the result and do whatever you want
           })
        }

    });

});

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

In my case, the issue was a misconstrued list of command-line arguments. I was doing this in my deployment file:

...
args:
  - "--foo 10"
  - "--bar 100"

Instead of the correct approach:

...
args:
  - "--foo"
  - "10"
  - "--bar"
  - "100"

"git rebase origin" vs."git rebase origin/master"

git rebase origin means "rebase from the tracking branch of origin", while git rebase origin/master means "rebase from the branch master of origin"

You must have a tracking branch in ~/Desktop/test, which means that git rebase origin knows which branch of origin to rebase with. If no tracking branch exists (in the case of ~/Desktop/fallstudie), git doesn't know which branch of origin it must take, and fails.

To fix this, you can make the branch track origin/master with:

git branch --set-upstream-to=origin/master 

Or, if master isn't the currently checked-out branch:

git branch --set-upstream-to=origin/master master

Changing the highlight color when selecting text in an HTML text input

Thanks for the links, but it does seem as if the actual text highlighting just isn't exposed.

As far as the actual issue at hand, I ended up opting for a different approach by eliminating the need for a text input altogether and using innerHTML with some JavaScript. Not only does it get around the text highlighting, it actually looks much cleaner.

This granular of a tweak to an HTML form control is just another good argument for eliminating form controls altogether. Haha!

GroupBy pandas DataFrame and select most common value

The problem here is the performance, if you have a lot of rows it will be a problem.

If it is your case, please try with this:

import pandas as pd

source = pd.DataFrame({'Country' : ['USA', 'USA', 'Russia','USA'], 
              'City' : ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
              'Short_name' : ['NY','New','Spb','NY']})

source.groupby(['Country','City']).agg(lambda x:x.value_counts().index[0])

source.groupby(['Country','City']).Short_name.value_counts().groupby['Country','City']).first()

What is Turing Complete?

I think the importance of the concept "Turing Complete" is in the the ability to identify a computing machine (not necessarily a mechanical/electrical "computer") that can have its processes be deconstructed into "simple" instructions, composed of simpler and simpler instructions, that a Universal machine could interpret and then execute.

I highly recommend The Annotated Turing

@Mark i think what you are explaining is a mix between the description of the Universal Turing Machine and Turing Complete.

Something that is Turing Complete, in a practical sense, would be a machine/process/computation able to be written and represented as a program, to be executed by a Universal Machine (a desktop computer). Though it doesn't take consideration for time or storage, as mentioned by others.

How can I output UTF-8 from Perl?

TMTOWTDI, chose the method that best fits how you work. I use the environment method so I don't have to think about it.

In the environment:

export PERL_UNICODE=SDL

on the command line:

perl -CSDL -le 'print "\x{1815}"';

or with binmode:

binmode(STDOUT, ":utf8");          #treat as if it is UTF-8
binmode(STDIN, ":encoding(utf8)"); #actually check if it is UTF-8

or with PerlIO:

open my $fh, ">:utf8", $filename
    or die "could not open $filename: $!\n";

open my $fh, "<:encoding(utf-8)", $filename
    or die "could not open $filename: $!\n";

or with the open pragma:

use open ":encoding(utf8)";
use open IN => ":encoding(utf8)", OUT => ":utf8";

How to convert PDF files to images

As for 2018 there is still not a simple answer to the question of how to convert a PDF document to an image in C#; many libraries use Ghostscript licensed under AGPL and in most cases an expensive commercial license is required for production use.

A good alternative might be using the popular 'pdftoppm' utility which has a GPL license; it can be used from C# as command line tool executed with System.Diagnostics.Process. Popular tools are well known in the Linux world, but a windows build is also available.

If you don't want to integrate pdftoppm by yourself, you can use my PdfRenderer popular wrapper (supports both classic .NET Framework and .NET Core) - it is not free, but pricing is very affordable.

Automatic creation date for Django model form objects?

You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

Find character position and update file name

If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.

 $text = "asdfNAME=PC123456<>Diweursejsfdjiwr"

asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456

 $text.IndexOf("E=")

7 - this is the "FIND" command for Powershell

 $text.substring(10,5)

C1234 - this is the "MID" command for Powershell

 $text.substring($text.IndexOf("E=")+2,8)

PC123456 - tada it has found and cut our text

-RavonTUS

How can I get the line number which threw exception?

Working for me:

var st = new StackTrace(e, true);

// Get the bottom stack frame
var frame = st.GetFrame(st.FrameCount - 1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
var method = frame.GetMethod().ReflectedType.FullName;
var path = frame.GetFileName();

Getting attributes of Enum's value

This is how I solved it without using custom helpers or extensions with .NET core 3.1.

Class

public enum YourEnum
{
    [Display(Name = "Suryoye means Arameans")]
    SURYOYE = 0,
    [Display(Name = "Oromoye means Syriacs")]
    OROMOYE = 1,
}

Razor

@using Enumerations

foreach (var name in Html.GetEnumSelectList(typeof(YourEnum)))
{
    <h1>@name.Text</h1>
}

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

Is there a TRY CATCH command in Bash

I've developed an almost flawless try & catch implementation in bash, that allows you to write code like:

try 
    echo 'Hello'
    false
    echo 'This will not be displayed'

catch 
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"

You can even nest the try-catch blocks inside themselves!

try {
    echo 'Hello'

    try {
        echo 'Nested Hello'
        false
        echo 'This will not execute'
    } catch {
        echo "Nested Caught (@ $__EXCEPTION_LINE__)"
    }

    false
    echo 'This will not execute too'

} catch {
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
}

The code is a part of my bash boilerplate/framework. It further extends the idea of try & catch with things like error handling with backtrace and exceptions (plus some other nice features).

Here's the code that's responsible just for try & catch:

set -o pipefail
shopt -s expand_aliases
declare -ig __oo__insideTryCatch=0

# if try-catch is nested, then set +e before so the parent handler doesn't catch us
alias try="[[ \$__oo__insideTryCatch -gt 0 ]] && set +e;
           __oo__insideTryCatch+=1; ( set -e;
           trap \"Exception.Capture \${LINENO}; \" ERR;"
alias catch=" ); Exception.Extract \$? || "

Exception.Capture() {
    local script="${BASH_SOURCE[1]#./}"

    if [[ ! -f /tmp/stored_exception_source ]]; then
        echo "$script" > /tmp/stored_exception_source
    fi
    if [[ ! -f /tmp/stored_exception_line ]]; then
        echo "$1" > /tmp/stored_exception_line
    fi
    return 0
}

Exception.Extract() {
    if [[ $__oo__insideTryCatch -gt 1 ]]
    then
        set -e
    fi

    __oo__insideTryCatch+=-1

    __EXCEPTION_CATCH__=( $(Exception.GetLastException) )

    local retVal=$1
    if [[ $retVal -gt 0 ]]
    then
        # BACKWARDS COMPATIBILE WAY:
        # export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-1)]}"
        # export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-2)]}"
        export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[-1]}"
        export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[-2]}"
        export __EXCEPTION__="${__EXCEPTION_CATCH__[@]:0:(${#__EXCEPTION_CATCH__[@]} - 2)}"
        return 1 # so that we may continue with a "catch"
    fi
}

Exception.GetLastException() {
    if [[ -f /tmp/stored_exception ]] && [[ -f /tmp/stored_exception_line ]] && [[ -f /tmp/stored_exception_source ]]
    then
        cat /tmp/stored_exception
        cat /tmp/stored_exception_line
        cat /tmp/stored_exception_source
    else
        echo -e " \n${BASH_LINENO[1]}\n${BASH_SOURCE[2]#./}"
    fi

    rm -f /tmp/stored_exception /tmp/stored_exception_line /tmp/stored_exception_source
    return 0
}

Feel free to use, fork and contribute - it's on GitHub.

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

" app-release.apk" how to change this default generated apk name

You might get the error with the latest android gradle plugin (3.0):

Cannot set the value of read-only property 'outputFile'

According to the migration guide, we should use the following approach now:

applicationVariants.all { variant ->
    variant.outputs.all {
        outputFileName = "${applicationName}_${variant.buildType.name}_${defaultConfig.versionName}.apk"
    }
}

Note 2 main changes here:

  1. all is used now instead of each to iterate over the variant outputs.
  2. outputFileName property is used instead of mutating a file reference.

header('HTTP/1.0 404 Not Found'); not doing anything

Another reason may be if you add any html tag before this redirect. Look carefully, you may left DOCTYPE or any html comment before this line.

Can grep show only words that match search pattern?

You could translate spaces to newlines and then grep, e.g.:

cat * | tr ' ' '\n' | grep th

Remove everything after a certain character

var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);

Sample here

I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).

Updated code to account for no '?':

var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);

Sample here

how to count the spaces in a java string?

Here's a different way of looking at it, and it's a simple one-liner:

int spaces = s.replaceAll("[^ ]", "").length();

This works by effectively removing all non-spaces then taking the length of what’s left (the spaces).

You might want to add a null check:

int spaces = s == null ? 0 : s.replaceAll("[^ ]", "").length();

Java 8 update

You can use a stream too:

int spaces = s.chars().filter(c -> c == (int)' ').count();

npm install Error: rollbackFailedOptional

    # first this
    > npm config rm proxy
    > npm config rm https-proxy

    # then this
    > npm config set registry https://registry.npmjs.org/

solved my problem.

Again: Be sure to check whether you have internet connected properly.

Converting a number with comma as decimal point to float

Might look excessive but will convert any given format no mater the locale:

function normalizeDecimal($val, int $precision = 4): string
{
    $input = str_replace(' ', '', $val);
    $number = str_replace(',', '.', $input);
    if (strpos($number, '.')) {
        $groups = explode('.', str_replace(',', '.', $number));
        $lastGroup = array_pop($groups);
        $number = implode('', $groups) . '.' . $lastGroup;
    }
    return bcadd($number, 0, $precision);
}

Output:

.12           -> 0.1200
123           -> 123.0000
123.91        -> 12345678.9100
123 456 78.91 -> 12345678.9100
123,456,78.91 -> 12345678.9100
123.456.78,91 -> 12345678.9100
123 456 78,91 -> 12345678.9100

error opening trace file: No such file or directory (2)

Write all your code below this 2 lines:-

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

It worked for me without re-installing again.

Clear and reset form input fields

state={ 
  name:"",
  email:""
}

handalSubmit = () => {
  after api call 
  let resetFrom = {}
  fetch('url')
  .then(function(response) {
    if(response.success){
       resetFrom{
          name:"",
          email:""
      }
    }
  })
  this.setState({...resetFrom})
}

How can I read user input from the console?

        double a,b;
        Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
        try
        {
            a = Convert.ToDouble(Console.ReadLine());
            b = a * Math.PI;
            Console.WriteLine("Sonuç " + b); 
        }
        catch (Exception)
        {
            Console.WriteLine("dönüstürme hatasi");
            throw;
        }

Select from multiple tables without a join?

The UNION ALL operator may be what you are looking for.

With this operator, you can concatenate the resultsets from multiple queries together, preserving all of the rows from each. Note that a UNION operator (without the ALL keyword) will eliminate any "duplicate" rows which exist in the resultset. The UNION ALL operator preserves all of the rows from each query (and will likely perform better since it doesn't have the overhead of performing the duplicate check and removal operation).

The number of columns and data type of each column must match in each of the queries. If one of the queries has more columns than the other, we sometimes include dummy expressions in the other query to make the columns and datatypes "match". Often, it's helpful to include an expression (an extra column) in the SELECT list of each query that returns a literal, to reveal which of the queries was the "source" of the row.

SELECT 'q1' AS source, a, b, c, d FROM t1 WHERE ...
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2 JOIN t3 ON ...
UNION ALL
SELECT 'q3', '1', '2', buckle, my_shoe FROM t4

You can wrap a query like this in a set of parenthesis, and use it as an inline view (or "derived table", in MySQL lingo), so that you can perform aggregate operations on all of the rows.

SELECT t.a
     , SUM(t.b)
     , AVG(t.c)
  FROM (
         SELECT 'q1' AS source, a, b, c, d FROM t1
          UNION ALL
         SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2
       ) t
 GROUP BY t.a
 ORDER BY t.a

How to overwrite the output directory in spark

  val jobName = "WordCount";
  //overwrite the output directory in spark  set("spark.hadoop.validateOutputSpecs", "false")
  val conf = new 
  SparkConf().setAppName(jobName).set("spark.hadoop.validateOutputSpecs", "false");
  val sc = new SparkContext(conf)

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

How can I get the error message for the mail() function?

sending mail in php is not a one-step process. mail() returns true/false, but even if it returns true, it doesn't mean the message is going to be sent. all mail() does is add the message to the queue(using sendmail or whatever you set in php.ini)

there is no reliable way to check if the message has been sent in php. you will have to look through the mail server logs.

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

Use :

<select onchange="myFunction()">

    function myFunction() {
        document.querySelectorAll("input[type=submit]")[0].click();
    }

Why does cURL return error "(23) Failed writing body"?

I encountered the same problem when doing:

curl -L https://packagecloud.io/golang-migrate/migrate/gpgkey | apt-key add -

The above query needs to be executed using root privileges.

Writing it in following way solved the issue for me:

curl -L https://packagecloud.io/golang-migrate/migrate/gpgkey | sudo apt-key add -

If you write sudo before curl, you will get the Failed writing body error.

How do you hide the Address bar in Google Chrome for Chrome Apps?

Instructions as of Dec 2018:

  1. Visit the site you want in Chrome
  2. From menu select "More tools" > "Create shortcut..."
  3. From apps (can visit chrome://apps/), right click site then enable "Open as window"

Now when you open the shortcut it will open in a window without toolbar.

not-null property references a null or transient value

I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)

How to update an "array of objects" with Firestore?

addToCart(docId: string, prodId: string): Promise<void> {
    return this.baseAngularFirestore.collection('carts').doc(docId).update({
        products:
        firestore.FieldValue.arrayUnion({
            productId: prodId,
            qty: 1
        }),
    });
}

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

LINQ - Left Join, Group By, and Count

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.ParentId into grouped
select new { ParentId = grouped.Key, Count = grouped.Count(t=>t.ChildId != null) }

Do conditional INSERT with SQL?

I dont know about SmallSQL, but this works for MSSQL:

IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
    UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
    INSERT INTO Table1 VALUES (...)

Based on the where-condition, this updates the row if it exists, else it will insert a new one.

I hope that's what you were looking for.

Adding a simple spacer to twitter bootstrap

You can add a class to each of your .row divs to add some space in between them like so:

.spacer {
    margin-top: 40px; /* define margin as you see fit */
}

You can then use it like so:

<div class="row spacer">
   <div class="span4">...</div>
   <div class="span4">...</div>
   <div class="span4">...</div>
</div>

<div class="row spacer">
   <div class="span4">...</div>
   <div class="span4">...</div>
   <div class="span4">...</div>
</div>

When I catch an exception, how do I get the type, file, and line number?

You could achieve this without having to import traceback:

try:
    func1()
except Exception as ex:
    trace = []
    tb = ex.__traceback__
    while tb is not None:
        trace.append({
            "filename": tb.tb_frame.f_code.co_filename,
            "name": tb.tb_frame.f_code.co_name,
            "lineno": tb.tb_lineno
        })
        tb = tb.tb_next
    print(str({
        'type': type(ex).__name__,
        'message': str(ex),
        'trace': trace
    }))

Output:

{

  'type': 'ZeroDivisionError',
  'message': 'division by zero',
  'trace': [
    {
      'filename': '/var/playground/main.py',
      'name': '<module>',
      'lineno': 16
    },
    {
      'filename': '/var/playground/main.py',
      'name': 'func1',
      'lineno': 11
    },
    {
      'filename': '/var/playground/main.py',
      'name': 'func2',
      'lineno': 7
    },
    {
      'filename': '/var/playground/my.py',
      'name': 'test',
      'lineno': 2
    }
  ]
}

Tracking changes in Windows registry

When using a VM, I use these steps to inspect changes to the registry:

  1. Using 7-Zip, open the vdi/vhd/vmdk file and extract the folder C:\Windows\System32\config
  2. Run OfflineRegistryView to convert the registry to plaintext
    • Set the 'Config Folder' to the folder you extracted
    • Set the 'Base Key' to HKLM\SYSTEM or HKLM\SOFTWARE
    • Set the 'Subkey Depth' to 'Unlimited'
    • Press the 'Go' button

Now use your favourite diff program to compare the 'before' and 'after' snapshots.

Twitter Bootstrap onclick event on buttons-radio

This is a really annoying one. What I ended up using is this:

First, create a group of simple buttons with no data-toggle attribute.

<div id="selector" class="btn-group">
    <button type="button" class="btn active">Day</button>
    <button type="button" class="btn">Week</button>
    <button type="button" class="btn">Month</button>
    <button type="button" class="btn">Year</button>
</div>

Next, write an event handler that simulates the radio button effect by 'activating' the clicked one and 'deactivating' all other buttons. (EDIT: Integrated Nick's cleaner version from the comments.)

$('#selector button').click(function() {
    $(this).addClass('active').siblings().removeClass('active');

    // TODO: insert whatever you want to do with $(this) here
});

Echoing the last command run in Bash?

Bash has built in features to access the last command executed. But that's the last whole command (e.g. the whole case command), not individual simple commands like you originally requested.

!:0 = the name of command executed.

!:1 = the first parameter of the previous command

!:* = all of the parameters of the previous command

!:-1 = the final parameter of the previous command

!! = the previous command line

etc.

So, the simplest answer to the question is, in fact:

echo !!

...alternatively:

echo "Last command run was ["!:0"] with arguments ["!:*"]"

Try it yourself!

echo this is a test
echo !!

In a script, history expansion is turned off by default, you need to enable it with

set -o history -o histexpand

Find in Files: Search all code in Team Foundation Server

If you install TFS 2008 PowerTools you will get a "Find in Source Control" action in the Team Explorer right click menu.

TFS2008 Power Tools

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

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

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


string.find()

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

Returns the startIndex & endIndex of the substring found.

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

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

You will likely use this in combination with string.sub

Example

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

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

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

How is Pythons glob.glob ordered?

From @Johan La Rooy's solution, sorting the images using sorted(glob.glob('*.png')) does not work for me, the output list is still not ordered by their names.

However, the sorted(glob.glob('*.png'), key=os.path.getmtime) works perfectly.

I am a bit confused how can sorting by their names does not work here.

Thank @Martin Thoma for posting this great question and @Johan La Rooy for the helpful solutions.

How to get your Netbeans project into Eclipse

One other easy way of doing it would be as follows (if you have a simple NetBeans project and not using maven for example).

  1. In Eclipse, Go to File -> New -> Java Project
  2. Give a name for your project and click finish to create your project
  3. When the project is created find the source folder in NetBeans project, drag and drop all the source files from the NetBeans project to 'src' folder of your new created project in eclipse.
  4. Move the java source files to respective package (if required)
  5. Now you should be able to run your NetBeans project in Eclipse.

How to set image button backgroundimage for different state?

Hi try the following code it will be useful to you,

((ImageView)findViewById(R.id.ImageViewButton)).setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN)
            ((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_over);

        if(event.getAction() == MotionEvent.ACTION_UP)
            ((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_normal);

        return false;
    }
});

Call a stored procedure with parameter in c#

It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.

Also, use a using for all disposable objects, so that you are sure that they are disposed properly:

private void button1_Click(object sender, EventArgs e) {
  using (SqlConnection con = new SqlConnection(dc.Con)) {
    using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
      cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }
}

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

  • {0} = Property Name
  • {1} = Max Length
  • {2} = Min Length

Much thanks to bloudraak for initially pointing this out.

Select Rows with id having even number

SELECT * FROM Orders where OrderID % 2 = 0;///this is for even numbers

SELECT * FROM Orders where OrderID % 2 != 0;///this is for odd numbers

What is the difference between an int and an Integer in Java and C#?

Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:

Integer i = new Integer(6);

You could call some method on i:

String s = i.toString();//sets s the string representation of i

Whereas with an int:

int i = 6;

You cannot call any methods on it, because it is simply a primitive. So:

String s = i.toString();//will not work!!!

would produce an error, because int is not an object.

int is one of the few primitives in Java (along with char and some others). I'm not 100% sure, but I'm thinking that the Integer object more or less just has an int property and a whole bunch of methods to interact with that property (like the toString() method for example). So Integer is a fancy way to work with an int (Just as perhaps String is a fancy way to work with a group of chars).

I know that Java isn't C, but since I've never programmed in C this is the closest I could come to the answer. Hope this helps!

Integer object javadoc

Integer Ojbect vs. int primitive comparison

HTML table headers always visible at top of window when viewing a large table

I've encountered this problem very recently. Unfortunately, I had to do 2 tables, one for the header and one for the body. It's probably not the best approach ever but here goes:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
    <title>oh hai</title>_x000D_
</head>_x000D_
<body>_x000D_
    <table id="tableHeader">_x000D_
        <tr>_x000D_
            <th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
            <th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
        </tr>_x000D_
    </table>_x000D_
    <div style="height:50px; overflow:auto; width:250px">_x000D_
        <table>_x000D_
            <tr>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This worked for me, it's probably not the elegant way but it does work. I'll investigate so see if I can do something better, but it allows for multiple tables.

Go read on the overflow propriety to see if it fits your need

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

Latex - Change margins of only a few pages

Look up \enlargethispage in some LaTeX reference.