Programs & Examples On #Xmlignore

It is a Boolean property for XML object in [tag:.net] applications that gets or sets a value that specifies whether or not the XmlSerializer serializes a public field or public read/write property.

PRINT statement in T-SQL

For the benefit of anyone else reading this question that really is missing print statements from their output, there actually are cases where the print executes but is not returned to the client. I can't tell you specifically what they are. I can tell you that if put a go statement immediately before and after any print statement, you will see it if it is executed.

How can I discover the "path" of an embedded resource?

The name of the resource is the name space plus the "pseudo" name space of the path to the file. The "pseudo" name space is made by the sub folder structure using \ (backslashes) instead of . (dots).

public static Stream GetResourceFileStream(String nameSpace, String filePath)
{
    String pseduoName = filePath.Replace('\\', '.');
    Assembly assembly = Assembly.GetExecutingAssembly();
    return assembly.GetManifestResourceStream(nameSpace + "." + pseduoName);
}

The following call:

GetResourceFileStream("my.namespace", "resources\\xml\\my.xml")

will return the stream of my.xml located in the folder-structure resources\xml in the name space: my.namespace.

Closing database connections in Java

It is always better to close the database/resource objects after usage. Better close the connection, resultset and statement objects in the finally block.

Until Java 7, all these resources need to be closed using a finally block. If you are using Java 7, then for closing the resources, you can do as follows.

try(Connection con = getConnection(url, username, password, "org.postgresql.Driver");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
) {

    // Statements
}
catch(....){}

Now, the con, stmt and rs objects become part of try block and Java automatically closes these resources after use.

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

No, you can't. JavaScript is executed on the client side (browser), while the session data is stored on the server.

However, you can expose session variables for JavaScript in several ways:

  • a hidden input field storing the variable as its value and reading it through the DOM API
  • an HTML5 data attribute which you can read through the DOM
  • storing it as a cookie and accessing it through JavaScript
  • injecting it directly in the JS code, if you have it inline

In JSP you'd have something like:

<input type="hidden" name="pONumb" value="${sessionScope.pONumb} />

or:

<div id="product" data-prodnumber="${sessionScope.pONumb}" />

Then in JS:

// you can find a more efficient way to select the input you want
var inputs = document.getElementsByTagName("input"), len = inputs.length, i, pONumb;
for (i = 0; i < len; i++) {
    if (inputs[i].name == "pONumb") {
        pONumb = inputs[i].value;
        break;
    }
}

or:

var product = document.getElementById("product"), pONumb;
pONumb = product.getAttribute("data-prodnumber");

The inline example is the most straightforward, but if you then want to store your JavaScript code as an external resource (the recommended way) it won't be feasible.

<script>
    var pONumb = ${sessionScope.pONumb};
    [...]
</script>

HTML5 event handling(onfocus and onfocusout) using angular 2

The solution is this:

  <input (click)="focusOut()" type="text" matInput [formControl]="inputControl"
  [matAutocomplete]="auto">
   <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" >
     <mat-option (onSelectionChange)="submitValue($event)" *ngFor="let option of 
      options | async" [value]="option">
      {{option.name | translate}}
     </mat-option>
  </mat-autocomplete>

TS
focusOut() {
this.inputControl.disable();
this.inputControl.enable();
}

What is the difference between Left, Right, Outer and Inner Joins?

SQL JOINS difference:

Very simple to remember :

INNER JOIN only show records common to both tables.

OUTER JOIN all the content of the both tables are merged together either they are matched or not.

LEFT JOIN is same as LEFT OUTER JOIN - (Select records from the first (left-most) table with matching right table records.)

RIGHT JOIN is same as RIGHT OUTER JOIN - (Select records from the second (right-most) table with matching left table records.)

enter image description here

How do I select an element with its name attribute in jQuery?

You can use:

jQuery('[name="' + nameAttributeValue + '"]');

this will be an inefficient way to select elements though, so it would be best to also use the tag name or restrict the search to a specific element:

jQuery('div[name="' + nameAttributeValue + '"]'); // with tag name
jQuery('div[name="' + nameAttributeValue + '"]',
     document.getElementById('searcharea'));      // with a search base

"Parse Error : There is a problem parsing the package" while installing Android application

In my case build 1 was installed correctly in my mobile using the signed APK (also from Google Play Store). But when I update the application with build 2 for first time, I had an issue installing it with the signed APK as I got "There was a problem parsing the package".

I tried several methods as specified above. But did not work.

After some time, I rerun the commands

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-key.keystore app-release-unsigned.apk myappkeyalias
zipalign -v 4 app-release-unsigned.apk MyApp.apk

and surprisingly, it worked.

It seems sometimes the APK built might be corrupt. So, Re-running jarsigner and zipalign commands resolved my issue.

Convert output of MySQL query to utf8

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

macOS on VMware doesn't recognize iOS device

I met the same problem. I found the solution in the solution from kb.vmware.com.
It works for me by adding

usb.quirks.device0 = "0xvid:0xpid skip-refresh"

Detail as below:


To add quirks:
  1. Shut down the virtual machine and quit Workstation/Fusion.

    Caution: Do not skip this step.
     
  2. Open the vmware.log file within the virtual machine bundle. For more information, see Locating a virtual machine bundle in VMware Workstation/Fusion (1007599).
  3. In the Filter box at the top of the Console window, enter the name of the device manufacturer.

    For example, if you enter the name Apple, you see a line that looks similar to:

    vmx | USB: Found device [name:Apple\ IR\ Receiver vid:05ac pid:8240 path:13/7/2 speed:full family:hid]



    The line has the name of the USB device and its vid and pid information. Make a note of the vid and pid values.
     

  4. Open the .vmx file using a text editor. For more information, see Editing the .vmx file for your Workstation/Fusion virtual machine (1014782).
  5. Add this line to the .vmx file, replacing vid and pid with the values noted in Step 2, each prefixed by the number 0 and the letter x .

    usb.quirks.device0 = "0xvid:0xpid skip-reset"

    For example, for the Apple device found in step 2, this line is:

    usb.quirks.device0 = "0x05ac:0x8240 skip-reset"
     

  6. Save the .vmx file.
  7. Re-open Workstation/Fusion. The edited .vmx file is reloaded with the changes.
  8. Start the virtual machine, and connect the device.
  9. If the issue is not resolved, replace the quirks line added in Step 4 with one of these lines, in the order provided, and repeat Steps 5 to 8:
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
usb.quirks.device0 = "0xvid:0xpid skip-setconfig"
usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig"

Notes:

  • Use one of these lines at a time. If one does not work, replace it with another one in the list. Do not add more than one of these in the .vmx file at a time.
  • The last line uses all three quirks in combination. Use this only if the other three lines do not work.

Refer this to see in detail.

Detecting Enter keypress on VB.NET

I had the same problem and I could not make this answer work on Framework 2.0 so I dug deeper.

You would have to first handle the PreviewKeyDown on the textbox so when ENTER came along you would set IsInputKey so that it could be handled by or forwarded to the keyDown event on the textbox. Like this:

Private Sub txtFiltro_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtFiltro.PreviewKeyDown
    Select Case e.KeyCode
        Case Keys.Enter
            e.IsInputKey = True
    End Select
 End Sub

and then you would handle the event keydown on the textbox. One of the answer was on the right track but missed setting the e.IsInputKey.

Private Sub txtFiltro_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFiltro.KeyDown
    If e.KeyCode = Keys.Enter Then
        e.handled = True
        Textbox1.Focus()
    End If
End Sub

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

How to update the value stored in Dictionary in C#?

You can follow this approach:

void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
    int val;
    if (dic.TryGetValue(key, out val))
    {
        // yay, value exists!
        dic[key] = val + newValue;
    }
    else
    {
        // darn, lets add the value
        dic.Add(key, newValue);
    }
}

The edge you get here is that you check and get the value of corresponding key in just 1 access to the dictionary. If you use ContainsKey to check the existance and update the value using dic[key] = val + newValue; then you are accessing the dictionary twice.

Java List.contains(Object with field value equal to x)

Binary Search

You can use Collections.binarySearch to search an element in your list (assuming the list is sorted):

Collections.binarySearch(list, new YourObject("a1", "b",
                "c"), new Comparator<YourObject>() {

            @Override
            public int compare(YourObject o1, YourObject o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

which will return a negative number if the object is not present in the collection or else it will return the index of the object. With this you can search for objects with different searching strategies.

Reading a List from properties file and load with spring annotation @Value

you can do this with annotations like this

 @Value("#{T(java.util.Arrays).asList('${my.list.of.strings:a,b,c}')}") 
    private List<String> mylist;

here my.list.of.strings will be picked from the properties file, if its not there, then the defaults a,b,c will be used

and in your properties file, you can have something like this

my.list.of.strings=d,e,f

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

I found this library quite simple and functional (http://kirillsprograms.com/top_Vectors.php). These are bare bone vectors implemented via C++ templates. No fancy stuff - just what you need to do with vectors (add, subtract multiply, dot, etc).

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I got the same exception when I locally tested. The problem was a URL schema in my request.

Change https:// to http:// in your client url.

Probably it helps.

How to get PID by process name?

To improve the Padraic's answer: when check_output returns a non-zero code, it raises a CalledProcessError. This happens when the process does not exists or is not running.

What I would do to catch this exception is:

#!/usr/bin/python

from subprocess import check_output, CalledProcessError

def getPIDs(process):
    try:
        pidlist = map(int, check_output(["pidof", process]).split())
    except  CalledProcessError:
        pidlist = []
    print 'list of PIDs = ' + ', '.join(str(e) for e in pidlist)

if __name__ == '__main__':
    getPIDs("chrome")

The output:

$ python pidproc.py
list of PIDS = 31840, 31841, 41942

Regular Expression to match only alphabetic characters

[a-zA-Z] should do that just fine.

You can reference the cheat sheet.

How Exactly Does @param Work - Java

You might miss @author and inside of @param you need to explain what's that parameter for, how to use it, etc.

Preserve Line Breaks From TextArea When Writing To MySQL

function breakit($t) {
    return nl2br(htmlentities($t, ENT_QUOTES, 'UTF-8'));
}

this may help you

pass the textarea wal

Drop multiple tables in one shot in MySQL

Example:

Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

Why can a function modify some arguments as perceived by the caller, but not others?

If the functions are re-written with completely different variables and we call id on them, it then illustrates the point well. I didn't get this at first and read jfs' post with the great explanation, so I tried to understand/convince myself:

def f(y, z):
    y = 2
    z.append(4)
    print ('In f():             ', id(y), id(z))

def main():
    n = 1
    x = [0,1,2,3]
    print ('Before in main:', n, x,id(n),id(x))
    f(n, x)
    print ('After in main:', n, x,id(n),id(x))

main()
Before in main: 1 [0, 1, 2, 3]   94635800628352 139808499830024
In f():                          94635800628384 139808499830024
After in main: 1 [0, 1, 2, 3, 4] 94635800628352 139808499830024

z and x have the same id. Just different tags for the same underlying structure as the article says.

How do I update a GitHub forked repository?

Here is GitHub's official document on Syncing a fork:

Syncing a fork

The Setup

Before you can sync, you need to add a remote that points to the upstream repository. You may have done this when you originally forked.

Tip: Syncing your fork only updates your local copy of the repository; it does not update your repository on GitHub.

$ git remote -v
# List the current remotes
origin  https://github.com/user/repo.git (fetch)
origin  https://github.com/user/repo.git (push)

$ git remote add upstream https://github.com/otheruser/repo.git
# Set a new remote

$ git remote -v
# Verify new remote
origin    https://github.com/user/repo.git (fetch)
origin    https://github.com/user/repo.git (push)
upstream  https://github.com/otheruser/repo.git (fetch)
upstream  https://github.com/otheruser/repo.git (push)

Syncing

There are two steps required to sync your repository with the upstream: first you must fetch from the remote, then you must merge the desired branch into your local branch.

Fetching

Fetching from the remote repository will bring in its branches and their respective commits. These are stored in your local repository under special branches.

$ git fetch upstream
# Grab the upstream remote's branches
remote: Counting objects: 75, done.
remote: Compressing objects: 100% (53/53), done.
remote: Total 62 (delta 27), reused 44 (delta 9)
Unpacking objects: 100% (62/62), done.
From https://github.com/otheruser/repo
 * [new branch]      master     -> upstream/master

We now have the upstream's master branch stored in a local branch, upstream/master

$ git branch -va
# List all local and remote-tracking branches
* master                  a422352 My local commit
  remotes/origin/HEAD     -> origin/master
  remotes/origin/master   a422352 My local commit
  remotes/upstream/master 5fdff0f Some upstream commit

Merging

Now that we have fetched the upstream repository, we want to merge its changes into our local branch. This will bring that branch into sync with the upstream, without losing our local changes.

$ git checkout master
# Check out our local master branch
Switched to branch 'master'

$ git merge upstream/master
# Merge upstream's master into our own
Updating a422352..5fdff0f
Fast-forward
 README                    |    9 -------
 README.md                 |    7 ++++++
 2 files changed, 7 insertions(+), 9 deletions(-)
 delete mode 100644 README
 create mode 100644 README.md

If your local branch didn't have any unique commits, git will instead perform a "fast-forward":

$ git merge upstream/master
Updating 34e91da..16c56ad
Fast-forward
 README.md                 |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

Tip: If you want to update your repository on GitHub, follow the instructions here

What is the correct syntax of ng-include?

For those trouble shooting, it is important to know that ng-include requires the url path to be from the app root directory and not from the same directory where the partial.html lives. (whereas partial.html is the view file that the inline ng-include markup tag can be found).

For example:

Correct: div ng-include src=" '/views/partials/tabSlides/add-more.html' ">

Incorrect: div ng-include src=" 'add-more.html' ">

How can I position my jQuery dialog to center?

Following position parameter worked for me

position: { my: "right bottom", at: "center center", of: window },

Good luck!

How to make a window always stay on top in .Net?

The way i solved this was by making a system tray icon that had a cancel option.

DropDownList's SelectedIndexChanged event not firing

Add property ViewStateMode="Enabled" and EnableViewState="true" And AutoPostBack="true" in drop DropDownList

Textarea onchange detection

The best thing that you can do is to set a function to be called on a given amount of time and this function to check the contents of your textarea.

self.setInterval('checkTextAreaValue()', 50);

How to convert list to string

L = ['L','O','L']
makeitastring = ''.join(map(str, L))

CSS3 opacity gradient?

You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.

CSS:

p {
    color: red;
    -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, 
    from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}

The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)

See a demo with a solid background, but you can change this to whatever you want.

DEMO

Notice also that all the usual image properties are available for mask-image

_x000D_
_x000D_
p  {_x000D_
  color: red;_x000D_
  font-size: 30px;_x000D_
  -webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
  -webkit-mask-size: 100% 50%;_x000D_
  -webkit-mask-repeat: no-repeat;_x000D_
  -webkit-mask-position: left top, left bottom;_x000D_
  }_x000D_
_x000D_
div {_x000D_
    background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.

The idea is to use

mix-blend-mode: hard-light;

that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency

_x000D_
_x000D_
div {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  width: 200px;_x000D_
  mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  left: 0px;_x000D_
  top: 0px;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(transparent, gray);_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

jEdit:

With the keyboard: press Alt-\ (Opt-\ in Mac OS X) to toggle between rectangular and normal selection mode; then use Shift plus arrow keys to extend selection. You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.

With the mouse: Either use Alt-\ (Opt-\ in Mac OS X) as above to toggle rectangular selection mode, then drag as usual; or Ctrl-drag (Cmd-drag in Mac OS X). You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.

Actually, you can even make a non-rectangular selection the normal way and then hit Alt-\ (Opt-\ in Mac OS X) to convert it into a rectangular one.

How can I read command line parameters from an R script?

A few points:

  1. Command-line parameters are accessible via commandArgs(), so see help(commandArgs) for an overview.

  2. You can use Rscript.exe on all platforms, including Windows. It will support commandArgs(). littler could be ported to Windows but lives right now only on OS X and Linux.

  3. There are two add-on packages on CRAN -- getopt and optparse -- which were both written for command-line parsing.

Edit in Nov 2015: New alternatives have appeared and I wholeheartedly recommend docopt.

How to mark a build unstable in Jenkins when running shell scripts

The TextFinder is good only if the job status hasn't been changed from SUCCESS to FAILED or ABORTED. For such cases, use a groovy script in the PostBuild step:

errpattern = ~/TEXT-TO-LOOK-FOR-IN-JENKINS-BUILD-OUTPUT.*/;
manager.build.logFile.eachLine{ line ->
    errmatcher=errpattern.matcher(line)
    if (errmatcher.find()) {
        manager.build.@result = hudson.model.Result.NEW-STATUS-TO-SET
    }
 }

See more details in a post I've wrote about it: http://www.tikalk.com/devops/JenkinsJobStatusChange/

How to identify and switch to the frame in selenium webdriver when frame does not have id

You also can use src to switch to frame, here is what you can use:

driver.switchTo().frame(driver.findElement(By.xpath(".//iframe[@src='https://tssstrpms501.corp.trelleborg.com:12001/teamworks/process.lsw?zWorkflowState=1&zTaskId=4581&zResetContext=true&coachDebugTrace=none']")));

Differences between SP initiated SSO and IDP initiated SSO

IDP Initiated SSO

From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html

In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.

Processing Steps:

  1. A user has logged on to the IdP.
  2. The user requests access to a protected SP resource. The user is not logged on to the SP site.
  3. Optionally, the IdP retrieves attributes from the user data store.
  4. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP.

SP Initiated SSO

From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST

In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.

Processing Steps:

  1. The user requests access to a protected SP resource. The request is redirected to the federation server to handle authentication.
  2. The federation server sends an HTML form back to the browser with a SAML request for authentication from the IdP. The HTML form is automatically posted to the IdP’s SSO service.
  3. If the user is not already logged on to the IdP site or if re-authentication is required, the IdP asks for credentials (e.g., ID and password) and the user logs on.
  4. Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)

  5. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.

  6. (Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.

HAProxy redirecting http to https (ssl)

I don't have enough reputation to comment on a previous answer, so I'm posting a new answer to complement Jay Taylor's answer. Basically his answer will do the redirect, an implicit redirect though, meaning it will issue a 302 (temporary redirect), but since the question informs that the entire website will be served as https, then the appropriate redirect should be a 301 (permanent redirect).

redirect scheme https code 301 if !{ ssl_fc }

It seems a small change, but the impact might be huge depending on the website, with a permanent redirect we are informing the browser that it should no longer look for the http version from the start (avoiding future redirects) - a time saver for https sites. It also helps with SEO, but not dividing the juice of your links.

How to find files recursively by file type and copy them to a directory while in ssh?

Try this:

find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;

How to find the serial port number on Mac OS X?

I was able to screen using the device's name anyway so that wasn't the issue. I was actually just trying to find the port number, i.e. 5331, 5332 etc. I managed to find this by a trial and error process using an app called TCP2Serial from the app store on Mac OS X. It isn't free but that's fine as long as I know it works!

Worth the 99c :) http://itunes.apple.com/us/app/tcp2serial/id506186902?mt=12

How to use if, else condition in jsf to display image

For those like I who just followed the code by skuntsel and received a cryptic stack trace, allow me to save you some time.

It seems c:if cannot by itself be followed by c:otherwise.

The correct solution is as follows:

<c:choose>
    <c:when test="#{some.test}">
        <p>some.test is true</p>
    </c:when>
    <c:otherwise>
        <p>some.test is not true</p>
    </c:otherwise>
</c:choose>

You can add additional c:when tests in as necessary.

Java naming convention for static final variables

The dialog on this seems to be the antithesis of the conversation on naming interface and abstract classes. I find this alarming, and think that the decision runs much deeper than simply choosing one naming convention and using it always with static final.

Abstract and Interface

When naming interfaces and abstract classes, the accepted convention has evolved into not prefixing or suffixing your abstract class or interface with any identifying information that would indicate it is anything other than a class.

public interface Reader {}
public abstract class FileReader implements Reader {}
public class XmlFileReader extends FileReader {}

The developer is said not to need to know that the above classes are abstract or an interface.

Static Final

My personal preference and belief is that we should follow similar logic when referring to static final variables. Instead, we evaluate its usage when determining how to name it. It seems the all uppercase argument is something that has been somewhat blindly adopted from the C and C++ languages. In my estimation, that is not justification to continue the tradition in Java.

Question of Intention

We should ask ourselves what is the function of static final in our own context. Here are three examples of how static final may be used in different contexts:

public class ChatMessage {
    //Used like a private variable
    private static final Logger logger = LoggerFactory.getLogger(XmlFileReader.class);

    //Used like an Enum
    public class Error {
        public static final int Success = 0;
        public static final int TooLong = 1;
        public static final int IllegalCharacters = 2;
    }

    //Used to define some static, constant, publicly visible property
    public static final int MAX_SIZE = Integer.MAX_VALUE;
}

Could you use all uppercase in all three scenarios? Absolutely, but I think it can be argued that it would detract from the purpose of each. So, let's examine each case individually.


Purpose: Private Variable

In the case of the Logger example above, the logger is declared as private, and will only be used within the class, or possibly an inner class. Even if it were declared at protected or package visibility, its usage is the same:

public void send(final String message) {
    logger.info("Sending the following message: '" + message + "'.");
    //Send the message
}

Here, we don't care that logger is a static final member variable. It could simply be a final instance variable. We don't know. We don't need to know. All we need to know is that we are logging the message to the logger that the class instance has provided.

public class ChatMessage {
    private final Logger logger = LoggerFactory.getLogger(getClass());
}

You wouldn't name it LOGGER in this scenario, so why should you name it all uppercase if it was static final? Its context, or intention, is the same in both circumstances.

Note: I reversed my position on package visibility because it is more like a form of public access, restricted to package level.


Purpose: Enum

Now you might say, why are you using static final integers as an enum? That is a discussion that is still evolving and I'd even say semi-controversial, so I'll try not to derail this discussion for long by venturing into it. However, it would be suggested that you could implement the following accepted enum pattern:

public enum Error {
    Success(0),
    TooLong(1),
    IllegalCharacters(2);

    private final int value;

    private Error(final int value) {
        this.value = value;
    }

    public int value() {
        return value;
    }

    public static Error fromValue(final int value) {
        switch (value) {
        case 0:
            return Error.Success;
        case 1:
            return Error.TooLong;
        case 2:
            return Error.IllegalCharacters;
        default:
            throw new IllegalArgumentException("Unknown Error value.");
        }
    }
}

There are variations of the above that achieve the same purpose of allowing explicit conversion of an enum->int and int->enum. In the scope of streaming this information over a network, native Java serialization is simply too verbose. A simple int, short, or byte could save tremendous bandwidth. I could delve into a long winded compare and contrast about the pros and cons of enum vs static final int involving type safety, readability, maintainability, etc.; fortunately, that lies outside the scope of this discussion.

The bottom line is this, sometimes static final int will be used as an enum style structure.

If you can bring yourself to accept that the above statement is true, we can follow that up with a discussion of style. When declaring an enum, the accepted style says that we don't do the following:

public enum Error {
    SUCCESS(0),
    TOOLONG(1),
    ILLEGALCHARACTERS(2);
}

Instead, we do the following:

public enum Error {
    Success(0),
    TooLong(1),
    IllegalCharacters(2);
}

If your static final block of integers serves as a loose enum, then why should you use a different naming convention for it? Its context, or intention, is the same in both circumstances.


Purpose: Static, Constant, Public Property

This usage case is perhaps the most cloudy and debatable of all. The static constant size usage example is where this is most often encountered. Java removes the need for sizeof(), but there are times when it is important to know how many bytes a data structure will occupy.

For example, consider you are writing or reading a list of data structures to a binary file, and the format of that binary file requires that the total size of the data chunk be inserted before the actual data. This is common so that a reader knows when the data stops in the scenario that there is more, unrelated, data that follows. Consider the following made up file format:

File Format: MyFormat (MYFM) for example purposes only
[int filetype: MYFM]
[int version: 0] //0 - Version of MyFormat file format
[int dataSize: 325] //The data section occupies the next 325 bytes
[int checksumSize: 400] //The checksum section occupies 400 bytes after the data section (16 bytes each)
[byte[] data]
[byte[] checksum]

This file contains a list of MyObject objects serialized into a byte stream and written to this file. This file has 325 bytes of MyObject objects, but without knowing the size of each MyObject you have no way of knowing which bytes belong to each MyObject. So, you define the size of MyObject on MyObject:

public class MyObject {
    private final long id; //It has a 64bit identifier (+8 bytes)
    private final int value; //It has a 32bit integer value (+4 bytes)
    private final boolean special; //Is it special? (+1 byte)

    public static final int SIZE = 13; //8 + 4 + 1 = 13 bytes
}

The MyObject data structure will occupy 13 bytes when written to the file as defined above. Knowing this, when reading our binary file, we can figure out dynamically how many MyObject objects follow in the file:

int dataSize = buffer.getInt();
int totalObjects = dataSize / MyObject.SIZE;

This seems to be the typical usage case and argument for all uppercase static final constants, and I agree that in this context, all uppercase makes sense. Here's why:

Java doesn't have a struct class like the C language, but a struct is simply a class with all public members and no constructor. It's simply a data structure. So, you can declare a class in struct like fashion:

public class MyFile {
    public static final int MYFM = 0x4D59464D; //'MYFM' another use of all uppercase!

    //The struct
    public static class MyFileHeader {
        public int fileType = MYFM;
        public int version = 0;
        public int dataSize = 0;
        public int checksumSize = 0;
    }
}

Let me preface this example by stating I personally wouldn't parse in this manner. I'd suggest an immutable class instead that handles the parsing internally by accepting a ByteBuffer or all 4 variables as constructor arguments. That said, accessing (setting in this case) this structs members would look something like:

MyFileHeader header = new MyFileHeader();
header.fileType     = buffer.getInt();
header.version      = buffer.getInt();
header.dataSize     = buffer.getInt();
header.checksumSize = buffer.getInt();

These aren't static or final, yet they are publicly exposed members that can be directly set. For this reason, I think that when a static final member is exposed publicly, it makes sense to uppercase it entirely. This is the one time when it is important to distinguish it from public, non-static variables.

Note: Even in this case, if a developer attempted to set a final variable, they would be met with either an IDE or compiler error.


Summary

In conclusion, the convention you choose for static final variables is going to be your preference, but I strongly believe that the context of use should heavily weigh on your design decision. My personal recommendation would be to follow one of the two methodologies:

Methodology 1: Evaluate Context and Intention [highly subjective; logical]

  • If it's a private variable that should be indistinguishable from a private instance variable, then name them the same. all lowercase
  • If it's intention is to serve as a type of loose enum style block of static values, then name it as you would an enum. pascal case: initial-cap each word
  • If it's intention is to define some publicly accessible, constant, and static property, then let it stand out by making it all uppercase

Methodology 2: Private vs Public [objective; logical]

Methodology 2 basically condenses its context into visibility, and leaves no room for interpretation.

  • If it's private or protected then it should be all lowercase.
  • If it's public or package then it should be all uppercase.

Conclusion

This is how I view the naming convention of static final variables. I don't think it is something that can or should be boxed into a single catch all. I believe that you should evaluate its intent before deciding how to name it.

However, the main objective should be to try and stay consistent throughout your project/package's scope. In the end, that is all you have control over.

(I do expect to be met with resistance, but also hope to gather some support from the community on this approach. Whatever your stance, please keep it civil when rebuking, critiquing, or acclaiming this style choice.)

Remove padding from columns in Bootstrap 3

<div class="col-md-12">
<h2>OntoExplorer<span style="color:#b92429">.</span></h2>

<div class="col-md-4">
    <div class="widget row">
        <div class="widget-header">
            <h3>Dimensions</h3>
        </div>

        <div class="widget-content" id="">
            <div id='jqxWidget'>
                <div style="clear:both;margin-bottom:20px;" id="listBoxA"></div>
                <div style="clear:both;" id="listBoxB"></div>

            </div>
        </div>
    </div>
</div>

<div class="col-md-8">
    <div class="widget row">
        <div class="widget-header">
            <h3>Results</h3>
        </div>

        <div class="widget-content">
            <div id="map_canvas" style="height: 362px;"></div>
        </div>
    </div>
</div>

You can add a class of row to the div inside the col-md-4 and the row's -15px margin will balance out the gutter from the columns. Good explanation here about gutters and rows in Bootstrap 3.

How do I make an HTTP request in Swift?

Using URLSession + Swift 5

Just adding to cezar's answer, if you want to make web request using Apple's URLSession class, there are multiple way to do the task

  1. Simple GET Request with URL
  2. Simple GET Request with URL and Parameters
  3. Simple GET Request with URL with Error Handlings
  4. Simple POST Request with URL, Parameters with Error Handlings

1. Simple GET Request with URL

func simpleGetUrlRequest()
    {
        let url = URL(string: "https://httpbin.org/get")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            print("The response is : ",String(data: data, encoding: .utf8)!)
            //print(NSString(data: data, encoding: String.Encoding.utf8.rawValue) as Any)
        }
        task.resume()
    }

Note : Make sure You must add "NSAppTransportSecurity" key in pList for http requests

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

2. Simple GET Request with URL and Parameters

func simpleGetUrlWithParamRequest()
    {
        let url = URL(string: "https://www.google.com/search?q=peace")!
        
        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            
            if error != nil || data == nil {
                print("Client error!")
                return
            }
            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Server error!")
                return
            }
            print("The Response is : ",response)
        }
        task.resume()
    }

3. Simple GET Request with URL with Error Handlings

func simpleGetUrlRequestWithErrorHandling()
    {
        let session = URLSession.shared
        let url = URL(string: "https://httpbin.org/get")!
        
        let task = session.dataTask(with: url) { data, response, error in
            
            if error != nil || data == nil {
                print("Client error!")
                return
            }
            
            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Server error!")
                return
            }
            
            guard let mime = response.mimeType, mime == "application/json" else {
                print("Wrong MIME type!")
                return
            }
            
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: [])
                print("The Response is : ",json)
            } catch {
                print("JSON error: \(error.localizedDescription)")
            }
            
        }
        task.resume()
    }

4. Simple POST Request with URL, Parameters with Error Handlings.

func simplePostRequestWithParamsAndErrorHandling(){
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30
        configuration.timeoutIntervalForResource = 30
        let session = URLSession(configuration: configuration)
        
        let url = URL(string: "https://httpbin.org/post")!
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        
        let parameters = ["username": "foo", "password": "123456"]
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
        } catch let error {
            print(error.localizedDescription)
        }
        
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
            
            if error != nil || data == nil {
                print("Client error!")
                return
            }
            
            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Oops!! there is server error!")
                return
            }
            
            guard let mime = response.mimeType, mime == "application/json" else {
                print("response is not json")
                return
            }
            
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: [])
                print("The Response is : ",json)
            } catch {
                print("JSON error: \(error.localizedDescription)")
            }
            
        })
        
        task.resume()
    }

Your suggestions are appreciated!!

Replace part of a string with another string

With C++11 you can use std::regex like so:

#include <regex>
...
std::string string("hello $name");
string = std::regex_replace(string, std::regex("\\$name"), "Somename");

The double backslash is required for escaping an escape character.

Amazon products API - Looking for basic overview and information

Your post contains several questions, so I'll try to answer them one at a time:

  1. The API you're interested in is the Product Advertising API (PA). It allows you programmatic access to search and retrieve product information from Amazon's catalog. If you're having trouble finding information on the API, that's because the web service has undergone two name changes in recent history: it was also known as ECS and AAWS.
  2. The signature process you're referring to is the same HMAC signature that all of the other AWS services use for authentication. All that's required to sign your requests to the Product Advertising API is a function to compute a SHA-1 hash and and AWS developer key. For more information, see the section of the developer documentation on signing requests.
  3. As far as I know, there is no support for retrieving RSS feeds of products or tags through PA. If anyone has information suggesting otherwise, please correct me.
  4. Either the REST or SOAP APIs should make your use case very straight forward. Amazon provides a fairly basic "getting started" guide available here. As well, you can view the complete API developer documentation here.

Although the documentation is a little hard to find (likely due to all the name changes), the PA API is very well documented and rather elegant. With a modicum of elbow grease and some previous experience in calling out to web services, you shouldn't have any trouble getting the information you need from the API.

How to set a bitmap from resource

Using this function you can get Image Bitmap. Just pass image url

 public Bitmap getBitmapFromURL(String strURL) {
      try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
      } catch (IOException e) {
        e.printStackTrace();
        return null;
      }
 }

Calculate RSA key fingerprint

Run the following command to retrieve the SHA256 fingerprint of your SSH key (-l means "list" instead of create a new key, -f means "filename"):

$ ssh-keygen -lf /path/to/ssh/key

So for example, on my machine the command I ran was (using RSA public key):

$ ssh-keygen -lf ~/.ssh/id_rsa.pub
2048 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff /Users/username/.ssh/id_rsa.pub (RSA)

To get the GitHub (MD5) fingerprint format with newer versions of ssh-keygen, run:

$ ssh-keygen -E md5 -lf <fileName>

Bonus information:

ssh-keygen -lf also works on known_hosts and authorized_keys files.

To find most public keys on Linux/Unix/OS X systems, run

$ find /etc/ssh /home/*/.ssh /Users/*/.ssh -name '*.pub' -o -name 'authorized_keys' -o -name 'known_hosts'

(If you want to see inside other users' homedirs, you'll have to be root or sudo.)

The ssh-add -l is very similar, but lists the fingerprints of keys added to your agent. (OS X users take note that magic passwordless SSH via Keychain is not the same as using ssh-agent.)

XML Schema minOccurs / maxOccurs default values

New, expanded answer to an old, commonly asked question...

Default Values

  • Occurrence constraints minOccurs and maxOccurs default to 1.

Common Cases Explained

<xsd:element name="A"/>

means A is required and must appear exactly once.


<xsd:element name="A" minOccurs="0"/>

means A is optional and may appear at most once.


 <xsd:element name="A" maxOccurs="unbounded"/>

means A is required and may repeat an unlimited number of times.


 <xsd:element name="A" minOccurs="0" maxOccurs="unbounded"/>

means A is optional and may repeat an unlimited number of times.


See Also

  • W3C XML Schema Part 0: Primer

    In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once.

  • W3C XML Schema Part 1: Structures Second Edition

    <element
      maxOccurs = (nonNegativeInteger | unbounded)  : 1
      minOccurs = nonNegativeInteger : 1
      >
    
    </element>
    

C++ Redefinition Header Files (winsock2.h)

In VS 2015, the following will work:

#define _WINSOCKAPI_

While the following won't:

#define WIN32_LEAN_AND_MEAN

Prevent Sequelize from outputting SQL to the console on execution of query?

As in other answers, you can just set logging:false, but I think better than completely disabling logging, you can just embrace log levels in your app. Sometimes you may want to take a look at the executed queries so it may be better to configure Sequelize to log at level verbose or debug. for example (I'm using winston here as a logging framework but you can use any other framework) :

var sequelize = new Sequelize('database', 'username', 'password', {
  logging: winston.debug
});

This will output SQL statements only if winston log level is set to debug or lower debugging levels. If log level is warn or info for example SQL will not be logged

How to count the frequency of the elements in an unordered list?

Another approach of doing this, albeit by using a heavier but powerful library - NLTK.

import nltk

fdist = nltk.FreqDist(a)
fdist.values()
fdist.most_common()

Escaping special characters in Java Regular Expressions

Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?

If you are looking for a way to create constants that you can use in your regex patterns, then just prepending them with "\\" should work but there is no nice Pattern.escape('.') function to help with this.

So if you are trying to match "\\d" (the string \d instead of a decimal character) then you would do:

// this will match on \d as opposed to a decimal character
String matchBackslashD = "\\\\d";
// as opposed to
String matchDecimalDigit = "\\d";

The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself. Prepending any special character with backslash turns it into a normal character instead of a special one.

matchPeriod = "\\.";
matchPlus = "\\+";
matchParens = "\\(\\)";
... 

In your post you use the Pattern.quote(string) method. This method wraps your pattern between "\\Q" and "\\E" so you can match a string even if it happens to have a special regex character in it (+, ., \\d, etc.)

Running a script inside a docker container using shell script

You could also mount a local directory into your docker image and source the script in your .bashrc. Don't forget the script has to consist of functions unless you want it to execute on every new shell. (This is outdated see the update notice.)

I'm using this solution to be able to update the script outside of the docker instance. This way I don't have to rerun the image if changes occur, I just open a new shell. (Got rid of reopening a shell - see the update notice)

Here is how you bind your current directory:

docker run -it -v $PWD:/scripts $my_docker_build /bin/bash

Now your current directory is bound to /scripts of your docker instance.

(Outdated) To save your .bashrc changes commit your working image with this command:

docker commit $container_id $my_docker_build

Update

To solve the issue to open up a new shell for every change I now do the following:

In the dockerfile itself I add RUN echo "/scripts/bashrc" > /root/.bashrc". Inside zshrc I export the scripts directory to the path. The scripts directory now contains multiple files instead of one. Now I can directly call all scripts without having open a sub shell on every change.

BTW you can define the history file outside of your container too. This way it's not necessary to commit on a bash change anymore.

How to list files in an android directory?

If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn't work, it's worth reading this answer:

Android Q (10) ask permission to get access all storage. Scoped storage

I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won't continue to work in future versions.

What does the term "canonical form" or "canonical representation" in Java mean?

A canonical form means a naturally unique representation of the element

Using UPDATE in stored procedure with optional parameters

ALTER PROCEDURE LN
    (
    @Firstname nvarchar(200)
)

AS
BEGIN

    UPDATE tbl_Students1
    SET Firstname=@Firstname 

    WHERE Studentid=3
END


exec LN 'Thanvi'

How do I compile the asm generated by GCC?

nasm -f bin -o 2_hello 2_hello.asm

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

right align an image using CSS HTML

<img style="float: right;" alt="" src="http://example.com/image.png" />
<div style="clear: right">
   ...text...
</div>    

jsFiddle.

Bootstrap Carousel Full Screen

I found an answer on the startbootstrap.com. Try this code:

CSS

html,
body {
    height: 100%;
}

.carousel,
.item,
.active {
    height: 100%;
}


.carousel-inner {
    height: 100%;
}

/* Background images are set within the HTML using inline CSS, not here */

.fill {
    width: 100%;
    height: 100%;
    background-position: center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
}

footer {
    margin: 50px 0;
}

HTML

   <div class="carousel-inner">
        <div class="item active">
            <!-- Set the first background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide One');"></div>
            <div class="carousel-caption">
                <h2>Caption 1</h2>
            </div>
        </div>
        <div class="item">
            <!-- Set the second background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide Two');"></div>
            <div class="carousel-caption">
                <h2>Caption 2</h2>
            </div>
        </div>
        <div class="item">
            <!-- Set the third background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide Three');"></div>
            <div class="carousel-caption">
                <h2>Caption 3</h2>
            </div>
        </div>
    </div>

Source

Unresolved Import Issues with PyDev and Eclipse

Following, in my opinion will solve the problem

  1. Adding the init.py to your "~/Desktop/Python_Tutorials/diveintopython/py" folder
  2. Go to Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter to remove your Python Interpreter setting (reason being is because PyDev unable to auto refresh any updates made to any System PythonPath)
  3. Add in the Interpreter with the same details as before (this will refresh your Python Interpreter setting with updates made to your PythonPath)
  4. Finally since your "~/Desktop/Python_Tutorials/diveintopython/py" folder not a standard PythonPath, you will need to add it in. There are two ways to do it

a. As per what David German suggested. However this only applicable for the particular projects you are in b. Add in "~/Desktop/Python_Tutorials/diveintopython/py" into a new PythonPath under Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter --> Libraries subtab --> NewFolder

Hope it helps.

c++ integer->std::string conversion. Simple function?

Now in c++11 we have

#include <string>
string s = std::to_string(123);

Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

Ruby: How to turn a hash into HTTP parameters?

I like using this gem:

https://rubygems.org/gems/php_http_build_query

Sample usage:

puts PHP.http_build_query({"a"=>"b","c"=>"d","e"=>[{"hello"=>"world","bah"=>"black"},{"hello"=>"world","bah"=>"black"}]})

# a=b&c=d&e%5B0%5D%5Bbah%5D=black&e%5B0%5D%5Bhello%5D=world&e%5B1%5D%5Bbah%5D=black&e%5B1%5D%5Bhello%5D=world

Remove an entire column from a data.frame in R

You can set it to NULL.

> Data$genome <- NULL
> head(Data)
   chr region
1 chr1    CDS
2 chr1   exon
3 chr1    CDS
4 chr1   exon
5 chr1    CDS
6 chr1   exon

As pointed out in the comments, here are some other possibilities:

Data[2] <- NULL    # Wojciech Sobala
Data[[2]] <- NULL  # same as above
Data <- Data[,-2]  # Ian Fellows
Data <- Data[-2]   # same as above

You can remove multiple columns via:

Data[1:2] <- list(NULL)  # Marek
Data[1:2] <- NULL        # does not work!

Be careful with matrix-subsetting though, as you can end up with a vector:

Data <- Data[,-(2:3)]             # vector
Data <- Data[,-(2:3),drop=FALSE]  # still a data.frame

Is there a way to make mv create the directory to be moved to if it doesn't exist?

Save as a script named mv or mv.sh

#!/bin/bash
# mv.sh
dir="$2"
tmp="$2"; tmp="${tmp: -1}"
[ "$tmp" != "/" ] && dir="$(dirname "$2")"
[ -a "$dir" ] ||
mkdir -p "$dir" &&
mv "$@"

Or put at the end of your ~/.bashrc file as a function that replaces the default mv on every new terminal. Using a function allows bash keep it memory, instead of having to read a script file every time.

function mv ()
{
    dir="$2"
    tmp="$2"; tmp="${tmp: -1}"
    [ "$tmp" != "/" ] && dir="$(dirname "$2")"
    [ -a "$dir" ] ||
    mkdir -p "$dir" &&
    mv "$@"
}

These based on the submission of Chris Lutz.

linux find regex

Note that -regex depends on whole path.

 -regex pattern
              File name matches regular expression pattern.  
              This is a match on the whole path, not a search.

You don't actually have to use -regex for what you are doing.

find . -iname "*[0-9]"

Could not obtain information about Windows NT group user

In my case I was getting this error trying to use the IS_ROLEMEMBER() function on SQL Server 2008 R2. This function isn't valid prior to SQL Server 2012.

Instead of this function I ended up using

select 1 
from sys.database_principals u 
inner join sys.database_role_members ur 
    on u.principal_id = ur.member_principal_id 
inner join sys.database_principals r 
    on ur.role_principal_id = r.principal_id 
where r.name = @role_name 
and u.name = @username

Significantly more verbose, but it gets the job done.

How do I split a string on a delimiter in Bash?

If you don't mind processing them immediately, I like to do this:

for i in $(echo $IN | tr ";" "\n")
do
  # process
done

You could use this kind of loop to initialize an array, but there's probably an easier way to do it. Hope this helps, though.

Undo a particular commit in Git that's been pushed to remote repos

Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

"date(): It is not safe to rely on the system's timezone settings..."

A quick solution whilst your rectify the incompatibilities, is to disable error reporting in your index.php file:

Insert the line below into your index.php below define( ‘_JEXEC’, 1 );

error_reporting( E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR |
E_COMPILE_WARNING );

How to obtain the location of cacerts of the default java installation?

As of OS X 10.10.1 (Yosemite), the location of the cacerts file has been changed to

$(/usr/libexec/java_home)/jre/lib/security/cacerts

How to extract request http headers from a request using NodeJS connect

If you use Express 4.x, you can use the req.get(headerName) method as described in Express 4.x API Reference

Convert String array to ArrayList

Using Collections#addAll()

String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>(); 
Collections.addAll(arrayList, words); 

CSS change button style after click

An easy way of doing this is to use JavaScript like so:

element.addEventListener('click', (e => {
    e.preventDefault();

    element.style = '<insert CSS here as you would in a style attribute>';
}));

Kubernetes service external ip pending

When using Minikube, you can get the IP and port through which you can access the service by running:

minikube service [service name]

E.g.:

minikube service kubia-http

jQuery fade out then fade in

fade the other in in the callback of fadeout, which runs when fadeout is done. Using your code:

$('#two, #three').hide();
$('.slide').click(function(){
    var $this = $(this);
    $this.fadeOut(function(){ $this.next().fadeIn(); });
});

alternatively, you can just "pause" the chain, but you need to specify for how long:

$(this).fadeOut().next().delay(500).fadeIn();

What is the most efficient way of finding all the factors of a number in Python?

Here is another alternate without reduce that performs well with large numbers. It uses sum to flatten the list.

def factors(n):
    return set(sum([[i, n//i] for i in xrange(1, int(n**0.5)+1) if not n%i], []))

Display loading image while post with ajax

_x000D_
_x000D_
//$(document).ready(function(){_x000D_
//  $("a").click(function(event){_x000D_
//  event.preventDefault();_x000D_
//  $("div").html("This is prevent link...");_x000D_
// });_x000D_
//});   _x000D_
_x000D_
$(document).ready(function(){_x000D_
 $("a").click(function(event){_x000D_
  event.preventDefault();_x000D_
  $.ajax({_x000D_
   beforeSend: function(){_x000D_
    $('#text').html("<img src='ajax-loader.gif' /> Loading...");_x000D_
   },_x000D_
   success : function(){_x000D_
    setInterval(function(){ $('#text').load("cd_catalog.txt"); },1000);_x000D_
   }_x000D_
  });_x000D_
 });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  _x000D_
<a href="http://www.wantyourhelp.com">[click to redirect][1]</a>_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

select DocumentFormat.OpenXml under references , view it's properties, and set the Copy Local option to True so that it copies it to the output folder. That worked for me.

Android Google Maps v2 - set zoom level for myLocation

Slightly different solution than HeatfanJohn's, where I change the zoom relatively to the current zoom level:

// Zoom out just a little
map.animateCamera(CameraUpdateFactory.zoomTo(map.getCameraPosition().zoom - 0.5f));

Use grep --exclude/--include syntax to not grep through certain files

The suggested command:

grep -Ir --exclude="*\.svn*" "pattern" *

is conceptually wrong, because --exclude works on the basename. Put in other words, it will skip only the .svn in the current directory.

Node JS Error: ENOENT

if your tmp folder is relative to the directory where your code is running remove the / in front of /tmp.

So you just have tmp/test.jpg in your code. This worked for me in a similar situation.

Xcode 9 error: "iPhone has denied the launch request"

This error occurred for me when upgrading an Xcode 8 project to run in Xcode 9, however the iOS Base SDK in the Build Settings is still at the previous version of iPhoneOS10.3.sdk and says SDK not found. However that application still builds and runs on a device but it fails to launch. Updating the iOS Base SDK to iOS 11.0 fixes this launch problem.

Usage of \b and \r in C

The interpretation of the backspace and carriage return characters is left to the software you use for display. A terminal emulator, when displaying \b would move the cursor one step back, and when displaying \r to the beginning of the line. If you print these characters somewhere else, like a text file, the software may choose. to do something else.

Swift apply .uppercaseString to only the first letter of a string

Swift 3 (xcode 8.3.3)

Uppercase all first characters of string

let str = "your string"
let capStr = str.capitalized

//Your String

Uppercase all characters

let str = "your string"
let upStr = str.uppercased()

//YOUR STRING

Uppercase only first character of string

 var str = "your string"
 let capStr = String(str.characters.prefix(1)).uppercased() + String(str.characters.dropFirst())

//Your string

Get text from pressed button

Try to use:

String buttonText = ((Button)v).getText().toString();

What does LayoutInflater in Android do?

here is an example for geting a refrence for the root View of a layout , inflating it and using it with setContentView(View view)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LayoutInflater li=getLayoutInflater();
    View rootView=li.inflate(R.layout.activity_main,null);
    setContentView(rootView);


}

jquery draggable: how to limit the draggable area?

$(function() { $( "#draggable" ).draggable({ containment: "window" }); });

of this code does not display. Full code and Demo: http://www.limitsizbilgi.com/div-tasima-surukle-birak-div-drag-and-drop-jquery.html

In order to limit the element inside its parent:

$( "#draggable" ).draggable({ containment: "window" });

How can I find the location of origin/master in git, and how do I change it?

[ Solution ]

$ git push origin

^ this solved it for me. What it did, it synchronized my master (on laptop) with "origin" that's on the remote server.

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

How to set Angular 4 background image?

This works for me:

put this in your markup:

<div class="panel panel-default" [ngStyle]="{'background-image': getUrl()}">

then in component:

getUrl()
{
  return "url('http://estringsoftware.com/wp-content/uploads/2017/07/estring-header-lowsat.jpg')";
}

C# How to change font of a label

I noticed there was not an actual full code answer, so as i come across this, i have created a function, that does change the font, which can be easily modified. I have tested this in

- XP SP3 and Win 10 Pro 64

private void SetFont(Form f, string name, int size, FontStyle style)
{
    Font replacementFont = new Font(name, size, style);
    f.Font = replacementFont;
}

Hint: replace Form to either Label, RichTextBox, TextBox, or any other relative control that uses fonts to change the font on them. By using the above function thus making it completely dynamic.

    /// To call the function do this.
    /// e.g in the form load event etc.

public Form1()
{
      InitializeComponent();
      SetFont(this, "Arial", 8, FontStyle.Bold);  
      // This sets the whole form and 
      // everything below it.
      // Shaun Cassidy.
}

You can also, if you want a full libary so you dont have to code all the back end bits, you can download my dll from Github.

Github DLL

/// and then import the namespace
using Droitech.TextFont;

/// Then call it using:
TextFontClass fClass = new TextFontClass();
fClass.SetFont(this, "Arial", 8, FontStyle.Bold);

Simple.

How to view table contents in Mysql Workbench GUI?

You have to open database connection, not workbench file with schema. It looks a bit wierd, but it makes sense when you realize what you are editing.

So, go to home tab, double click database connection (create it if you don't have it yet) and have fun.

Onclick event to remove default value in a text input field

You actually want to show a placeholder, HTML 5 offer this feature and it's very sweet !

Try this out :

<input name="Name" placeholder="Enter Your Name">

How can we print line numbers to the log in java

Log4J allows you to include the line number as part of its output pattern. See http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html for details on how to do this (the key element in the conversion pattern is "L"). However, the Javadoc does include the following:

WARNING Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue.

How can I use std::maps with user-defined types as key?

You don't have to define operator< for your class, actually. You can also make a comparator function object class for it, and use that to specialize std::map. To extend your example:

struct Class1Compare
{
   bool operator() (const Class1& lhs, const Class1& rhs) const
   {
       return lhs.id < rhs.id;
   }
};

std::map<Class1, int, Class1Compare> c2int;

It just so happens that the default for the third template parameter of std::map is std::less, which will delegate to operator< defined for your class (and fail if there is none). But sometimes you want objects to be usable as map keys, but you do not actually have any meaningful comparison semantics, and so you don't want to confuse people by providing operator< on your class just for that. If that's the case, you can use the above trick.

Yet another way to achieve the same is to specialize std::less:

namespace std
{
    template<> struct less<Class1>
    {
       bool operator() (const Class1& lhs, const Class1& rhs) const
       {
           return lhs.id < rhs.id;
       }
    };
}

The advantage of this is that it will be picked by std::map "by default", and yet you do not expose operator< to client code otherwise.

How do I download a file from the internet to my linux server with Bash

I guess you could use curl and wget, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.

Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx, a text based browser.

How to get ID of the last updated row in MySQL?

If you are only doing insertions, and want one from the same session, do as per peirix's answer. If you are doing modifications, you will need to modify your database schema to store which entry was most recently updated.

If you want the id from the last modification, which may have been from a different session (i.e. not the one that was just done by the PHP code running at present, but one done in response to a different request), you can add a TIMESTAMP column to your table called last_modified (see http://dev.mysql.com/doc/refman/5.1/en/datetime.html for information), and then when you update, set last_modified=CURRENT_TIME.

Having set this, you can then use a query like: SELECT id FROM table ORDER BY last_modified DESC LIMIT 1; to get the most recently modified row.

Is there a way to list open transactions on SQL Server 2000 database?

You can get all the information of active transaction by the help of below query

SELECT
trans.session_id AS [SESSION ID],
ESes.host_name AS [HOST NAME],login_name AS [Login NAME],
trans.transaction_id AS [TRANSACTION ID],
tas.name AS [TRANSACTION NAME],tas.transaction_begin_time AS [TRANSACTION 
BEGIN TIME],
tds.database_id AS [DATABASE ID],DBs.name AS [DATABASE NAME]
FROM sys.dm_tran_active_transactions tas
JOIN sys.dm_tran_session_transactions trans
ON (trans.transaction_id=tas.transaction_id)
LEFT OUTER JOIN sys.dm_tran_database_transactions tds
ON (tas.transaction_id = tds.transaction_id )
LEFT OUTER JOIN sys.databases AS DBs
ON tds.database_id = DBs.database_id
LEFT OUTER JOIN sys.dm_exec_sessions AS ESes
ON trans.session_id = ESes.session_id
WHERE ESes.session_id IS NOT NULL

and it will give below similar result enter image description here

and you close that transaction by the help below KILL query by refering session id

KILL 77

Deciding between HttpClient and WebClient

Perhaps you could think about the problem in a different way. WebClient and HttpClient are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient and HttpClient, and then use the IoC container to inject the implementation via config.

What this would allow you to do would be to switch between HttpClient and WebClient easily so that you are able to objectively test in the production environment.

So questions like:

Will HttpClient be a better design choice if we upgrade to .Net 4.5?

Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient or WebClient.

/// <summary>
/// Dependency Injection abstraction for rest clients. 
/// </summary>
public interface IClient
{
    /// <summary>
    /// Adapter for serialization/deserialization of http body data
    /// </summary>
    ISerializationAdapter SerializationAdapter { get; }

    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns></returns>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Default timeout for http requests
    /// </summary>
    TimeSpan Timeout { get; set; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    Uri BaseUri { get; set; }

    /// <summary>
    /// Name of the client
    /// </summary>
    string Name { get; }
}

public class Request<TRequestBody>
{
    #region Public Properties
    public IHeadersCollection Headers { get; }
    public Uri Resource { get; set; }
    public HttpRequestMethod HttpRequestMethod { get; set; }
    public TRequestBody Body { get; set; }
    public CancellationToken CancellationToken { get; set; }
    public string CustomHttpRequestMethod { get; set; }
    #endregion

    public Request(Uri resource,
        TRequestBody body,
        IHeadersCollection headers,
        HttpRequestMethod httpRequestMethod,
        IClient client,
        CancellationToken cancellationToken)
    {
        Body = body;
        Headers = headers;
        Resource = resource;
        HttpRequestMethod = httpRequestMethod;
        CancellationToken = cancellationToken;

        if (Headers == null) Headers = new RequestHeadersCollection();

        var defaultRequestHeaders = client?.DefaultRequestHeaders;
        if (defaultRequestHeaders == null) return;

        foreach (var kvp in defaultRequestHeaders)
        {
            Headers.Add(kvp);
        }
    }
}

public abstract class Response<TResponseBody> : Response
{
    #region Public Properties
    public virtual TResponseBody Body { get; }

    #endregion

    #region Constructors
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response() : base()
    {
    }

    protected Response(
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    TResponseBody body,
    Uri requestUri
    ) : base(
        headersCollection,
        statusCode,
        httpRequestMethod,
        responseData,
        requestUri)
    {
        Body = body;
    }

    public static implicit operator TResponseBody(Response<TResponseBody> readResult)
    {
        return readResult.Body;
    }
    #endregion
}

public abstract class Response
{
    #region Fields
    private readonly byte[] _responseData;
    #endregion

    #region Public Properties
    public virtual int StatusCode { get; }
    public virtual IHeadersCollection Headers { get; }
    public virtual HttpRequestMethod HttpRequestMethod { get; }
    public abstract bool IsSuccess { get; }
    public virtual Uri RequestUri { get; }
    #endregion

    #region Constructor
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response()
    {
    }

    protected Response
    (
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    Uri requestUri
    )
    {
        StatusCode = statusCode;
        Headers = headersCollection;
        HttpRequestMethod = httpRequestMethod;
        RequestUri = requestUri;
        _responseData = responseData;
    }
    #endregion

    #region Public Methods
    public virtual byte[] GetResponseData()
    {
        return _responseData;
    }
    #endregion
}

Full code

HttpClient Implementation

You can use Task.Run to make WebClient run asynchronously in its implementation.

Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient may work better for some customers, and HttpClient may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.

BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.

How to wait for 2 seconds?

How about this?

WAITFOR DELAY '00:00:02';

If you have "00:02" it's interpreting that as Hours:Minutes.

Express-js can't GET my static files, why?

this one worked for me

app.use(express.static(path.join(__dirname, 'public')));

app.use('/img',express.static(path.join(__dirname, 'public/images')));

app.use('/shopping-cart/javascripts',express.static(path.join(__dirname, 'public/javascripts')));

app.use('/shopping-cart/stylesheets',express.static(path.join(__dirname, 'public/stylesheets')));

app.use('/user/stylesheets',express.static(path.join(__dirname, 'public/stylesheets')));

app.use('/user/javascripts',express.static(path.join(__dirname, 'public/javascripts')));

How to have a a razor action link open in a new tab?

With Named arguments:

@Html.ActionLink(linkText: "TestTab", actionName: "TestAction", controllerName: "TestController", routeValues: null, htmlAttributes: new { target = "_blank"})

How to get the selected radio button value using js

A simpler way of doing this is to use a global js variable that simply holds the id of the clicked radio button. Then you don't have to waste code spinning thru your radio lists looking for the selected value. I have done this in cases where I have a dynamically generated list of 100 or more radio buttons. spinning thru them is (almost imperceptible) slow, but this is an easier solution.

you can also do this with the id, but you usually just want the value.

<script>
var gRadioValue = ''; //global declared outside of function
function myRadioFunc(){
    var radioVal = gRadioValue;  
    // or maybe: var whichRadio = document.getElementById(gWhichCheckedId);
    //do somethign with radioVal
}
<script>

<input type="radio" name="rdo" id="rdo1" value="1" onClick="gRadioValue =this.value;"> One
<input type="radio" name="rdo" id="rdo2" value="2" onClick="gRadioValue =this.value;"> Two
...
<input type="radio" name="rdo" id="rdo99" value="99" onClick="gRadioValue =this.value;"> 99

Get an object attribute

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

How to store Query Result in variable using mysql

Select count(*) from table_name into @var1; 
Select @var1;

How can I convert a long to int in Java?

I Also Faced This Problem. To Solve This I have first converted my long to String then to int.

int i = Integer.parseInt(String.valueOf(long));

base_url() function not working in codeigniter

First of all load URL helper. you can load in "config/autoload.php" file and add following code $autoload['helper'] = array('url');

or in controller add following code

$this->load->helper('url');

then go to config.php in cofig folder and set

$config['base_url'] = 'http://urlbaseurl.com/';

hope this will help thanks

C - error: storage size of ‘a’ isn’t known

Say it like this: struct xyx a;

CSS how to make scrollable list

As per your question vertical listing have a scrollbar effect.

CSS / HTML :

_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8">_x000D_
        <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <header>header area</header>_x000D_
        <nav>_x000D_
            <ul>_x000D_
                <li>Link 1</li>_x000D_
                <li>Link 2</li>_x000D_
                <li>Link 3</li>_x000D_
                <li>Link 4</li>_x000D_
                <li>Link 5</li>_x000D_
                <li>Link 6</li> _x000D_
                <li>Link 7</li> _x000D_
                <li>Link 8</li>_x000D_
                <li>Link 9</li>_x000D_
                <li>Link 10</li>_x000D_
                <li>Link 11</li>_x000D_
                <li>Link 13</li>_x000D_
                <li>Link 13</li>_x000D_
_x000D_
            </ul>_x000D_
        </nav>_x000D_
        _x000D_
        <footer>footer area</footer>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Resolve promises one after another (i.e. in sequence)?

This is to extend on how to process a sequence of promises in a more generic way, supporting dynamic / infinite sequences, based on spex.sequence implementation:

var $q = require("q");
var spex = require('spex')($q);

var files = []; // any dynamic source of files;

var readFile = function (file) {
    // returns a promise;
};

function source(index) {
    if (index < files.length) {
        return readFile(files[index]);
    }
}

function dest(index, data) {
    // data = resolved data from readFile;
}

spex.sequence(source, dest)
    .then(function (data) {
        // finished the sequence;
    })
    .catch(function (error) {
        // error;
    });

Not only this solution will work with sequences of any size, but you can easily add data throttling and load balancing to it.

Sending Multipart File as POST parameters with RestTemplate requests

I recently struggled with this issue for 3 days. How the client is sending the request might not be the cause, the server might not be configured to handle multipart requests. This is what I had to do to get it working:

pom.xml - Added commons-fileupload dependency (download and add the jar to your project if you are not using dependency management such as maven)

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>${commons-version}</version>
</dependency>

web.xml - Add multipart filter and mapping

<filter>
  <filter-name>multipartFilter</filter-name>
  <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>multipartFilter</filter-name>
  <url-pattern>/springrest/*</url-pattern>
</filter-mapping>

app-context.xml - Add multipart resolver

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <beans:property name="maxUploadSize">
        <beans:value>10000000</beans:value>
    </beans:property>
</beans:bean>

Your Controller

@RequestMapping(value=Constants.REQUEST_MAPPING_ADD_IMAGE, method = RequestMethod.POST, produces = { "application/json"})
public @ResponseBody boolean saveStationImage(
        @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_FILE) MultipartFile file,
        @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_URI) String imageUri, 
        @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_TYPE) String imageType, 
        @RequestParam(value = Constants.MONGO_FIELD_STATION_ID) String stationId) {
    // Do something with file
    // Return results
}

Your client

public static Boolean updateStationImage(StationImage stationImage) {
    if(stationImage == null) {
        Log.w(TAG + ":updateStationImage", "Station Image object is null, returning.");
        return null;
    }

    Log.d(TAG, "Uploading: " + stationImage.getImageUri());
    try {
        RestTemplate restTemplate = new RestTemplate();
        FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
        formConverter.setCharset(Charset.forName("UTF8"));
        restTemplate.getMessageConverters().add(formConverter);
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));

        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();

        parts.add(Constants.STATION_PROFILE_IMAGE_FILE, new FileSystemResource(stationImage.getImageFile()));
        parts.add(Constants.STATION_PROFILE_IMAGE_URI, stationImage.getImageUri());
        parts.add(Constants.STATION_PROFILE_IMAGE_TYPE, stationImage.getImageType());
        parts.add(Constants.FIELD_STATION_ID, stationImage.getStationId());

        return restTemplate.postForObject(Constants.REST_CLIENT_URL_ADD_IMAGE, parts, Boolean.class);
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));

        Log.e(TAG + ":addStationImage", sw.toString());
    }

    return false;
}

That should do the trick. I added as much information as possible because I spent days, piecing together bits and pieces of the full issue, I hope this will help.

How can I select from list of values in Oracle

You don't need to create any stored types, you can evaluate Oracle's built-in collection types.

select distinct column_value from table(sys.odcinumberlist(1,1,2,3,3,4,4,5))

How to set Grid row and column positions programmatically

Here is an example which might help someone:

Grid test = new Grid();
test.ColumnDefinitions.Add(new ColumnDefinition());
test.ColumnDefinitions.Add(new ColumnDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());

Label t1 = new Label();
t1.Content = "Test1";
Label t2 = new Label();
t2.Content = "Test2";
Label t3 = new Label();
t3.Content = "Test3";
Label t4 = new Label();
t4.Content = "Test4";
Label t5 = new Label();
t5.Content = "Test5";
Label t6 = new Label();
t6.Content = "Test6";

Grid.SetColumn(t1, 0);
Grid.SetRow(t1, 0);
test.Children.Add(t1);

Grid.SetColumn(t2, 1);
Grid.SetRow(t2, 0);
test.Children.Add(t2);

Grid.SetColumn(t3, 0);
Grid.SetRow(t3, 1);
test.Children.Add(t3);

Grid.SetColumn(t4, 1);
Grid.SetRow(t4, 1);
test.Children.Add(t4);

Grid.SetColumn(t5, 0);
Grid.SetRow(t5, 2);
test.Children.Add(t5);

Grid.SetColumn(t6, 1);
Grid.SetRow(t6, 2);
test.Children.Add(t6);

MVC - Set selected value of SelectList

I needed a dropdown in a editable grid myself with preselected dropdown values. Afaik, the selectlist data is provided by the controller to the view, so it is created before the view consumes it. Once the view consumes the SelectList, I hand it over to a custom helper that uses the standard DropDownList helper. So, a fairly light solution imo. Guess it fits in the ASP.Net MVC spirit at the time of writing; when not happy roll your own...

public static string DropDownListEx(this HtmlHelper helper, string name, SelectList selectList, object selectedValue)
{
    return helper.DropDownList(name, new SelectList(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectedValue));
}

Displaying a 3D model in JavaScript/HTML5

I also needed what you've been searching for and did some research.

I found JSC3D (https://code.google.com/p/jsc3d/). It's a project written entirely in Javascript and uses the HTML canvas. It has been tested for Opera, Chrome, Firefox, Safari, IE9 and more.

Then you have services as p3d.in and Sketchfab that give you a nice reader to view 3D models on a web page: they use HTML5 and WebGL. They both have a free version.

String to date in Oracle with milliseconds

I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.

CodeIgniter activerecord, retrieve last insert id?

List of details which helps in requesting id and queries are

For fetching Last inserted Id :This will fetching the last records from the table

$this->db->insert_id(); 

Fetching SQL query add this after modal request

$this->db->last_query()

React Native add bold or italics to single words in <Text> field

Bold text:

<Text>
  <Text>This is a sentence</Text>
  <Text style={{fontWeight: "bold"}}> with</Text>
  <Text> one word in bold</Text>
</Text>

Italic text:

<Text>
  <Text>This is a sentence</Text>
  <Text style={{fontStyle: "italic"}}> with</Text>
  <Text> one word in italic</Text>
</Text>

How do I copy the contents of a String to the clipboard in C#?

In Windows Forms, if your string is in a textbox, you can easily use this:

textBoxcsharp.SelectAll();
textBoxcsharp.Copy();
textBoxcsharp.DeselectAll();

Truncating long strings with CSS: feasible yet?

If you're OK with a JavaScript solution, there's a jQuery plug-in to do this in a cross-browser fashion - see http://azgtech.wordpress.com/2009/07/26/text-overflow-ellipsis-for-firefox-via-jquery/

How do I print part of a rendered HTML page in JavaScript?

Along the same lines as some of the suggestions you would need to do at least the following:

  • Load some CSS dynamically through JavaScript
  • Craft some print-specific CSS rules
  • Apply your fancy CSS rules through JavaScript

An example CSS could be as simple as this:

@media print {
  body * {
    display:none;
  }

  body .printable {
    display:block;
  }
}

Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.

<script type="text/javascript">
  function divPrint() {
    // Some logic determines which div should be printed...
    // This example uses div3.
    $("#div3").addClass("printable");
    window.print();
  }
</script>

You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.

Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to load the CSS dynamically like in this answer.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Print Portion Example</title>
    <style type="text/css">
      @media print {
        body * {
          display:none;
        }

        body .printable {
          display:block;
        }
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  </head>

  <body>
    <h1>Print Section Example</h1>
    <div id="div1">Div 1</div>
    <div id="div2">Div 2</div>
    <div id="div3">Div 3</div>
    <div id="div4">Div 4</div>
    <div id="div5">Div 5</div>
    <div id="div6">Div 6</div>
    <p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
    <script type="text/javascript">
      function divPrint() {
        // Some logic determines which div should be printed...
        // This example uses div3.
        $("#div3").addClass("printable");
        window.print();
      }
    </script>
  </body>
</html>

Magento: Set LIMIT on collection

Order Collection Limit :

$orderCollection = Mage::getResourceModel('sales/order_collection'); 
$orderCollection->getSelect()->limit(10);

foreach ($orderCollection->getItems() as $order) :
   $orderModel = Mage::getModel('sales/order');
   $order =   $orderModel->load($order['entity_id']);
   echo $order->getId().'<br>'; 
endforeach; 

On Duplicate Key Update same as insert

Here is a solution to your problem:

I've tried to solve problem like yours & I want to suggest to test from simple aspect.

Follow these steps: Learn from simple solution.

Step 1: Create a table schema using this SQL Query:

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` varchar(32) NOT NULL,
  `status` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `no_duplicate` (`username`,`password`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

A table <code>user</code> with data

Step 2: Create an index of two columns to prevent duplicate data using following SQL Query:

ALTER TABLE `user` ADD INDEX no_duplicate (`username`, `password`);

or, Create an index of two column from GUI as follows: Create index from GUI Select columns to create index Indexes of table <code>user</code>

Step 3: Update if exist, insert if not using following queries:

INSERT INTO `user`(`username`, `password`) VALUES ('ersks','Nepal') ON DUPLICATE KEY UPDATE `username`='master',`password`='Nepal';

INSERT INTO `user`(`username`, `password`) VALUES ('master','Nepal') ON DUPLICATE KEY UPDATE `username`='ersks',`password`='Nepal';

Table <code>user</code> after running above query

How to include css files in Vue 2

Try using the @ symbol before the url string. Import your css in the following manner:

import Vue from 'vue'

require('@/assets/styles/main.css')

In your App.vue file you can do this to import a css file in the style tag

<template>
  <div>
  </div>
</template>

<style scoped src="@/assets/styles/mystyles.css">
</style>

php - add + 7 days to date format mm dd, YYYY

The "+1 month" issue with strtotime

As noted in several blogs, strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

$dt = date("Y-m-d");
echo date( "Y-m-d", strtotime( "$dt +1 day" ) ); // PHP:  2009-03-04
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP:  2009-03-31

ASP.Net which user account running Web Service on IIS 7?

I had a ton of trouble with this and then found a great solution:

Create a file in a text editor called whoami.php with the below code as it's content, save the file and upload it to public_html (or whatever you root of your webserver directory is named). It should output a useful string that you can use to track down the user the webserver is running as, my output was "php is running as user: nt authority\iusr" which allowed me to track down the permissions I needed to modify to the user "IUSR".

<?php
  // outputs the username that owns the running php/httpd process
  // (on a system with the "whoami" executable in the path)
  echo 'php is running as user: ' . exec('whoami');
?>

Get MAC address using shell script

Get MAC adress for eth0:

$ cat /etc/sysconfig/network-scripts/ifcfg-eth0 | grep HWADDR | cut -c 9-25

Example:

[me@machine ~]$ cat /etc/sysconfig/network-scripts/ifcfg-eth0 | grep HWADDR | cut -c 9-25
55:b5:00:10:be:10

Passing HTML to template using Flask/Jinja2

When you have a lot of variables that don't need escaping, you can use an autoescape block:

{% autoescape off %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}

How do I remove objects from an array in Java?

Assign null to the array locations.

How do you redirect to a page using the POST verb?

try this one

return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");

How to add a border just on the top side of a UIView

extension UIView {

    func addBorder(edge: UIRectEdge, color: UIColor, borderWidth: CGFloat) {

        let seperator = UIView()
        self.addSubview(seperator)
        seperator.translatesAutoresizingMaskIntoConstraints = false

        seperator.backgroundColor = color

        if edge == .top || edge == .bottom
        {
            seperator.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
            seperator.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
            seperator.heightAnchor.constraint(equalToConstant: borderWidth).isActive = true

            if edge == .top
            {
                seperator.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            }
            else
            {
                seperator.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            }
        }
        else if edge == .left || edge == .right
        {
            seperator.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            seperator.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            seperator.widthAnchor.constraint(equalToConstant: borderWidth).isActive = true

            if edge == .left
            {
                seperator.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
            }
            else
            {
                seperator.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
            }
        }
    }

}

remove None value from a list without removing the 0 value

A list comprehension is likely the cleanest way:

>>> L = [0, 23, 234, 89, None, 0, 35, 9
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

There is also a functional programming approach but it is more involved:

>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(partial(is_not, None), L))
[0, 23, 234, 89, 0, 35, 9]

PHP Redirect with POST data

You can let PHP do a POST, but then your php will get the return, with all sorts of complications. I think the simplest would be to actually let the user do the POST.

So, kind-of what you suggested, you'll get indeed this part:

Customer fill detail in Page A, then in Page B we create another page show all the customer detail there, click a CONFIRM button then POST to Page C.

But you can actually do a javascript submit on page B, so there is no need for a click. Make it a "redirecting" page with a loading animation, and you're set.

How do I resolve ClassNotFoundException?

If you have added multiple (Third-Party)**libraries and Extends **Application class

Then it might occur.

For that, you have to set multiDexEnabled true and replace your extended Application class with MultiDexApplication.

It will be solved.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

returns true if subject is between low and high (inclusive)

$between = function( $low, $high, $subject ) {
    if( $subject < $low ) return false;
    if( $subject > $high ) return false;
    return true;
};

if( $between( 0, 100, $givenNumber )) {
   // do whatever...
}

looks cleaner to me

AngularJs $http.post() does not send data

use this way. no need to write so much

 isAuth = $http.post("Yr URL", {username: username, password: password});

and in the nodejs back end

app.post("Yr URL",function(req,resp)
{

  var username = req.body.username||req.param('username');
  var password = req.body.password||req.param('password');
}

I hope this helps

How do I configure Apache 2 to run Perl CGI scripts?

I'm guessing you've taken a look at mod_perl?

Have you tried the following tutorial?

EDIT: In relation to your posting - perhaps you could include a sample of the code inside your .cgi file. Perhaps even the first few lines?

Setting width and height

This helped in my case:

options: {
    responsive: true,
    scales: {
        yAxes: [{
            display: true,
            ticks: {
                min:0,
                max:100
            }
        }]
    }
}

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Like the previous comment mention, the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." its a warning because you are missunderstanding this line: mongoose.connect('mongodb://localhost/info'); and browsing this url: http://localhost:28017/

However, if you want to see the mongo's admin web page, you could do it, with this command:

mongod --rest --httpinterface

browsing this url: http://localhost:28017/

the parameter httpinterface activate the admin web page, and the parameter rest its needed for activate the rest services the page require

Check/Uncheck checkbox with JavaScript

function setCheckboxValue(checkbox,value) {
    if (checkbox.checked!=value)
        checkbox.click();
}

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

What happens when a duplicate key is put into a HashMap?

         HashMap<Emp, Emp> empHashMap = new HashMap<Emp, Emp>();

         empHashMap.put(new Emp(1), new Emp(1));
         empHashMap.put(new Emp(1), new Emp(1));
         empHashMap.put(new Emp(1), new Emp());
         empHashMap.put(new Emp(1), new Emp());
         System.out.println(empHashMap.size());
    }
}

class Emp{
    public Emp(){   
    }
    public Emp(int id){
        this.id = id;
    }
    public int id;
    @Override
    public boolean equals(Object obj) {
        return this.id == ((Emp)obj).id;
    }

    @Override
    public int hashCode() {
        return id;
    }
}


OUTPUT : is 1

Means hash map wont allow duplicates, if you have properly overridden equals and hashCode() methods.

HashSet also uses HashMap internally, see the source doc

public class HashSet{
public HashSet() {
        map = new HashMap<>();
    }
}

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

GitLab remote: HTTP Basic: Access denied and fatal Authentication

If you are using git > 2.11 and using Kerberos to interact with Gitlab you need set this configuration in your local git to avoid the remote: HTTP Basic: Access denied error.

$ git config --global http.emptyAuth true

Source

CSS table layout: why does table-row not accept a margin?

The closest thing I've seen would be to set border-spacing: 0 30px; to the container div. However, this just leaves me with space on the upper edge of the table, which defeats the purpose, since you wanted margin-bottom.

How to get the current plugin directory in WordPress?

Why not use the WordPress core function that's designed specifically for that purpose?

<?php plugin_dir_path( __FILE__ ); ?>

See Codex documentation here.

You also have

<?php plugin_dir_url( __FILE__ ); ?>

if what you're looking for is a URI as opposed to a server path.

See Codex documentation here.

IMO it's always best to use the highest-level method that's available in core, and this is it. It makes your code more future proof.

Is it possible to find out the users who have checked out my project on GitHub?

If by "checked out" you mean people who have cloned your project, then no it is not possible. You don't even need to be a GitHub user to clone a repository, so it would be infeasible to track this.

Quick easy way to migrate SQLite3 to MySQL?

This simple solution worked for me:

<?php
$sq = new SQLite3( 'sqlite3.db' );

$tables = $sq->query( 'SELECT name FROM sqlite_master WHERE type="table"' );

while ( $table = $tables->fetchArray() ) {
    $table = current( $table );
    $result = $sq->query( sprintf( 'SELECT * FROM %s', $table ) );

    if ( strpos( $table, 'sqlite' ) !== false )
        continue;

    printf( "-- %s\n", $table );
    while ( $row = $result->fetchArray( SQLITE3_ASSOC ) ) {
        $values = array_map( function( $value ) {
            return sprintf( "'%s'", mysql_real_escape_string( $value ) );
        }, array_values( $row ) );
        printf( "INSERT INTO `%s` VALUES( %s );\n", $table, implode( ', ', $values ) );
    }
}

How to install gdb (debugger) in Mac OSX El Capitan?

It seems that MacPorts could be installed in El Capitan right now: https://www.macports.org/install.php Then you probably can install gdb by link you mentioned.

Filtering a spark dataframe based on date

Don't use this as suggested in other answers

.filter(f.col("dateColumn") < f.lit('2017-11-01'))

But use this instead

.filter(f.col("dateColumn") < f.unix_timestamp(f.lit('2017-11-01 00:00:00')).cast('timestamp'))

This will use the TimestampType instead of the StringType, which will be more performant in some cases. For example Parquet predicate pushdown will only work with the latter.

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

The latest version of the pipeline sh step allows you to do the following;

// Git committer email
GIT_COMMIT_EMAIL = sh (
    script: 'git --no-pager show -s --format=\'%ae\'',
    returnStdout: true
).trim()
echo "Git committer email: ${GIT_COMMIT_EMAIL}"

Another feature is the returnStatus option.

// Test commit message for flags
BUILD_FULL = sh (
    script: "git log -1 --pretty=%B | grep '\\[jenkins-full]'",
    returnStatus: true
) == 0
echo "Build full flag: ${BUILD_FULL}"

These options where added based on this issue.

See official documentation for the sh command.

For declarative pipelines (see comments), you need to wrap code into script step:

script {
   GIT_COMMIT_EMAIL = sh (
        script: 'git --no-pager show -s --format=\'%ae\'',
        returnStdout: true
    ).trim()
    echo "Git committer email: ${GIT_COMMIT_EMAIL}"
}

fetch gives an empty response body

In many case you will need to add the bodyParser module in your express node app. Then in your app.use part below app.use(express.static('www')); add these 2 lines app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json());

Disable sorting for a particular column in jQuery DataTables

If you already have to hide Some columns, like I hide last name column. I just had to concatenate fname , lname , So i made query but hide that column from front end. The modifications in Disable sorting in such situation are :

    "aoColumnDefs": [
        { 'bSortable': false, 'aTargets': [ 3 ] },
        {
            "targets": [ 4 ],
            "visible": false,
            "searchable": true
        }
    ],

Notice that I had Hiding functionality here

    "columnDefs": [
            {
                "targets": [ 4 ],
                "visible": false,
                "searchable": true
            }
        ],

Then I merged it into "aoColumnDefs"

Writing to a TextBox from another thread?

Most simple, without caring about delegates

if(textBox1.InvokeRequired == true)
    textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});

else
    textBox1.Text = "Invoke was NOT needed"; 

Unable to start Service Intent

1) check if service declaration in manifest is nested in application tag

<application>
    <service android:name="" />
</application>

2) check if your service.java is in the same package or diff package as the activity

<application>
    <!-- service.java exists in diff package -->
    <service android:name="com.package.helper.service" /> 
</application>
<application>
    <!-- service.java exists in same package -->
    <service android:name=".service" /> 
</application>

How to create a DataFrame of random integers with Pandas?

numpy.random.randint accepts a third argument (size) , in which you can specify the size of the output array. You can use this to create your DataFrame -

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Here - np.random.randint(0,100,size=(100, 4)) - creates an output array of size (100,4) with random integer elements between [0,100) .


Demo -

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

which produces:

     A   B   C   D
0   45  88  44  92
1   62  34   2  86
2   85  65  11  31
3   74  43  42  56
4   90  38  34  93
5    0  94  45  10
6   58  23  23  60
..  ..  ..  ..  ..

Selecting a Linux I/O Scheduler

The Linux Kernel does not automatically change the IO Scheduler at run-time. By this I mean, the Linux kernel, as of today, is not able to automatically choose an "optimal" scheduler depending on the type of secondary storage devise. During start-up, or during run-time, it is possible to change the IO scheduler manually.

The default scheduler is chosen at start-up based on the contents in the file located at /linux-2.6 /block/Kconfig.iosched. However, it is possible to change the IO scheduler during run-time by echoing a valid scheduler name into the file located at /sys/block/[DEV]/queue/scheduler. For example, echo deadline > /sys/block/hda/queue/scheduler

How do you fade in/out a background color using jquery?

I know that the question was how to do it with Jquery, but you can achieve the same affect with simple css and just a little jquery...

For example, you have a div with 'box' class, add the following css

.box {
background-color: black;
-webkit-transition: background 0.5s linear;
-moz-transition: background 0.5s linear;
-ms-transition: background 0.5s linear;
-o-transition: background 0.5s linear;
transition: background 0.5s linear;
}

and then use AddClass function to add another class with different background color like 'box highlighted' or something like that with the following css:

.box.highlighted {
  background-color: white;
}

I am a beginner and maybe there are some disadvantages of this method but maybe it'll be helpful for somebody

Here's a codepen: https://codepen.io/anon/pen/baaLYB

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

Automatically get loop index in foreach loop in Perl

Well, there is this way:

use List::Rubyish;

$list = List::Rubyish->new( [ qw<a b c> ] );
$list->each_index( sub { say "\$_=$_" } );

See List::Rubyish.

How can I remove all files in my git repo and update/push from my local git repo?

Warning: this will delete your files, make sure you have a backup or can revert the commit.

Delete all elements in repository:

$ git rm -r *

then:

$ git commit -m 'Delete all the stuff'

Find a string between 2 known values

A Regex approach using lazy match and back-reference:

foreach (Match match in Regex.Matches(
        "morenonxmldata<tag1>0002</tag1>morenonxmldata<tag2>abc</tag2>asd",
        @"<([^>]+)>(.*?)</\1>"))
{
    Console.WriteLine("{0}={1}",
        match.Groups[1].Value,
        match.Groups[2].Value);
}

List files ONLY in the current directory

import os
for subdir, dirs, files in os.walk('./'):
    for file in files:
      do some stuff
      print file

You can improve this code with del dirs[:]which will be like following .

import os
for subdir, dirs, files in os.walk('./'):
    del dirs[:]
    for file in files:
      do some stuff
      print file

Or even better if you could point os.walk with current working directory .

import os
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd, topdown=True):
    del dirs[:]  # remove the sub directories.
    for file in files:
      do some stuff
      print file

Angular 2 change event on every keypress

Use ngModelChange by breaking up the [(x)] syntax into its two pieces, i.e., property databinding and event binding:

<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />
{{mymodel}}
valuechange(newValue) {
  mymodel = newValue;
  console.log(newValue)
}

It works for the backspace key too.

Get width in pixels from element with style set with %?

Try jQuery:

$("#banner-contenedor").width();

create multiple tag docker image

You can't create tags with Dockerfiles but you can create multiple tags on your images via the command line.

Use this to list your image ids:

$ docker images

Then tag away:

$ docker tag 9f676bd305a4 ubuntu:13.10
$ docker tag 9f676bd305a4 ubuntu:saucy
$ docker tag eb601b8965b8 ubuntu:raring
...

How to get request URI without context path?

getPathInfo() sometimes return null. In documentation HttpServletRequest

This method returns null if there was no extra path information.

I need get path to file without context path in Filter and getPathInfo() return me null. So I use another method: httpRequest.getServletPath()

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String newPath = parsePathToFile(httpRequest.getServletPath());
    ...

}

Two decimal places using printf( )

For %d part refer to this How does this program work? and for decimal places use %.2f

Casting interfaces for deserialization in JSON.NET

To enable deserialization of multiple implementations of interfaces, you can use JsonConverter, but not through an attribute:

Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Converters.Add(new DTOJsonConverter());
Interfaces.IEntity entity = serializer.Deserialize(jsonReader);

DTOJsonConverter maps each interface with a concrete implementation:

class DTOJsonConverter : Newtonsoft.Json.JsonConverter
{
    private static readonly string ISCALAR_FULLNAME = typeof(Interfaces.IScalar).FullName;
    private static readonly string IENTITY_FULLNAME = typeof(Interfaces.IEntity).FullName;


    public override bool CanConvert(Type objectType)
    {
        if (objectType.FullName == ISCALAR_FULLNAME
            || objectType.FullName == IENTITY_FULLNAME)
        {
            return true;
        }
        return false;
    }

    public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
    {
        if (objectType.FullName == ISCALAR_FULLNAME)
            return serializer.Deserialize(reader, typeof(DTO.ClientScalar));
        else if (objectType.FullName == IENTITY_FULLNAME)
            return serializer.Deserialize(reader, typeof(DTO.ClientEntity));

        throw new NotSupportedException(string.Format("Type {0} unexpected.", objectType));
    }

    public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

DTOJsonConverter is required only for the deserializer. The serialization process is unchanged. The Json object do not need to embed concrete types names.

This SO post offers the same solution one step further with a generic JsonConverter.

Return JSON response from Flask view

If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files and pass it to the summary function.

from flask import request, jsonify
from werkzeug import secure_filename

@app.route('/summary', methods=['GET', 'POST'])
def summary():
    if request.method == 'POST':
        csv = request.files['data']
        return jsonify(
            summary=make_summary(csv),
            csv_name=secure_filename(csv.filename)
        )

    return render_template('submit_data.html')

Replace the 'data' key for request.files with the name of the file input in your HTML form.

Python, compute list difference

When having a look at TimeComplexity of In-operator, in worst case it works with O(n). Even for Sets.

So when comparing two arrays we'll have a TimeComplexity of O(n) in best case and O(n^2) in worst case.

An alternative (but unfortunately more complex) solution, which works with O(n) in best and worst case is this one:

# Compares the difference of list a and b
# uses a callback function to compare items
def diff(a, b, callback):
  a_missing_in_b = []
  ai = 0
  bi = 0

  a = sorted(a, callback)
  b = sorted(b, callback)

  while (ai < len(a)) and (bi < len(b)):

    cmp = callback(a[ai], b[bi])
    if cmp < 0:
      a_missing_in_b.append(a[ai])
      ai += 1
    elif cmp > 0:
      # Item b is missing in a
      bi += 1
    else:
      # a and b intersecting on this item
      ai += 1
      bi += 1

  # if a and b are not of same length, we need to add the remaining items
  for ai in xrange(ai, len(a)):
    a_missing_in_b.append(a[ai])


  return a_missing_in_b

e.g.

>>> a=[1,2,3]
>>> b=[2,4,6]
>>> diff(a, b, cmp)
[1, 3]

Initialize 2D array

You can use for loop if you really want to.

char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
     table[i/row][i % col] = char('a' + (i+1));
}

or do what bhesh said.

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Actually your Windows firewall is blocking the connection. You need to enter these commands into cmd.exe from Administrator.

netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=tcp
netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=udp

In case something goes wrong then you can revert by this:

netsh advfirewall firewall delete rule name="FTP" program=%SystemRoot%\System32\ftp.exe

Disable ONLY_FULL_GROUP_BY

Give this a try:

SET sql_mode = ''

Community Note: As pointed out in the answers below, this actually clears all the SQL modes currently enabled. That may not necessarily be what you want.

How to copy to clipboard using Access/VBA?

VB 6 provides a Clipboard object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.

If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.

However, a simpler alternative is to use the DataObject class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.

For example, to place some text on the clipboard, you could use the following code:

Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"
clipboard.PutInClipboard

Or, to copy text from the clipboard into a string variable:

Dim clipboard As MSForms.DataObject
Dim strContents As String

Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

You can use the "filter" filter in your controller to get all the "C" grades. Getting the first element of the result array will give you the title of the subject that has grade "C".

$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];

http://jsbin.com/ewitun/1/edit

The same with plain ES6:

$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]

How to extract epoch from LocalDate and LocalDateTime?

The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance.

LocalDate

LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();

LocalDateTime

LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();

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

You can use union method for sets: set.union(other_set)

Note that it returns a new set i.e it doesn't modify itself.

Check if a variable exists in a list in Bash

I find it's easier to use the form echo $LIST | xargs -n1 echo | grep $VALUE as illustrated below:

LIST="ITEM1 ITEM2"
VALUE="ITEM1"
if [ -n "`echo $LIST | xargs -n1 echo | grep -e \"^$VALUE`$\" ]; then
    ...
fi

This works for a space-separated list, but you could adapt it to any other delimiter (like :) by doing the following:

LIST="ITEM1:ITEM2"
VALUE="ITEM1"
if [ -n "`echo $LIST | sed 's|:|\\n|g' | grep -e \"^$VALUE`$\"`" ]; then
   ...
fi

Note that the " are required for the test to work.

Predefined type 'System.ValueTuple´2´ is not defined or imported

The ValueTuple types are built into newer frameworks:

  • .NET Framework 4.7
  • .NET Core 2.0
  • Mono 5.0
  • .Net Standard 2.0

Until you target one of those newer framework versions, you need to reference the ValueTuple package.

More details at http://blog.monstuff.com/archives/2017/03/valuetuple-availability.html

set environment variable in python script

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

Rolling back bad changes with svn in Eclipse

You have two choices to do this.

The Quick and Dirty is selecting your files (using ctrl) in Project Explorer view, right-click them, choose Replace with... and then you choose the best option for you, from Latest from Repository, or some Branch version. After getting those files you modify them (with a space, or fix something, your call and commit them to create a newer revision.

A more clean way is choosing Merge at team menu and navigate through the wizard that will help you to recovery the old version in the actual revision.

Both commands have their command-line equivalents: svn revert and svn merge.

How can I get the current PowerShell executing file?

While the current Answer is right in most cases, there are certain situations that it will not give you the correct answer. If you use inside your script functions then:

$MyInvocation.MyCommand.Name 

Returns the name of the function instead name of the name of the script.

function test {
    $MyInvocation.MyCommand.Name
}

Will give you "test" no matter how your script is named. The right command for getting the script name is always

$MyInvocation.ScriptName

this returns the full path of the script you are executing. If you need just the script filename than this code should help you:

split-path $MyInvocation.PSCommandPath -Leaf

A button to start php script, how?

This one works for me:

index.php

    <?php
       if(isset($_GET['action']))
              {
                 //your code
                 echo 'Welcome';
              }
    ?>


    <form id="frm" method="post"  action="?action" >
    <input type="submit" value="Submit" id="submit" />
    </form>

This link can be helpful:

https://blogs.msdn.microsoft.com/brian_swan/2010/02/08/getting-started-with-the-sql-server-driver-for-php/

Using :after to clear floating elements

No, you don't it's enough to do something like this:

<ul class="clearfix">
  <li>one</li>
  <li>two></li>
</ul>

And the following CSS:

ul li {float: left;}


.clearfix:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}

.clearfix {
  display: inline-block;
}

html[xmlns] .clearfix {
   display: block;
}

* html .clearfix {
   height: 1%;
}

Change the background color of a pop-up dialog

To expand on @DaneWhite's answer, you don't have to rely on the built-in themes. You can easily supply your own style:

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:background">@color/myColor</item>
</style>

and then apply it in the Builder constructor:

Java:

AlertDialog alertDialog = new AlertDialog.Builder(getContext(), R.style.MyDialogTheme)
        ...
        .create();

Kotlin:

var alertDialog = AlertDialog.Builder(context, R.style.MyDialogTheme)
        ...
        .create()

This should work whether you are using android.support.v7.app.AlertDialog or android.app.AlertDialog

This also works better than @DummyData's answer because you don't resize the dialog. If you set window's background drawable you overwrite some existing dimensional information and get a dialog that is not standard width.

If you set background on theme and the set the theme on dialog you'll end up with a dialog that is colored how you want but still the correct width.

Verify object attribute value with mockito

This is answer based on answer from iraSenthil but with annotation (Captor). In my opinion it has some advantages:

  • it's shorter
  • it's easier to read
  • it can handle generics without warnings

Example:

@RunWith(MockitoJUnitRunner.class)
public class SomeTest{

    @Captor
    private ArgumentCaptor<List<SomeType>> captor;

    //...

    @Test 
    public void shouldTestArgsVals() {
        //...
        verify(mockedObject).someMethodOnMockedObject(captor.capture());

        assertThat(captor.getValue().getXXX(), is("expected"));
    }
}

AngularJS- Login and Authentication in each route and controller

You can use resolve:

angular.module('app',[])
.config(function($routeProvider)
{
    $routeProvider
    .when('/', {
        templateUrl  : 'app/views/login.html',
        controller   : 'YourController',
        controllerAs : 'Your',
        resolve: {
            factory : checkLoginRedirect
        }
    })
}

And, the function of the resolve:

function checkLoginRedirect($location){

    var user = firebase.auth().currentUser;

    if (user) {
        // User is signed in.
        if ($location.path() == "/"){
            $location.path('dash'); 
        }

        return true;
    }else{
        // No user is signed in.
        $location.path('/');
        return false;
    }   
}

Firebase also has a method that helps you install an observer, I advise installing it inside a .run:

.run(function(){

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            console.log('User is signed in.');
        } else {
            console.log('No user is signed in.');
        }
    });
  }

What is the use of the JavaScript 'bind' method?

  • function.prototype.bind() accepts an Object.

  • It binds the calling function to the passed Object and the returns the same.

  • When an object is bound to a function, it means you will be able to access the values of that object from within the function using 'this' keyword.

It can also be said as,

function.prototype.bind() is used to provide/change the context of a function.

_x000D_
_x000D_
let powerOfNumber = function(number) {
  let product = 1;
    for(let i=1; i<= this.power; i++) {
      product*=number;
  }
  return product;
}


let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));

let powerOfThree = powerOfNumber.bind({power:3});
alert(powerOfThree(2));

let powerOfFour = powerOfNumber.bind({power:4});
alert(powerOfFour(2));
_x000D_
_x000D_
_x000D_

Let us try to understand this.

    let powerOfNumber = function(number) {
      let product = 1;
      for (let i = 1; i <= this.power; i++) {
        product *= number;
      }
      return product;
    }

Here, in this function, this corresponds to the object bound to the function powerOfNumber. Currently we don't have any function that is bound to this function.

Let us create a function powerOfTwo which will find the second power of a number using the above function.

  let powerOfTwo = powerOfNumber.bind({power:2});
  alert(powerOfTwo(2));

Here the object {power : 2} is passed to powerOfNumber function using bind.

The bind function binds this object to the powerOfNumber() and returns the below function to powerOfTwo. Now, powerOfTwo looks like,

    let powerOfNumber = function(number) {
      let product = 1;
        for(let i=1; i<=2; i++) {
          product*=number;
      }
      return product;
    }

Hence, powerOfTwo will find the second power.

Feel free to check this out.

bind() function in Javascript

git rm - fatal: pathspec did not match any files

To remove the tracked and old committed file from git you can use the below command. Here in my case, I want to untrack and remove all the file from dist directory.

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch dist' --tag-name-filter cat -- --all

Then, you need to add it into your .gitignore so it won't be tracked further.

Java word count program

public class wordCount
{
public static void main(String ar[]) throws Exception
{
System.out.println("Simple Java Word Count Program");


    int wordCount = 1,count=1;
 BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
            String str2 = "", str1 = "";

            while ((str1 = br.readLine()) != null) {

                    str2 += str1;

            }


    for (int i = 0; i < str2.length(); i++) 
    {
        if (str2.charAt(i) == ' ' && str2.charAt(i+1)!=' ') 
        {
            wordCount++;
        } 


        }

    System.out.println("Word count is = " +(wordCount));
}

}

How do I combine two lists into a dictionary in Python?

If there are duplicate keys in the first list that map to different values in the second list, like a 1-to-many relationship, but you need the values to be combined or added or something instead of updating, you can do this:

i = iter(["a", "a", "b", "c", "b"])
j = iter([1,2,3,4,5])
k = list(zip(i, j))
for (x,y) in k:
    if x in d:
        d[x] = d[x] + y #or whatever your function needs to be to combine them
    else:
        d[x] = y

In that example, d == {'a': 3, 'c': 4, 'b': 8}

Onclick function based on element id

you can try these:

document.getElementById("RootNode").onclick = function(){/*do something*/};

or

$('#RootNode').click(function(){/*do something*/});

or

$(document).on("click", "#RootNode", function(){/*do something*/});

There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload or DOMReady event, like:

//in Vanilla JavaScript
window.addEventListener("load", function(){
     document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
    $('#RootNode').click(function(){/*do something*/});
});

Why do I keep getting Delete 'cr' [prettier/prettier]?

I know this is old but I just encountered the issue in my team (some mac, some linux, some windows , all vscode).

solution was to set the line ending in vscode's settings:

.vscode/settings.json

{
    "files.eol": "\n",
}

https://qvault.io/2020/06/18/how-to-get-consistent-line-breaks-in-vs-code-lf-vs-crlf/

Preloading @font-face fonts?

This answer is no longer up to date

Please refer to this updated answer: https://stackoverflow.com/a/46830425/4031815


Deprecated answer

I'm not aware of any current technique to avoid the flicker as the font loads, however you can minimize it by sending proper cache headers for your font and making sure that that request goes through as quickly as possible.

Email address validation in C# MVC 4 application: with or without using Regex

Why not just use the EmailAttribute?

[Email(ErrorMessage = "Bad email")]
public string Email { get; set; }