Programs & Examples On #Sudoers

Exit/save edit to sudoers file? Putty SSH

Just open file by nano /file_name

Once done, press CTRL+O and then Enter to save. Then press CTRL+X to return.

Here CTRL+O : is CTRL and O for Orange Not 0 Zero

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

How to run script as another user without password?

try running:

su -c "Your command right here" -s /bin/sh username

This will run the command as username given that you have permissions to sudo as that user.

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Closing pyplot windows

plt.close() will close current instance.

plt.close(2) will close figure 2

plt.close(plot1) will close figure with instance plot1

plt.close('all') will close all fiures

Found here.

Remember that plt.show() is a blocking function, so in the example code you used above, plt.close() isn't being executed until the window is closed, which makes it redundant.

You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.

EXAMPLE

After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.

Below I create a plot:

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')

In this case, ax above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax).

par_plot is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.

I can also create a slider widget by doing the following:

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

The first line creates a new axes for the slider (called axsliderA), the second line creates a slider instance sA which is placed in the axes, and the third line specifies a function to call when the slider value changes (update).

My update function could look something like this:

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()

The par_plot.set_ydata(y_data) changes the ydata property of the Line2D object with the handle par_plot.

The draw() function updates the current set of axes.

Putting it all together:

from pylab import *
import matplotlib.pyplot as plt
import numpy

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()


x_data = numpy.arange(-100,100,0.1);

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)

ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)

axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)

axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;

par_plot, = plot(x_data,y_data, lw=2, color='red')

show()

A note about the above: When I run the application, the code runs sequentially right through (it stores the update function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).

This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.

Run .php file in Windows Command Prompt (cmd)

You should declare Environment Variable for PHP in path, so you could use like this:

C:\Path\to\somewhere>php cli.php

You can do it like this

Difference between web server, web container and application server

Web Container + HTTP request handling = WebServer

Web Server + EJB + (Messaging + Transactions+ etc) = ApplicaitonServer

hibernate could not get next sequence value

Using the GeneratedValue and GenericGenerator with the native strategy:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_native")
@GenericGenerator(name = "id_native", strategy = "native")
@Column(name = "id", updatable = false, nullable = false)
private Long id;

I had to create a sequence call hibernate_sequence as Hibernate looks up for such a sequence by default:

create sequence hibernate_sequence start with 1 increment by 50;
grant usage, select on all sequences in schema public to my_user_name;

Mix Razor and Javascript code

Inside a code block (eg, @foreach), you need to mark the markup (or, in this case, Javascript) with @: or the <text> tag.

Inside the markup contexts, you need to surround code with code blocks (@{ ... } or @if, ...)

Node/Express file upload

Another option is to use multer, which uses busboy under the hood, but is simpler to set up.

var multer = require('multer');

Use multer and set the destination for the upload:

app.use(multer({dest:'./uploads/'}));

Create a form in your view, enctype='multipart/form-data is required for multer to work:

form(role="form", action="/", method="post", enctype="multipart/form-data")
    div(class="form-group")
        label Upload File
        input(type="file", name="myfile", id="myfile")

Then in your POST you can access the data about the file:

app.post('/', function(req, res) {
  console.dir(req.files);
});

A full tutorial on this can be found here.

Java : Cannot format given Object as a Date

java.time

I should like to contribute the modern answer. The SimpleDateFormat class is notoriously troublesome, and while it was reasonable to fight one’s way through with it when this question was asked six and a half years ago, today we have much better in java.time, the modern Java date and time API. SimpleDateFormat and its friend Date are now considered long outdated, so don’t use them anymore.

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM/uuuu");
    String dateformat = "2012-11-17T00:00:00.000-05:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(dateformat);
    String monthYear = dateTime.format(monthFormatter);
    System.out.println(monthYear);

Output:

11/2012

I am exploiting the fact that your string is in ISO 8601 format, the international standard, and that the classes of java.time parse this format as their default, that is, without any explicit formatter. It’s stil true what the other answers say, you need to parse the original string first, then format the resulting date-time object into a new string. Usually this requires two formatters, only in this case we’re lucky and can do with just one formatter.

What went wrong in your code

  • As others have said, SimpleDateFormat.format cannot accept a String argument, also when the parameter type is declared to be Object.
  • Because of the exception you didn’t get around to discovering: there is also a bug in your format pattern string, mm/yyyy. Lowercase mm os for minute of the hour. You need uppercase MM for month.
  • Finally the Java naming conventions say to use a lowercase first letter in variable names, so use lowercase m in monthYear (also because java.time includes a MonthYear class with uppercase M, so to avoid confusion).

Links

How to handle ETIMEDOUT error?

This is caused when your request response is not received in given time(by timeout request module option).

Basically to catch that error first, you need to register a handler on error, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ }). Some more explanation here.

In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }.

If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.

If you want to wait longer, you can set timeout option of request yourself. You can set it to 0 for no timeout.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

Fairly new to using PowerShell, think I might be able to help. Could you try this?

I believe you're not getting the correct parameters to your script block:

param([string]$one, [string]$two)
$res = Invoke-Command -Credential $migratorCreds -ScriptBlock {Get-LocalUsers -parentNodeXML $args[0] -migratorUser $args[1] } -ArgumentList $xmlPRE, $migratorCreds

Jenkins Host key verification failed

I ran into this issue and it turned out the problem was that the jenkins service wasn't being run as the jenkins user. So running the commands as the jenkins user worked just fine.

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I doubt anything is killing the process just because it takes a long time. Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem. What might be happening is you're hitting a bug in Python or standard library code that causes a crash of the process.

How to get a unique device ID in Swift?

class func uuid(completionHandler: @escaping (String) -> ()) {
    if let uuid = UIDevice.current.identifierForVendor?.uuidString {
        completionHandler(uuid)
    }
    else {
        // If the value is nil, wait and get the value again later. This happens, for example, after the device has been restarted but before the user has unlocked the device.
        // https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor?language=objc
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            uuid(completionHandler: completionHandler)
        }
    }
}

RESTful web service - how to authenticate requests from other services?

There are several different approaches you can take.

  1. The RESTful purists will want you to use BASIC authentication, and send credentials on every request. Their rationale is that no one is storing any state.

  2. The client service could store a cookie, which maintains a session ID. I don't personally find this as offensive as some of the purists I hear from - it can be expensive to authenticate over and over again. It sounds like you're not too fond of this idea, though.

  3. From your description, it really sounds like you might be interested in OAuth2 My experience so far, from what I've seen, is that it's kind of confusing, and kind of bleeding edge. There are implementations out there, but they're few and far between. In Java, I understand that it has been integrated into Spring3's security modules. (Their tutorial is nicely written.) I've been waiting to see if there will be an extension in Restlet, but so far, although it's been proposed, and may be in the incubator, it's still not been fully incorporated.

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

When you test with device you want to add your PC ip address.

in pc run in cmd Ipconfig

in ubuntu run terminal ifconfig

Then use "http://your_pc_ip_address:8080/register" insted of using "http://10.0.2.2:8080/register"

in my pc = 192.168.1.3

and also add internet permission to Manifest

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

RegExp in TypeScript

In typescript, the declaration is something like this:

const regex : RegExp = /.+\*.+/;

using RegExp constructor:

const regex = new RegExp('.+\\*.+');

What is the difference between <p> and <div>?

The only difference between the two elements is semantics. Both elements, by default, have the CSS rule display: block (hence block-level) applied to them; nothing more (except somewhat extra margin in some instances). However, as aforementioned, they both different greatly in terms of semantics.

The <p> element, as its name somewhat implies, is for paragraphs. Thus, <p> should be used when you want to create blocks of paragraph text.

The <div> element, however, has little to no meaning semantically and therefore can be used as a generic block-level element — most commonly, people use it within layouts because it is meaningless semantically and can be used for generally anything you might require a block-level element for.

Link for more detail

Return anonymous type results?

Well, if you're returning Dogs, you'd do:

public IQueryable<Dog> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    return from d in db.Dogs
           join b in db.Breeds on d.BreedId equals b.BreedId
           select d;
}

If you want the Breed eager-loaded and not lazy-loaded, just use the appropriate DataLoadOptions construct.

self referential struct definition?

From the theoretical point of view, Languages can only support self-referential structures not self-inclusive structures.

Adding days to $Date in PHP

Here is a small snippet to demonstrate the date modifications:

$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";

//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";

//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";

//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";

How to get a password from a shell script without echoing

Turn echo off using stty, then back on again after.

Running code after Spring Boot starts

Try this one and it will run your code when the application context has fully started.

 @Component
public class OnStartServer implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent arg0) {
                // EXECUTE YOUR CODE HERE 
    }
}

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Save Javascript objects in sessionStorage

Session storage cannot support an arbitrary object because it may contain function literals (read closures) which cannot be reconstructed after a page reload.

Change text color with Javascript?

You set the style per element and not by its content:

function init() { 
  document.getElementById("about").style.color = 'blue';
}

With innerHTML you get/set the content of an element. So if you would want to modify your title, innerHTML would be the way to go.

In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style property of the element itself.

Write string to text file and ensure it always overwrites the existing content.

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

Where to place and how to read configuration resource files in servlet based application?

Assume your code is looking for the file say app.properties. Copy this file to any dir and add this dir to classpath, by creating a setenv.sh in the bin dir of tomcat.

In your setenv.sh of tomcat( if this file is not existing, create one , tomcat will load this setenv.sh file. #!/bin/sh CLASSPATH="$CLASSPATH:/home/user/config_my_prod/"

You should not have your properties files in ./webapps//WEB-INF/classes/app.properties

Tomcat class loader will override the with the one from WEB-INF/classes/

A good read: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

ORA-00972 identifier is too long alias column name

No, prior to Oracle version 12.2, identifiers are not allowed to exceed 30 characters in length. See the Oracle SQL Language Reference.

However, from version 12.2 they can be up to 128 bytes long. (Note: bytes, not characters).

docker mounting volumes on host

The VOLUME command will mount a directory inside your container and store any files created or edited inside that directory on your hosts disk outside the container file structure, bypassing the union file system.

The idea is that your volumes can be shared between your docker containers and they will stay around as long as there's a container (running or stopped) that references them.

You can have other containers mount existing volumes (effectively sharing them between containers) by using the --volumes-from command when you run a container.

The fundamental difference between VOLUME and -v is this: -v will mount existing files from your operating system inside your docker container and VOLUME will create a new, empty volume on your host and mount it inside your container.

Example:

  1. You have a Dockerfile that defines a VOLUME /var/lib/mysql.
  2. You build the docker image and tag it some-volume
  3. You run the container

And then,

  1. You have another docker image that you want to use this volume
  2. You run the docker container with the following: docker run --volumes-from some-volume docker-image-name:tag
  3. Now you have a docker container running that will have the volume from some-volume mounted in /var/lib/mysql

Note: Using --volumes-from will mount the volume over whatever exists in the location of the volume. I.e., if you had stuff in /var/lib/mysql, it will be replaced with the contents of the volume.

How do I select text nodes with jQuery?

$('body').find('*').contents().filter(function () { return this.nodeType === 3; });

How to merge a Series and DataFrame

Update
From v0.24.0 onwards, you can merge on DataFrame and Series as long as the Series is named.

df.merge(s.rename('new'), left_index=True, right_index=True)
# If series is already named,
# df.merge(s, left_index=True, right_index=True)

Nowadays, you can simply convert the Series to a DataFrame with to_frame(). So (if joining on index):

df.merge(s.to_frame(), left_index=True, right_index=True)

How to mention C:\Program Files in batchfile

Now that bash is out for windows 10, if you want to access program files from bash, you can do it like so: cd /mnt/c/Program\ Files.

How to click a href link using Selenium

Thi is your code :

Driver.findElement(By.xpath(//a[@href ='/docs/configuration']")).click();

You missed the Quotation mark

it should be as below

Driver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();

Hope this helps!

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

Go to command prompt, cd to the appropriate folder and type:

notepad .htaccess

After confirmation dialog the file will be created and you will be editing it directly. If you just want to create an empty file, try

echo. > .htaccess

How to config Tomcat to serve images from an external folder outside webapps?

You could have a redirect servlet. In you web.xml you'd have:

<servlet>
    <servlet-name>images</servlet-name>
    <servlet-class>com.example.images.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>images</servlet-name>
    <url-pattern>/images/*</url-pattern>
</servlet-mapping>

All your images would be in "/images", which would be intercepted by the servlet. It would then read in the relevant file in whatever folder and serve it right back out. For example, say you have a gif in your images folder, c:\Server_Images\smilie.gif. In the web page would be <img src="http:/example.com/app/images/smilie.gif".... In the servlet, HttpServletRequest.getPathInfo() would yield "/smilie.gif". Which the servlet would find in the folder.

How do I calculate a trendline for a graph?

Here's what I ended up using.

public class DataPoint<T1,T2>
{
    public DataPoint(T1 x, T2 y)
    {
        X = x;
        Y = y;
    }

    [JsonProperty("x")]
    public T1 X { get; }

    [JsonProperty("y")]
    public T2 Y { get; }
}

public class Trendline
{
    public Trendline(IEnumerable<DataPoint<long, decimal>> dataPoints)
    {
        int count = 0;
        long sumX = 0;
        long sumX2 = 0;
        decimal sumY = 0;
        decimal sumXY = 0;

        foreach (var dataPoint in dataPoints)
        {
            count++;
            sumX += dataPoint.X;
            sumX2 += dataPoint.X * dataPoint.X;
            sumY += dataPoint.Y;
            sumXY += dataPoint.X * dataPoint.Y;
        }

        Slope = (sumXY - ((sumX * sumY) / count)) / (sumX2 - ((sumX * sumX) / count));
        Intercept = (sumY / count) - (Slope * (sumX / count));
    }

    public decimal Slope { get; private set; }
    public decimal Intercept { get; private set; }
    public decimal Start { get; private set; }
    public decimal End { get; private set; }

    public decimal GetYValue(decimal xValue)
    {
        return Slope * xValue + Intercept;
    }
}

My data set is using a Unix timestamp for the x-axis and a decimal for the y. Change those datatypes to fit your need. I do all the sum calculations in one iteration for the best possible performance.

Difference between maven scope compile and provided for JAR packaging

For a jar file, the difference is in the classpath listed in the MANIFEST.MF file included in the jar if addClassPath is set to true in the maven-jar-plugin configuration. 'compile' dependencies will appear in the manifest, 'provided' dependencies won't.

One of my pet peeves is that these two words should have the same tense. Either compiled and provided, or compile and provide.

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

You could use prop as well. Check the following code below.

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").prop("readonly", false); 
     }
     else{ 
         $("#no_of_staff").prop("readonly", true); 
     }
   });
});

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

ICommand MVVM implementation

This is almost identical to how Karl Shifflet demonstrated a RelayCommand, where Execute fires a predetermined Action<T>. A top-notch solution, if you ask me.

public class RelayCommand : ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;

    public RelayCommand(Predicate<object> canExecute, Action<object> execute)
    {
        _canExecute = canExecute;
        _execute = execute;
    }

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

This could then be used as...

public class MyViewModel
{
    private ICommand _doSomething;
    public ICommand DoSomethingCommand
    {
        get
        {
            if (_doSomething == null)
            {
                _doSomething = new RelayCommand(
                    p => this.CanDoSomething,
                    p => this.DoSomeImportantMethod());
            }
            return _doSomething;
        }
    }
}

Read more:
Josh Smith (introducer of RelayCommand): Patterns - WPF Apps With The MVVM Design Pattern

Java Code for calculating Leap Year

import javax.swing.*;
public class LeapYear {
    public static void main(String[] args) {
    int year;
String yearStr = JOptionPane.showInputDialog(null, "Enter radius: " );

year = Integer.parseInt( yearStr );

boolean isLeapYear;
isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);  

 if(isLeapYear){ 
JOptionPane.showMessageDialog(null, "Leap Year!"); 
 }  
 else{
JOptionPane.showMessageDialog(null, "Not a Leap Year!"); 
    }
    }
    }

Why Does OAuth v2 Have Both Access and Refresh Tokens?

This answer is from Justin Richer via the OAuth 2 standard body email list. This is posted with his permission.


The lifetime of a refresh token is up to the (AS) authorization server — they can expire, be revoked, etc. The difference between a refresh token and an access token is the audience: the refresh token only goes back to the authorization server, the access token goes to the (RS) resource server.

Also, just getting an access token doesn’t mean the user’s logged in. In fact, the user might not even be there anymore, which is actually the intended use case of the refresh token. Refreshing the access token will give you access to an API on the user’s behalf, it will not tell you if the user’s there.

OpenID Connect doesn’t just give you user information from an access token, it also gives you an ID token. This is a separate piece of data that’s directed at the client itself, not the AS or the RS. In OIDC, you should only consider someone actually “logged in” by the protocol if you can get a fresh ID token. Refreshing it is not likely to be enough.

For more information please read http://oauth.net/articles/authentication/

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

What is difference between monolithic and micro kernel?

Monolithic kernel has all kernel services along with kernel core part, thus are heavy and has negative impact on speed and performance. On the other hand micro kernel is lightweight causing increase in performance and speed.
I answered same question at wordpress site. For the difference between monolithic, microkernel and exokernel in tabular form, you can visit here

clear form values after submission ajax

$.post('mail.php',{name:$('#name').val(),
                          email:$('#e-mail').val(),
                          phone:$('#phone').val(),
                          message:$('#message').val()},

        //return the data
        function(data){
           if(data==<when do you want to clear the form>){

           $('#<form Id>').find(':input').each(function() {
                 switch(this.type) {
                      case 'password':
                      case 'select-multiple':
                      case 'select-one':
                      case 'text':
                      case 'textarea':
                          $(this).val('');
                          break;
                      case 'checkbox':
                      case 'radio':
                          this.checked = false;
                  }
              });
           }      
   });

http://www.electrictoolbox.com/jquery-clear-form/

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

If you're not using jQuery... you need to access one of the event's TouchLists to get a Touch object which has pageX/Y clientX/Y etc.

Here are links to the relevant docs:

I'm using e.targetTouches[0].pageX in my case.

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

How to generate a number of most distinctive colors in R?

You can generate a set of colors like this:

myCol = c("pink1", "violet", "mediumpurple1", "slateblue1", "purple", "purple3",
          "turquoise2", "skyblue", "steelblue", "blue2", "navyblue",
          "orange", "tomato", "coral2", "palevioletred", "violetred", "red2",
          "springgreen2", "yellowgreen", "palegreen4",
          "wheat2", "tan", "tan2", "tan3", "brown",
          "grey70", "grey50", "grey30")

These colors are as distinct as possible. For those similar colors, they form a gradient so that you can easily tell the differences between them.

What is the backslash character (\\)?

\ is used as for escape sequence in many programming languages, including Java.

If you want to

  • go to next line then use \n or \r,
  • for tab use \t
  • likewise to print a \ or " which are special in string literal you have to escape it with another \ which gives us \\ and \"

Running npm command within Visual Studio Code

There is an extension available, npm Script runner. I have not tried it myself, though.

Default keystore file does not exist?

You must be providing the wrong path to the debug.keystore file.

Follow these steps to get the correct path and complete your command:

  1. In eclipse, click the Window menu -> Preferences -> Expand Android -> Build
  2. In the right panel, look for: Default debug keystore:
  3. Select the entire box next to the label specified in Step 2

And finally, use the path you just copied from Step 3 to construct your command:

For example, in my case, it would be:

C:\Program Files\Java\jre7\bin>keytool -list -v -keystore "C:\Users\Siddharth Lele.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

UPDATED:

If you had already followed the steps mentioned above, the only other solution is to delete the debug.keystore and let Eclipse recreate it for you.

Step 1: Go to the path where your keystore is stored. In your case, C:\Users\Suresh\.android\debug.keystore

Step 2: Close and restart Eclipse.

Step 3 (Optional): You may need to clean your project before the debug.keystore is created again.

Source: http://www.coderanch.com/t/440920/Security/KeyTool-genkeypair-exception-Keystore-file

You can refer to this for the part about deleting your debug.keystore file: "Debug certificate expired" error in Eclipse Android plugins

Apache won't start in wamp

Sometimes it is Skype or another application "Holding" on to port 80. Jusct close Skype

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

How does "FOR" work in cmd batch file?

This works for me:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS
@REM insure path is terminated with a ;
set tpath=%path%;
echo.
:again
@REM This FOR statement grabs the first element in the path
FOR /F "delims=;" %%I IN ("%TPATH%") DO (
  echo    %%I 
  @REM remove the current element of the path
  set TPATH=!TPATH:%%I;=!
)
@REM loop back if there is more to do. 
IF DEFINED TPATH GOTO :again

ENDLOCAL

npm start error with create-react-app

I have faced the following issue.

enter image description here

Please find the solution:

  1. Add "C:\Windows\System32" to the global PATH environment variable.

  2. Check whether the environment variables has been created for nodejs,npm and composer. if not create one

enter image description here

  1. Run your app.

Count cells that contain any text

The criterium should be "?*" and not "<>" because the latter will also count formulas that contain empty results, like ""

So the simplest formula would be

=COUNTIF(Range,"?*")

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

Here's a solution using a negative lookahead (not supported in all regex engines):

^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$

Test that it works as expected:

import re
tests = [
   ('a', True),
   ('_', False),
   ('zz', True),
   ('a0', True),
   ('A_', False),
   ('a0_b', True),
   ('a__b', False),
   ('a_1_c', True),
]

regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
   is_match = re.match(regex, test[0]) is not None
   if is_match != test[1]:
       print "fail: "  + test[0]

JQuery .each() backwards

I prefer creating a reverse plug-in eg

jQuery.fn.reverse = function(fn) {       
   var i = this.length;

   while(i--) {
       fn.call(this[i], i, this[i])
   }
};

Usage eg:

$('#product-panel > div').reverse(function(i, e) {
    alert(i);
    alert(e);
});

How do I set the figure title and axes labels font size in Matplotlib?

Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:

from matplotlib import pyplot as plt    

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')

For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page):

axes.titlesize      : large   # fontsize of the axes title
axes.labelsize      : medium  # fontsize of the x any y labels

(As far as I can see, there is no way to set x and y label sizes separately.)

And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually.

Using Git with Visual Studio

Currently there are 2 options for Git Source Control in Visual Studio (2010 and 12):

  1. Git Source Control Provider
  2. Microsoft Git Provider

I have tried both and have found 1st one to be more mature, and has more features. For instance it plays nicely with both tortoise git and git extensions, and even exposed their features.

Note: Whichever extension you use, make sure that you enable it from Tools -> Options -> Source control -> Plugin Selection for it to work.

How do I uniquely identify computers visiting my web site?

You can use fingerprintjs2

new Fingerprint2().get(function(result, components) {
  console.log(result) // a hash, representing your device fingerprint
  console.log(components) // an array of FP components
  //submit hash and JSON object to the server 
})

After that you can check all your users against existing and check JSON similarity, so even if their fingerprint mutates, you still can track them

Why do I need to configure the SQL dialect of a data source?

Databases implement subtle differences in the SQL they use. Things such as data types for example vary across databases (e.g. in Oracle You might put an integer value in a number field and in SQL Server use an int field). Or database specific functionality - selecting the top n rows is different depending on the database. The dialect abstracts this so you don't have to worry about it.

CSS3 Continuous Rotate Animation (Just like a loading sundial)

Your code seems correct. I would presume it is something to do with the fact you are using a .png and the way the browser redraws the object upon rotation is inefficient, causing the hang (what browser are you testing under?)

If possible replace the .png with something native.

see; http://kilianvalkhof.com/2010/css-xhtml/css3-loading-spinners-without-images/

Chrome gives me no pauses using this method.

How to setup FTP on xampp

I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!

Is there a splice method for strings?

So, whatever adding splice method to a String prototype cant work transparent to spec...

Let's do some one extend it:

String.prototype.splice = function(...a){
    for(var r = '', p = 0, i = 1; i < a.length; i+=3)
        r+= this.slice(p, p=a[i-1]) + (a[i+1]||'') + this.slice(p+a[i], p=a[i+2]||this.length);
    return r;
}
  • Every 3 args group "inserting" in splice style.
  • Special if there is more then one 3 args group, the end off each cut will be the start of next.
    • '0123456789'.splice(4,1,'fourth',8,1,'eighth'); //return '0123fourth567eighth9'
  • You can drop or zeroing the last arg in each group (that treated as "nothing to insert")
    • '0123456789'.splice(-4,2); //return '0123459'
  • You can drop all except 1st arg in last group (that treated as "cut all after 1st arg position")
    • '0123456789'.splice(0,2,null,3,1,null,5,2,'/',8); //return '24/7'
  • if You pass multiple, you MUST check the sort of the positions left-to-right order by youreself!
  • And if you dont want you MUST DO NOT use it like this:
    • '0123456789'.splice(4,-3,'what?'); //return "0123what?123456789"

How can I simulate an array variable in MySQL?

I know that this is a bit of a late response, but I recently had to solve a similar problem and thought that this may be useful to others.

Background

Consider the table below called 'mytable':

Starting table

The problem was to keep only latest 3 records and delete any older records whose systemid=1 (there could be many other records in the table with other systemid values)

It would be good is you could do this simply using the statement

DELETE FROM mytable WHERE id IN (SELECT id FROM `mytable` WHERE systemid=1 ORDER BY id DESC LIMIT 3)

However this is not yet supported in MySQL and if you try this then you will get an error like

...doesn't yet support 'LIMIT & IN/ALL/SOME subquery'

So a workaround is needed whereby an array of values is passed to the IN selector using variable. However, as variables need to be single values, I would need to simulate an array. The trick is to create the array as a comma separated list of values (string) and assign this to the variable as follows

SET @myvar := (SELECT GROUP_CONCAT(id SEPARATOR ',') AS myval FROM (SELECT * FROM `mytable` WHERE systemid=1 ORDER BY id DESC LIMIT 3 ) A GROUP BY A.systemid);

The result stored in @myvar is

5,6,7

Next, the FIND_IN_SET selector is used to select from the simulated array

SELECT * FROM mytable WHERE FIND_IN_SET(id,@myvar);

The combined final result is as follows:

SET @myvar := (SELECT GROUP_CONCAT(id SEPARATOR ',') AS myval FROM (SELECT * FROM `mytable` WHERE systemid=1 ORDER BY id DESC LIMIT 3 ) A GROUP BY A.systemid);
DELETE FROM mytable WHERE FIND_IN_SET(id,@myvar);

I am aware that this is a very specific case. However it can be modified to suit just about any other case where a variable needs to store an array of values.

I hope that this helps.

Java system properties and environment variables

How to enable core dump in my Linux C++ program

You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>.

How to get the CPU Usage in C#?

CMS has it right, but also if you use the server explorer in visual studio and play around with the performance counter tab then you can figure out how to get lots of useful metrics.

HTML5 - mp4 video does not play in IE9

From what I've heard, video support is minimal at best.

From http://diveintohtml5.ep.io/video.html#what-works:

As of this writing, this is the landscape of HTML5 video:

  • Mozilla Firefox (3.5 and later) supports Theora video and Vorbis audio in an Ogg container. Firefox 4 also supports WebM.

  • Opera (10.5 and later) supports Theora video and Vorbis audio in an Ogg container. Opera 10.60 also supports WebM.

  • Google Chrome (3.0 and later) supports Theora video and Vorbis audio in an Ogg container. Google Chrome 6.0 also supports WebM.

  • Safari on Macs and Windows PCs (3.0 and later) will support anything that QuickTime supports. In theory, you could require your users to install third-party QuickTime plugins. In practice, few users are going to do that. So you’re left with the formats that QuickTime supports “out of the box.” This is a long list, but it does not include WebM, Theora, Vorbis, or the Ogg container. However, QuickTime does ship with support for H.264 video (main profile) and AAC audio in an MP4 container.

  • Mobile phones like Apple’s iPhone and Google Android phones support H.264 video (baseline profile) and AAC audio (“low complexity” profile) in an MP4 container.

  • Adobe Flash (9.0.60.184 and later) supports H.264 video (all profiles) and AAC audio (all profiles) in an MP4 container.

  • Internet Explorer 9 supports all profiles of H.264 video and either AAC or MP3 audio in an MP4 container. It will also play WebM video if you install a third-party codec, which is not installed by default on any version of Windows. IE9 does not support other third-party codecs (unlike Safari, which will play anything QuickTime can play).

  • Internet Explorer 8 has no HTML5 video support at all, but virtually all Internet Explorer users will have the Adobe Flash plugin. Later in this chapter, I’ll show you how you can use HTML5 video but gracefully fall back to Flash.

As well, you should note this section just below on the same page:

There is no single combination of containers and codecs that works in all HTML5 browsers.

This is not likely to change in the near future.

To make your video watchable across all of these devices and platforms, you’re going to need to encode your video more than once.

"Find next" in Vim

Typing n will go to the next match.

Jquery Setting Value of Input Field

change your jquery loading setting to onload in jsfiddle . . .it works . . .

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Put novalidate="novalidate" on <form> tag.

<form novalidate="novalidate">
...
</form>

In XHTML, attribute minimization is forbidden, and the novalidate attribute must be defined as <form novalidate="novalidate">.

http://www.w3schools.com/tags/att_form_novalidate.asp

How to Serialize a list in java?

List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.

How to resolve "gpg: command not found" error during RVM installation?

As the instruction said "might need gpg2"

In mac, you can try install it with homebrew

$ brew install gpg2 

How to write a multiline command?

The caret character works, however the next line should not start with double quotes. e.g. this will not work:

C:\ ^
"SampleText" ..

Start next line without double quotes (not a valid example, just to illustrate)

Android Get Application's 'Home' Data Directory

You can try Context.getApplicationInfo().dataDir if you want the package's persistent data folder.

getFilesDir() returns a subroot of this.

Random String Generator Returning Same String

If you wanted to generate a string of Numbers and Characters for a strong password.

private static Random random = new Random();

private static string CreateTempPass(int size)
        {
            var pass = new StringBuilder();
            for (var i=0; i < size; i++)
            {
                var binary = random.Next(0,2);
                switch (binary)
                {
                    case 0:
                    var ch = (Convert.ToChar(Convert.ToInt32(Math.Floor(26*random.NextDouble() + 65))));
                        pass.Append(ch);
                        break;
                    case 1:
                        var num = random.Next(1, 10);
                        pass.Append(num);
                        break;
                }
            }
            return pass.ToString();
        }

A simple explanation of Naive Bayes Classification

Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action
It uses an example problem from this book on page 351
This is the data set that we will be using
enter image description here
In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'} then what is the probability that he will buy or will not buy a computer.
The code below exactly answers that question.
Just create a file called named new_dataset.csv and paste the following content.

Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no

Here is the code the comments explains everything we are doing here! [python]

import pandas as pd 
import pprint 

class Classifier():
    data = None
    class_attr = None
    priori = {}
    cp = {}
    hypothesis = None


    def __init__(self,filename=None, class_attr=None ):
        self.data = pd.read_csv(filename, sep=',', header =(0))
        self.class_attr = class_attr

    '''
        probability(class) =    How many  times it appears in cloumn
                             __________________________________________
                                  count of all class attribute
    '''
    def calculate_priori(self):
        class_values = list(set(self.data[self.class_attr]))
        class_data =  list(self.data[self.class_attr])
        for i in class_values:
            self.priori[i]  = class_data.count(i)/float(len(class_data))
        print "Priori Values: ", self.priori

    '''
        Here we calculate the individual probabilites 
        P(outcome|evidence) =   P(Likelihood of Evidence) x Prior prob of outcome
                               ___________________________________________
                                                    P(Evidence)
    '''
    def get_cp(self, attr, attr_type, class_value):
        data_attr = list(self.data[attr])
        class_data = list(self.data[self.class_attr])
        total =1
        for i in range(0, len(data_attr)):
            if class_data[i] == class_value and data_attr[i] == attr_type:
                total+=1
        return total/float(class_data.count(class_value))

    '''
        Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
        (Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
        scaled by P(Multiple Evidence)
    '''
    def calculate_conditional_probabilities(self, hypothesis):
        for i in self.priori:
            self.cp[i] = {}
            for j in hypothesis:
                self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
        print "\nCalculated Conditional Probabilities: \n"
        pprint.pprint(self.cp)

    def classify(self):
        print "Result: "
        for i in self.cp:
            print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]

if __name__ == "__main__":
    c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
    c.calculate_priori()
    c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}

    c.calculate_conditional_probabilities(c.hypothesis)
    c.classify()

output:

Priori Values:  {'yes': 0.6428571428571429, 'no': 0.35714285714285715}

Calculated Conditional Probabilities: 

{
 'no': {
        '<=30': 0.8,
        'fair': 0.6, 
        'medium': 0.6, 
        'yes': 0.4
        },
'yes': {
        '<=30': 0.3333333333333333,
        'fair': 0.7777777777777778,
        'medium': 0.5555555555555556,
        'yes': 0.7777777777777778
      }
}

Result: 
yes  ==>  0.0720164609053
no  ==>  0.0411428571429

Hope it helps in better understanding the problem

peace

Adding a collaborator to my free GitHub account?

Clear Instructions On How to Add A Collaborator - 2020 Update

Pictures are worth a thousand words. Let's put that to the test:

Picture Instructions (Click to Zoom in):

Picture Instructions

.......and videos/gifs are worth another thousand more:

Gif Instructions (Click to Zoom in):

Hopefully the pictures/gif make it easier for you to configure this!

enter image description here

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

Execute a large SQL script (with GO commands)

I had the same problem in java and I solved it with a bit of logic and regex. I believe the same logic can be applied.First I read from the slq file into memory. Then I apply the following logic. It's pretty much what has been said before however I believe that using regex word bound is safer than expecting a new line char.

String pattern = "\\bGO\\b|\\bgo\\b";

String[] splitedSql = sql.split(pattern);
for (String chunk : splitedSql) {
  getJdbcTemplate().update(chunk);
}

This basically splits the sql string into an array of sql strings. The regex is basically to detect full 'go' words either lower case or upper case. Then you execute the different querys sequentially.

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

If you using Bootstrap:

The current version of Bootstrap (3.0.2) (with jQuery 1.10.2 & Chrome) seems to generate this warning as well.

(It does so on Twitter too, BTW.)

Update

The current version of Bootstrap (3.1.0) no longer seems to generate this warning.

JPA Native Query select and cast object

You might want to try one of the following ways:

  • Using the method createNativeQuery(sqlString, resultClass)

    Native queries can also be defined dynamically using the EntityManager.createNativeQuery() API.

    String sql = "SELECT USER.* FROM USER_ AS USER WHERE ID = ?";
    
    Query query = em.createNativeQuery(sql, User.class);
    query.setParameter(1, id);
    User user = (User) query.getSingleResult();
    
  • Using the annotation @NamedNativeQuery

    Native queries are defined through the @NamedNativeQuery and @NamedNativeQueries annotations, or <named-native-query> XML element.

    @NamedNativeQuery(
        name="complexQuery",
        query="SELECT USER.* FROM USER_ AS USER WHERE ID = ?",
        resultClass=User.class
    )
    public class User { ... }
    
    Query query = em.createNamedQuery("complexQuery", User.class);
    query.setParameter(1, id);
    User user = (User) query.getSingleResult();
    

You can read more in the excellent open book Java Persistence (available in PDF).

-------
NOTE: With regard to use of getSingleResult(), see Why you should never use getSingleResult() in JPA.

How to mount a host directory in a Docker container

I'm just experimenting with getting my SailsJS app running inside a Docker container to keep my physical machine clean.

I'm using the following command to mount my SailsJS/NodeJS application under /app:

cd my_source_code_folder
docker run -it -p 1337:1337 -v $(pwd):/app my_docker/image_with_nodejs_etc

how to add css class to html generic control div?

My approach would be:

/// <summary>
/// Appends CSS Class seprated by a space character
/// </summary>
/// <param name="control">Target control</param>
/// <param name="cssClass">CSS class name to append</param>
public static void AppendCss(HtmlGenericControl control, string cssClass)
{
    // Ensure CSS class is definied
    if (string.IsNullOrEmpty(cssClass)) return;

    // Append CSS class
    if (string.IsNullOrEmpty(control.Attributes["class"]))
    {
        // Set our CSS Class as only one
        control.Attributes["class"] = cssClass;
    }
    else
    {
        // Append new CSS class with space as seprator
        control.Attributes["class"] += (" " + cssClass);
    }
}

MySQL dump by query

You could use --where option on mysqldump to produce an output that you are waiting for:

mysqldump -u root -p test t1 --where="1=1 limit 100" > arquivo.sql

At most 100 rows from test.t1 will be dumped from database table.

Cheers, WB

How do I get the full path of the current file's directory?

You can use os and os.path library easily as follows

import os
os.chdir(os.path.dirname(os.getcwd()))

os.path.dirname returns upper directory from current one. It lets us change to an upper level without passing any file argument and without knowing absolute path.

os.path.dirname(os.path.abspath(myfilename))

Inner join vs Where

They should be exactly the same. However, as a coding practice, I would rather see the Join. It clearly articulates your intent,

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

How to access the php.ini file in godaddy shared hosting linux

I had this exact problem with my GoDaddy account.

I am running the Linux hosting with cPanel

follow these steps and you should be fine if you are running the same hosting as me:

first, go to you Manage Your Hosting -> Manage

then you will see a section called Files, click on File Manager

you can select the Document Root for: yourwebsite.com then click GO

this should bring you right away in the public_html folder

in that folder, you can add a file (by clicking the +File in top left corner), call it phpinfo.php

right click that new file, and select edit :

right this in it and save changes:

<?php phpinfo(); ?>

it the same public_html folder, add another file called php.ini

edit this one too, right those lines:

max_execution_time 600
memory_limit 128M
post_max_size 32M
upload_max_filesize 32M

now, go back to your Manage Your Hosting -> Manage, look for PHP Process

click Kill Process, this will allows a refresh with your new settings. you are good to go

side note: you can see your new settings by navigating to yourwebiste.com/phpinfo.php

How to search and replace text in a file?

Like so:

def find_and_replace(file, word, replacement):
  with open(file, 'r+') as f:
    text = f.read()
    f.write(text.replace(word, replacement))

Getting Python error "from: can't read /var/mail/Bio"

Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.

./manage.py shell

and only then

>>> from django.contrib.sites.models import Site

JavaScript calculate the day of the year (1 - 366)

/*USE THIS SCRIPT */

var today = new Date();
var first = new Date(today.getFullYear(), 0, 1);
var theDay = Math.round(((today - first) / 1000 / 60 / 60 / 24) + .5, 0);
alert("Today is the " + theDay + (theDay == 1 ? "st" : (theDay == 2 ? "nd" : (theDay == 3 ? "rd" : "th"))) + " day of the year");

Redirecting from HTTP to HTTPS with PHP

On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:

if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

Ruby/Rails: converting a Date to a UNIX timestamp

DateTime.new(2012, 1, 15).to_time.to_i

Calling Objective-C method from C++ member function?

You can compile your code as Objective-C++ - the simplest way is to rename your .cpp as .mm. It will then compile properly if you include EAGLView.h (you were getting so many errors because the C++ compiler didn't understand any of the Objective-C specific keywords), and you can (for the most part) mix Objective-C and C++ however you like.

Responsive bootstrap 3 timepicker?

Above of all, I found this library right here. Works out of the box perfectly on a Bootstrap-3 environment.

Bootstrap-3 Clock-Picker

CSS

<link rel="stylesheet" type="text/css" href="dist/bootstrap-clockpicker.min.css">

HTML

<div class="input-group clockpicker">
    <input type="text" class="form-control" value="09:30">
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-time"></span>
    </span>
</div>

JAVASCRIPT

<script type="text/javascript" src="dist/bootstrap-clockpicker.min.js"></script>
<script type="text/javascript">
    $('.clockpicker').clockpicker();
</script>

As simple as that! Find more examples on the link above.

Update 18/04/2018

If you are using Bootstrap-4, the most popular time/date picker library available right now is Tempus Dominus. It is not fancy looking, but much responsive and modern.

Bootstrap-4 Tempus Dominus

Run PHP function on html button click

Use an AJAX Request on your PHP file, then display the result on your page, without any reloading.

http://api.jquery.com/load/ This is a simple solution if you don't need any POST data.

Laravel 5 Eloquent where and or in Clauses

Using advanced wheres:

CabRes::where('m__Id', 46)
      ->where('t_Id', 2)
      ->where(function($q) {
          $q->where('Cab', 2)
            ->orWhere('Cab', 4);
      })
      ->get();

Or, even better, using whereIn():

CabRes::where('m__Id', 46)
      ->where('t_Id', 2)
      ->whereIn('Cab', $cabIds)
      ->get();

Which JDK version (Language Level) is required for Android Studio?

Normally, I would go with what the documentation says but if the instructor explicitly said to stick with JDK 6, I'd use JDK 6 because you would want your development environment to be as close as possible to the instructors. It would suck if you ran into an issue and having the thought in the back of your head that maybe it's because you're on JDK 7 that you're having the issue. Btw, I haven't touched Android recently but I personally never ran into issues when I was on JDK 7 but mind you, I only code Android apps casually.

How to use classes from .jar files?

Not every jar file is executable.

Now, you need to import the classes, which are there under the jar, in your java file. For example,

import org.xml.sax.SAXException;

If you are working on an IDE, then you should refer its documentation. Or at least specify which one you are using here in this thread. It would definitely enable us to help you further.

And if you are not using any IDE, then please look at javac -cp option. However, it's much better idea to package your program in a jar file, and include all the required jars within that. Then, in order to execute your jar, like,

java -jar my_program.jar

you should have a META-INF/MANIFEST.MF file in your jar. See here, for how-to.

pip is not able to install packages correctly: Permission denied error

Set up a virtualenv:

% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py 
% sudo python /tmp/get-pip.py

These commands install pip into the global site-packages directory.

% sudo pip install virtualenv

and ditto for virtualenv:

% mkdir -p ~/.virtualenvs

I like my virtualenvs under one tree in my home directory called .virtualenvs

% virtualenv ~/.virtualenvs/lxmltest

Creates a virtualenv.

% . ~/.virtualenvs/lxmltest/bin/activate

Removes the need to specify the full path to pip/python in this virtualenv.

% pip install lxml

Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest and start again from a new virtualenv.

Get cursor position (in characters) within a text Input field

Perhaps you need a selected range in addition to cursor position. Here is a simple function, you don't even need jQuery:

function caretPosition(input) {
    var start = input[0].selectionStart,
        end = input[0].selectionEnd,
        diff = end - start;

    if (start >= 0 && start == end) {
        // do cursor position actions, example:
        console.log('Cursor Position: ' + start);
    } else if (start >= 0) {
        // do ranged select actions, example:
        console.log('Cursor Position: ' + start + ' to ' + end + ' (' + diff + ' selected chars)');
    }
}

Let's say you wanna call it on an input whenever it changes or mouse moves cursor position (in this case we are using jQuery .on()). For performance reasons, it may be a good idea to add setTimeout() or something like Underscores _debounce() if events are pouring in:

$('input[type="text"]').on('keyup mouseup mouseleave', function() {
    caretPosition($(this));
});

Here is a fiddle if you wanna try it out: https://jsfiddle.net/Dhaupin/91189tq7/

Calculate the mean by group

We already have tons of options to get mean by group, adding one more from mosaic package.

mosaic::mean(speed~dive, data = df)
#dive1 dive2 
#0.579 0.440 

This returns a named numeric vector, if needed a dataframe we can wrap it in stack

stack(mosaic::mean(speed~dive, data = df))

#  values   ind
#1  0.579 dive1
#2  0.440 dive2

data

set.seed(123)
df <- data.frame(dive=factor(sample(c("dive1","dive2"),10,replace=TRUE)),
                 speed=runif(10))

Adding extra zeros in front of a number using jQuery?

Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.

var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);

Create a pointer to two-dimensional array

You can do it like this:

uint8_t (*matrix_ptr)[10][20] = &l_matrix;

Global Angular CLI version greater than local version

This is how I fixed it. in Visual Studio Code's terminal, First cache clean

npm cache clean --force

Then updated cli

ng update @angular/cli

If any module missing after this, use below command

npm install

Character reading from file in Python

Ref: http://docs.python.org/howto/unicode

Reading Unicode from a file is therefore simple:

import codecs
with codecs.open('unicode.rst', encoding='utf-8') as f:
    for line in f:
        print repr(line)

It's also possible to open files in update mode, allowing both reading and writing:

with codecs.open('test', encoding='utf-8', mode='w+') as f:
    f.write(u'\u4500 blah blah blah\n')
    f.seek(0)
    print repr(f.readline()[:1])

EDIT: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII.

If you're trying to convert to an ASCII string, try one of the following:

  1. Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example

  2. Use the unicodedata module's normalize() and the string.encode() method to convert as best you can to the next closest ASCII equivalent (Ref https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python):

    >>> teststr
    u'I don\xe2\x80\x98t like this'
    >>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')
    'I donat like this'
    

How to print like printf in Python3?

The most recommended way to do is to use format method. Read more about it here

a, b = 1, 2

print("a={0},b={1}".format(a, b))

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

The problem is that I missed out 'db' folder for the dbpath in the command:

C:\mongodb\bin> mongod --directoryperdb --dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongodb.log --logappend -rest --install

break out of if and foreach

foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;
        break;
    }
}

Simply use break. That will do it.

Object reference not set to an instance of an object.

strSearch in this case is probably null (not simply empty).

Try using

String.IsNullOrEmpty(strSearch)

if you are just trying to determine if the string doesn't have any contents.

Create whole path automatically when writing to a new file

Something like:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);

Disable button after click in JQuery

*Updated

jQuery version would be something like below:

function load(recieving_id){
    $('#roommate_but').prop('disabled', true);
    $.get('include.inc.php?i=' + recieving_id, function(data) {
        $("#roommate_but").html(data);
    });
}

How to insert current_timestamp into Postgres via python

Just use

now()

or

CURRENT_TIMESTAMP

I prefer the latter as I like not having additional parenthesis but thats just personal preference.

How to make sure you don't get WCF Faulted state exception?

This error can also be caused by having zero methods tagged with the OperationContract attribute. This was my problem when building a new service and testing it a long the way.

Can I change the headers of the HTTP request sent by the browser?

Use some javascript!

xmlhttp=new XMLHttpRequest();
xmlhttp.open('PUT',http://www.mydomain.org/documents/standards/browsers/supportlist)
xmlhttp.send("page content goes here");

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

If you transferred these files through disk or other means, it is likely they were not saved properly.

How to create UILabel programmatically using Swift?

Create label in swift 4

 let label = UILabel(frame: CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.size.width, height: 50))
    label.textAlignment = .center
    label.text = "Hello this my label"

    //To set the color
    label.backgroundColor = UIColor.white
    label.textColor = UIColor.black

    //To set the font Dynamic
    label.font = UIFont(name: "Helvetica-Regular", size: 20.0)

    //To set the system font
    label.font = UIFont.systemFont(ofSize: 20.0)

    //To display multiple lines
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping //Wrap the word of label
    label.lineBreakMode = .byCharWrapping //Wrap the charactor of label

    label.sizeToFit()
    self.view.addSubview(label)

Division of integers in Java

In Java
Integer/Integer = Integer
Integer/Double = Double//Either of numerator or denominator must be floating point number
1/10 = 0
1.0/10 = 0.1
1/10.0 = 0.1

Just type cast either of them.

javascript cell number validation

If number is your form element, then its length will be undefined since elements don't have length. You want

if (number.value.length != 10) { ... }

An easier way to do all the validation at once, though, would be with a regex:

var val = number.value
if (/^\d{10}$/.test(val)) {
    // value is ok, use it
} else {
    alert("Invalid number; must be ten digits")
    number.focus()
    return false
}

\d means "digit," and {10} means "ten times." The ^ and $ anchor it to the start and end, so something like asdf1234567890asdf does not match.

How to bind Dataset to DataGridView in windows application

use like this :-

gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();

I hope it helps!!

How do I shrink my SQL Server Database?

I recently did this. I was trying to make a compact version of my database for testing on the road, but I just couldn't get it to shrink, no matter how many rows I deleted. Eventually, after many other commands in this thread, I found that my clustered indexes were not getting rebuilt after deleting rows. Rebuilding my indexes made it so I could shrink properly.

Conditional WHERE clause in SQL Server

This seemed easier to think about where either of two parameters could be passed into a stored procedure. It seems to work:

SELECT * 
FROM x 
WHERE CONDITION1
AND ((@pol IS NOT NULL AND x.PolicyNo = @pol) OR (@st IS NOT NULL AND x.State = @st))
AND OTHERCONDITIONS

Keras, How to get the output of each layer?

You can easily get the outputs of any layer by using: model.layers[index].output

For all layers use this:

from keras import backend as K

inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functors = [K.function([inp, K.learning_phase()], [out]) for out in outputs]    # evaluation functions

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = [func([test, 1.]) for func in functors]
print layer_outs

Note: To simulate Dropout use learning_phase as 1. in layer_outs otherwise use 0.

Edit: (based on comments)

K.function creates theano/tensorflow tensor functions which is later used to get the output from the symbolic graph given the input.

Now K.learning_phase() is required as an input as many Keras layers like Dropout/Batchnomalization depend on it to change behavior during training and test time.

So if you remove the dropout layer in your code you can simply use:

from keras import backend as K

inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functors = [K.function([inp], [out]) for out in outputs]    # evaluation functions

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = [func([test]) for func in functors]
print layer_outs

Edit 2: More optimized

I just realized that the previous answer is not that optimized as for each function evaluation the data will be transferred CPU->GPU memory and also the tensor calculations needs to be done for the lower layers over-n-over.

Instead this is a much better way as you don't need multiple functions but a single function giving you the list of all outputs:

from keras import backend as K

inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functor = K.function([inp, K.learning_phase()], outputs )   # evaluation function

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = functor([test, 1.])
print layer_outs

How to print environment variables to the console in PowerShell?

In addition to Mathias answer.

Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable:

$ Get-Variable

Name                           Value
----                           -----
$                              name
?                              True
^                              gci
args                           {}
ChocolateyTabSettings          @{AllCommands=False}
ConfirmPreference              High
DebugPreference                SilentlyContinue
EnabledExperimentalFeatures    {}
Error                          {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference          Continue
ErrorView                      NormalView
ExecutionContext               System.Management.Automation.EngineIntrinsics
false                          False
FormatEnumerationLimit         4
...

These also include stuff you may have set in your profile startup script.

How can I undo a mysql statement that I just executed?

Basically: If you're doing a transaction just do a rollback. Otherwise, you can't "undo" a MySQL query.

How can I get the active screen dimensions?

Beware of the scale factor of your windows (100% / 125% / 150% / 200%). You can get the real screen size by using the following code:

SystemParameters.FullPrimaryScreenHeight
SystemParameters.FullPrimaryScreenWidth

CSS get height of screen resolution

You actually don't need the screen resolution, what you want is the browser's dimensions because in many cases the the browser is windowed, and even in maximized size the browser won't take 100% of the screen.

what you want is View-port-height and View-port-width:

<div style="height: 50vh;width: 25vw"></div>

this will render a div with 50% of the inner browser's height and 25% of its width.

(to be honest this answer was part of what @Hendrik_Eichler wanted to say, but he only gave a link and didn't address the issue directly)

Disable Laravel's Eloquent timestamps

Eloquent Model:

class User extends Model    
{      
    protected $table = 'users';

    public $timestamps = false;
}

Or Simply try this

$users = new Users();
$users->timestamps = false;
$users->name = 'John Doe';
$users->email = '[email protected]';
$users->save();

Trust Store vs Key Store - creating with keytool

In simplest terms :

Keystore is used to store your credential (server or client) while truststore is used to store others credential (Certificates from CA).

Keystore is needed when you are setting up server side on SSL, it is used to store server's identity certificate, which server will present to a client on the connection while trust store setup on client side must contain to make the connection work. If you browser to connect to any website over SSL it verifies certificate presented by server against its truststore.

SQL Server principal "dbo" does not exist,

If the above does not work then try the following. It solved the problem for me even when the owner was well defined for the database.

SQL Server 2008 replication failing with: process could not execute 'sp_replcmds'

PNG transparency issue in IE8

PNG transparency pr?bl?m in IE8

Dan's solution worked for me. I was trying to fade a div with a background image. Caveats: you cannot fade the div directly, instead fade a wrapper image. Also, add the following filters to apply a background image:

-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png')"; /* IE8 */   
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png');   /* IE6 & 7 */      

Please note that the paths in the src attributes of the filters are absolute, and not relative to the css sheet.

I also added:

background: transparent\9;

This causes IE to ignore my earlier declaration of the actual background image for the other browsers.

Thanks Dan!!!

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

I tried Ricardo Stuven's way but it didn't work for me. What worked in the end was adding "compact": false to my .babelrc file:

{
    "compact": false,
    "presets": ["latest", "react", "stage-0"]
}

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

How to read the last row with SQL Server

If you don't have any ordered column, you can use the physical id of each lines:

SELECT top 1 sys.fn_PhysLocFormatter(%%physloc%%) AS [File:Page:Slot], 
              T.*
FROM MyTable As T
order by sys.fn_PhysLocFormatter(%%physloc%%) DESC

Java2D: Increase the line width

You should use setStroke to set a stroke of the Graphics2D object.

The example at http://www.java2s.com gives you some code examples.

The following code produces the image below:

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(10));
                g2.draw(new Line2D.Float(30, 20, 80, 90));
            }
        });
        jf.setSize(300, 200);
        jf.setVisible(true);
    }
}

enter image description here

(Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


This post has been rewritten as an article here.

Passing data to a bootstrap modal

Here is a cleaner way to do it if you are using Bootstrap 3.2.0.

Link HTML

<a href="#my_modal" data-toggle="modal" data-book-id="my_id_value">Open Modal</a>

Modal JavaScript

//triggered when modal is about to be shown
$('#my_modal').on('show.bs.modal', function(e) {

    //get data-id attribute of the clicked element
    var bookId = $(e.relatedTarget).data('book-id');

    //populate the textbox
    $(e.currentTarget).find('input[name="bookId"]').val(bookId);
});

http://jsfiddle.net/k7FC2/

modal View controllers - how to display and dismiss

Radu Simionescu - awesome work! and below Your solution for Swift lovers:

@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
    let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
    var presentingVC = self.presentingViewController
    self.dismissViewControllerAnimated(false, completion: { () -> Void   in
        presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
    })
}

Initialize/reset struct to zero/null

debugger screenshot

Take a surprise from gnu11!

typedef struct {
    uint8_t messType;
    uint8_t ax;  //axis
    uint32_t position;
    uint32_t velocity;
}TgotoData;

TgotoData tmpData = { 0 };

nothing is zero.

How to change the spinner background in Android?

Even though it is an older post but as I came across it while looking for same problem so I thought I will add my two cents as well. Here is my version of Spinner's background with DropDown arrow. Just the complete background, not only the arrow.

This is how it looks.. Screenshot of Spinner using spinner_bg.xml

Apply on spinner like...

<Spinner
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="@drawable/spinner_bg" />

spinner_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <color android:color="@color/InputBg" />
    </item>
    <item android:gravity="center_vertical|right" android:right="8dp">
        <layer-list>
            <item android:width="12dp" android:height="12dp" android:gravity="center" android:bottom="10dp">
                <rotate
                    android:fromDegrees="45"
                    android:toDegrees="45">
                    <shape android:shape="rectangle">
                        <solid android:color="#666666" />
                        <stroke android:color="#aaaaaa" android:width="1dp"/>
                    </shape>
                </rotate>
            </item>
            <item android:width="30dp" android:height="10dp" android:bottom="21dp" android:gravity="center">
                <shape android:shape="rectangle">
                    <solid android:color="@color/InputBg"/>
                </shape>
            </item>
        </layer-list>
    </item>
</layer-list>

@color/InputBg should be replaced by the color you want as your background.

First it fills the background with desired color. Then a child layer-list makes a square and rotates it by 45 degrees and then a second Rectangle with background color covers the top part of rotated square making it look like a down arrow. (There is an extra stroke in rotated rectangle with is not really required)

How to copy selected files from Android with adb pull

You can move your files to other folder and then pull whole folder.

adb shell mkdir /sdcard/tmp
adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir
adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end)
adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back
adb shell rmdir /sdcard/tmp # remove temporary directory

How to print last two columns using awk

You can make use of variable NF which is set to the total number of fields in the input record:

awk '{print $(NF-1),"\t",$NF}' file

this assumes that you have at least 2 fields.

HTML5 Video Stop onClose

Try this:

if ($.browser.msie)
{
   // Some other solution as applies to whatever IE compatible video player used.
}
else
{
   $('video')[0].pause();
}

But, consider that $.browser is deprecated, but I haven't found a comparable solution.

How to extract an assembly from the GAC?

One other direction--just unpack the MSI file and get the goodies that way. Saves you from the eventual uninstall . . .

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I've no idea why the other two answers are so popular!

I believe you were right in assuming the ORM framework should handle it - after all, that is what it promises to deliver. Otherwise your domain model gets corrupted by persistence concerns. NHibernate manages this happily if you setup the cascade settings correctly. In Entity Framework it is also possible, they just expect you to follow better standards when setting up your database model, especially when they have to infer what cascading should be done:

You have to define the parent - child relationship correctly by using an "identifying relationship".

If you do this, Entity Framework knows the child object is identified by the parent, and therefore it must be a "cascade-delete-orphans" situation.

Other than the above, you might need to (from NHibernate experience)

thisParent.ChildItems.Clear();
thisParent.ChildItems.AddRange(modifiedParent.ChildItems);

instead of replacing the list entirely.

UPDATE

@Slauma's comment reminded me that detached entities are another part of the overall problem. To solve that, you can take the approach of using a custom model binder that constructs your models by attempting to load it from the context. This blog post shows an example of what I mean.

What is the difference between mocking and spying when using Mockito?

The answer is in the documentation:

Real partial mocks (Since 1.8.0)

Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.

Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.

callRealMethod() was introduced after spy(), but spy() was left there of course, to ensure backward compatibility.

Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod() is called. In general, I would prefer using callRealMethod(), because it doesn't force me to use the doXxx().when() idiom instead of the traditional when().thenXxx()

PowerShell The term is not recognized as cmdlet function script file or operable program

Yet another way this error message can occur...

If PowerShell is open in a directory other than the target file, e.g.:

If someScript.ps1 is located here: C:\SlowLearner\some_missing_path\someScript.ps1, then C:\SlowLearner>. ./someScript.ps1 wont work.

In that case, navigate to the path: cd some_missing_path then this would work:

C:\SlowLearner\some_missing_path>. ./someScript.ps1

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

How to select rows in a DataFrame between two values, in Python Pandas?

there is a nicer alternative - use query() method:

In [58]: df = pd.DataFrame({'closing_price': np.random.randint(95, 105, 10)})

In [59]: df
Out[59]:
   closing_price
0            104
1             99
2             98
3             95
4            103
5            101
6            101
7             99
8             95
9             96

In [60]: df.query('99 <= closing_price <= 101')
Out[60]:
   closing_price
1             99
5            101
6            101
7             99

UPDATE: answering the comment:

I like the syntax here but fell down when trying to combine with expresison; df.query('(mean + 2 *sd) <= closing_price <=(mean + 2 *sd)')

In [161]: qry = "(closing_price.mean() - 2*closing_price.std())" +\
     ...:       " <= closing_price <= " + \
     ...:       "(closing_price.mean() + 2*closing_price.std())"
     ...:

In [162]: df.query(qry)
Out[162]:
   closing_price
0             97
1            101
2             97
3             95
4            100
5             99
6            100
7            101
8             99
9             95

Change background of LinearLayout in Android

 android:background="@drawable/ic_launcher"

should be included inside Layout tab. where ic_launcher is image name that u can put inside project folder/res/drawable . you can copy any number of images and make it as background

Xcode - Warning: Implicit declaration of function is invalid in C99

I have the same warning (it's make my app cannot build). When I add C function in Objective-C's .m file, But forgot to declared it at .h file.

What to do with commit made in a detached head

Create a branch where you are, then switch to master and merge it:

git branch my-temporary-work
git checkout master
git merge my-temporary-work

Select info from table where row has max date

SELECT group, date, checks
  FROM table 
  WHERE checks > 0
  GROUP BY group HAVING date = max(date) 

should work.

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

Write-Output should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it to out-default if nothing else uses it first.

Write-Host should be used when you want to do the opposite.

[console]::WriteLine is essentially what Write-Host is doing behind the scenes.

Run this demonstration code and examine the result.

function Test-Output {
    Write-Output "Hello World"
}

function Test-Output2 {
    Write-Host "Hello World" -foreground Green
}

function Receive-Output {
    process { Write-Host $_ -foreground Yellow }
}

#Output piped to another function, not displayed in first.
Test-Output | Receive-Output

#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output 

#Pipeline sends to Out-Default at the end.
Test-Output 

You'll need to enclose the concatenation operation in parentheses, so that PowerShell processes the concatenation before tokenizing the parameter list for Write-Host, or use string interpolation

write-host ("count=" + $count)
# or
write-host "count=$count"

BTW - Watch this video of Jeffrey Snover explaining how the pipeline works. Back when I started learning PowerShell I found this to be the most useful explanation of how the pipeline works.

Draw on HTML5 Canvas using a mouse

Googled this ("html5 canvas paint program"). Looks like what you need.

http://dev.opera.com/articles/view/html5-canvas-painting/

Eclipse/Java code completion not working

For those running Xfce + having IBus plugin activated, there might be keyboard shortcut conflict.

See more info on my blog: http://peter-butkovic.blogspot.de/2013/05/keyboard-shortcut-ctrlspace-caught-in.html

UPDATE:

as suggested by @nhahtdh's comment, adding the some more info to answer directly: IBus plugin in Xfce uses by default Ctrl+Space shortcut for keyboard layout switching. To change it, go to: Options and change it to whatever else you prefer.

Replace \n with actual new line in Sublime Text

On Windows, Sublime text,

You press Ctrl + H to replace \n by a new line created by Ctrl + Enter.

Replace : \n

By : (press Ctrl + Enter)

Field 'id' doesn't have a default value?

The id should set as auto-increment.

To modify an existing id column to auto-increment, just add this

ALTER TABLE card_games MODIFY id int NOT NULL AUTO_INCREMENT;

PHP Echo text Color

Try this

<?php 
echo '<i style="color:blue;font-size:30px;font-family:calibri ;">
      hello php color </i> ';
//we cannot use double quote after echo , it must be single quote.
?>

Git: How to remove file from index without deleting files from any repository

The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.

Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.

https://help.github.com/articles/remove-sensitive-data/

You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.

To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.

It looked intimidating at first, but really, was easy and worked like a charm ! :-)

Selenium WebDriver and DropDown Boxes

You can use this

(new SelectElement(driver.FindElement(By.Id(""))).SelectByText("");

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Vlookup is good if the reference values (column A, sheet 1) are in ascending order. Another option is Index and Match, which can be used no matter the order (As long as the values in column a, sheet 1 are unique)

This is what you would put in column B on sheet 2

=INDEX(Sheet1!A$1:B$6,MATCH(A1,Sheet1!A$1:A$6),2)

Setting Sheet1!A$1:B$6 and Sheet1!A$1:A$6 as named ranges makes it a little more user friendly.

Javascript can't find element by id?

How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,

window.onload = doStuff;

function doStuff() {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
}

The other alternative is to keep your <script...</script> just before the closing </body> tag.

Regular expression for decimal number

In .NET, I recommend to dynamically build the regular expression with the decimal separator of the current cultural context:

using System.Globalization;

...

NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
Regex re = new Regex("^(?\\d+(" 
                   + Regex.Escape(nfi.CurrencyDecimalSeparator) 
                   + "\\d{1,2}))$");

You might want to pimp the regexp by allowing 1000er separators the same way as the decimal separator.

How can I convert an RGB image into grayscale in Python?

Three of the suggested methods were tested for speed with 1000 RGBA PNG images (224 x 256 pixels) running with Python 3.5 on Ubuntu 16.04 LTS (Xeon E5 2670 with SSD).

Average run times

pil : 1.037 seconds

scipy: 1.040 seconds

sk : 2.120 seconds

PIL and SciPy gave identical numpy arrays (ranging from 0 to 255). SkImage gives arrays from 0 to 1. In addition the colors are converted slightly different, see the example from the CUB-200 dataset.

SkImage: SkImage

PIL : PIL

SciPy : SciPy

Original: Original

Diff : enter image description here

Code

  1. Performance

    run_times = dict(sk=list(), pil=list(), scipy=list())
    for t in range(100):
        start_time = time.time()
        for i in range(1000):
            z = random.choice(filenames_png)
            img = skimage.color.rgb2gray(skimage.io.imread(z))
        run_times['sk'].append(time.time() - start_time)

    start_time = time.time()
    for i in range(1000):
        z = random.choice(filenames_png)
        img = np.array(Image.open(z).convert('L'))
    run_times['pil'].append(time.time() - start_time)
    
    start_time = time.time()
    for i in range(1000):
        z = random.choice(filenames_png)
        img = scipy.ndimage.imread(z, mode='L')
    run_times['scipy'].append(time.time() - start_time)
    

    for k, v in run_times.items(): print('{:5}: {:0.3f} seconds'.format(k, sum(v) / len(v)))

  2. Output
    z = 'Cardinal_0007_3025810472.jpg'
    img1 = skimage.color.rgb2gray(skimage.io.imread(z)) * 255
    IPython.display.display(PIL.Image.fromarray(img1).convert('RGB'))
    img2 = np.array(Image.open(z).convert('L'))
    IPython.display.display(PIL.Image.fromarray(img2))
    img3 = scipy.ndimage.imread(z, mode='L')
    IPython.display.display(PIL.Image.fromarray(img3))
    
  3. Comparison
    img_diff = np.ndarray(shape=img1.shape, dtype='float32')
    img_diff.fill(128)
    img_diff += (img1 - img3)
    img_diff -= img_diff.min()
    img_diff *= (255/img_diff.max())
    IPython.display.display(PIL.Image.fromarray(img_diff).convert('RGB'))
    
  4. Imports
    import skimage.color
    import skimage.io
    import random
    import time
    from PIL import Image
    import numpy as np
    import scipy.ndimage
    import IPython.display
    
  5. Versions
    skimage.version
    0.13.0
    scipy.version
    0.19.1
    np.version
    1.13.1
    

Python threading.timer - repeat function every 'n' seconds

I like right2clicky's answer, especially in that it doesn't require a Thread to be torn down and a new one created every time the Timer ticks. In addition, it's an easy override to create a class with a timer callback that gets called periodically. That's my normal use case:

class MyClass(RepeatTimer):
    def __init__(self, period):
        super().__init__(period, self.on_timer)

    def on_timer(self):
        print("Tick")


if __name__ == "__main__":
    mc = MyClass(1)
    mc.start()
    time.sleep(5)
    mc.cancel()

C# DLL config file

As Marc says, this is not possible (although Visual Studio allows you to add an application configuration file in a class library project).

You might want to check out the AssemblySettings class which seems to make assembly config files possible.

How can I create download link in HTML?

To link to the file, do the same as any other page link:

<a href="...">link text</a>

To force things to download even if they have an embedded plugin (Windows + QuickTime = ugh), you can use this in your htaccess / apache2.conf:

AddType application/octet-stream EXTENSION

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

How to call code behind server method from a client side JavaScript function?

In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:

aspx code:

    <asp:Button runat="server" id="btnResponse1" Text="" 
    style="display: none; width:100%; height:100%"
    OnClick="btnResponses_Clicked" />

    <div class="circlebuttontext" id="calendarButtonText">Calendar</div>
</div>    

C# code behind:

protected void btnResponses_Clicked(object sender, EventArgs e)
{
    if(sender == btnResponse1)
    {
        //Your code behind logic for that button goes here
    }
}

How do I format currencies in a Vue component?

Try this:

methods: {
    formatPrice(value) {
        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'PHP',
            minimumFractionDigits: 2
        });
        return formatter.format(value);
    },
}

Then you can just call this like:

{{ formatPrice(item.total) }}

Decode HTML entities in Python string?

Python 3.4+

Use html.unescape():

import html
print(html.unescape('&pound;682m'))

FYI html.parser.HTMLParser.unescape is deprecated, and was supposed to be removed in 3.5, although it was left in by mistake. It will be removed from the language soon.


Python 2.6-3.3

You can use HTMLParser.unescape() from the standard library:

>>> try:
...     # Python 2.6-2.7 
...     from HTMLParser import HTMLParser
... except ImportError:
...     # Python 3
...     from html.parser import HTMLParser
... 
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

You can also use the six compatibility library to simplify the import:

>>> from six.moves.html_parser import HTMLParser
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

Error 405 (Method Not Allowed) Laravel 5

The methodNotAllowed exception indicates that a route doesn't exist for the HTTP method you are requesting.

Your form is set up to make a DELETE request, so your route needs to use Route::delete() to receive this.

Route::delete('empresas/eliminar/{id}', [
        'as' => 'companiesDelete',
        'uses' => 'CompaniesController@delete'
]);

How to display the first few characters of a string in Python?

Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'

Alternatively

>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'

Override standard close (X) button in a Windows Form

protected override bool ProcessCmdKey(ref Message msg, Keys dataKey)
    {
        if (dataKey == Keys.Escape)
        {
            this.Close();
            //this.Visible = false;
            //Plus clear values from form, if Visible false.
        }
        return base.ProcessCmdKey(ref msg, dataKey);
    }

Disable the postback on an <ASP:LinkButton>

Why not use an empty ajax update panel and wire the linkbutton's click event to it? This way only the update panel will get updated, thus avoiding a postback and allowing you to run your javascript

Client to send SOAP request and receive response

Call SOAP webservice in c#

using (var client = new UpdatedOutlookServiceReferenceAPI.OutlookServiceSoapClient("OutlookServiceSoap"))
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
    var result = client.UploadAttachmentBase64(GUID, FinalFileName, fileURL);

    if (result == true)
    {
        resultFlag = true;
    }
    else
    {
        resultFlag = false;
    }
    LogWriter.LogWrite1("resultFlag : " + resultFlag);
}

How to test if a DataSet is empty?

To check dataset is empty or not You have to check null and tables count.

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
da.Fill(ds);
if(ds != null && ds.Tables.Count > 0)
{
 // your code
}

iOS how to set app icon and launch images

As per updated version(Xcode 8.3.3) I saw that below resolution are required for all fields of AppIcon sets.

40x40
58x58
60x60
80x80
87x87
120x120
180x180

It comes with hdpi, xhdpi, xxhdpi etc. Hope it will helps others.

Edited to 120x120

Change MySQL root password in phpMyAdmin

you can use this command

 mysql> UPDATE mysql.user SET Password=PASSWORD('Your new Password') WHERE User='root';

check the links http://www.kirupa.com/forum/showthread.php?279644-How-to-reset-password-in-WAMP-server http://www.phpmytutor.com/blogs/2012/08/27/change-mysql-root-password-in-wamp-server/

Find your config.inc.php file under the phpMyAdmin installation directory and update the line that looks like
this:

$cfg['Servers'][$i]['password']      = 'password';

... to this:

 $cfg['Servers'][$i]['password']      = 'newpassword';

What special characters must be escaped in regular expressions?

Sometimes simple escaping is not possible with the characters you've listed. For example, using a backslash to escape a bracket isn't going to work in the left hand side of a substitution string in sed, namely

sed -e 's/foo\(bar/something_else/'

I tend to just use a simple character class definition instead, so the above expression becomes

sed -e 's/foo[(]bar/something_else/'

which I find works for most regexp implementations.

BTW Character classes are pretty vanilla regexp components so they tend to work in most situations where you need escaped characters in regexps.

Edit: After the comment below, just thought I'd mention the fact that you also have to consider the difference between finite state automata and non-finite state automata when looking at the behaviour of regexp evaluation.

You might like to look at "the shiny ball book" aka Effective Perl (sanitised Amazon link), specifically the chapter on regular expressions, to get a feel for then difference in regexp engine evaluation types.

Not all the world's a PCRE!

Anyway, regexp's are so clunky compared to SNOBOL! Now that was an interesting programming course! Along with the one on Simula.

Ah the joys of studying at UNSW in the late '70's! (-:

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

Insert NULL value into INT column

Just use the insert query and put the NULL keyword without quotes. That will work-

INSERT INTO `myDatabase`.`myTable` (`myColumn`) VALUES (NULL);

How do I use Linq to obtain a unique list of properties from a list of objects?

Using straight Linq, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();

How to embed PDF file with responsive width

_x000D_
_x000D_
<embed src="your.pdf" type="application/pdf#view=FitH" width="actual-width.px" height="actual-height.px"></embed>
_x000D_
_x000D_
_x000D_

Check this link for all PDF Parameters: https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=7

Chrome has its own PDF reader & all parameter don't work on chrome. Mozilla is worst for handling PDFs.

Open a Web Page in a Windows Batch FIle

You can use the start command to do much the same thing as ShellExecute. For example

 start "" http://www.stackoverflow.com

This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.

REST / SOAP endpoints for a WCF service

This post has already a very good answer by "Community wiki" and I also recommend to look at Rick Strahl's Web Blog, there are many good posts about WCF Rest like this.

I used both to get this kind of MyService-service... Then I can use the REST-interface from jQuery or SOAP from Java.

This is from my Web.Config:

<system.serviceModel>
 <services>
  <service name="MyService" behaviorConfiguration="MyServiceBehavior">
   <endpoint name="rest" address="" binding="webHttpBinding" contract="MyService" behaviorConfiguration="restBehavior"/>
   <endpoint name="mex" address="mex" binding="mexHttpBinding" contract="MyService"/>
   <endpoint name="soap" address="soap" binding="basicHttpBinding" contract="MyService"/>
  </service>
 </services>
 <behaviors>
  <serviceBehaviors>
   <behavior name="MyServiceBehavior">
    <serviceMetadata httpGetEnabled="true"/>
    <serviceDebug includeExceptionDetailInFaults="true" />
   </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
   <behavior name="restBehavior">
    <webHttp/>
   </behavior>
  </endpointBehaviors>
 </behaviors>
</system.serviceModel>

And this is my service-class (.svc-codebehind, no interfaces required):

    /// <summary> MyService documentation here ;) </summary>
[ServiceContract(Name = "MyService", Namespace = "http://myservice/", SessionMode = SessionMode.NotAllowed)]
//[ServiceKnownType(typeof (IList<MyDataContractTypes>))]
[ServiceBehavior(Name = "MyService", Namespace = "http://myservice/")]
public class MyService
{
    [OperationContract(Name = "MyResource1")]
    [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "MyXmlResource/{key}")]
    public string MyResource1(string key)
    {
        return "Test: " + key;
    }

    [OperationContract(Name = "MyResource2")]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "MyJsonResource/{key}")]
    public string MyResource2(string key)
    {
        return "Test: " + key;
    }
}

Actually I use only Json or Xml but those both are here for a demo purpose. Those are GET-requests to get data. To insert data I would use method with attributes:

[OperationContract(Name = "MyResourceSave")]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "MyJsonResource")]
public string MyResourceSave(string thing){
    //...

Hide text using css

<style>
body {
     visibility:hidden
}
body .moz-signature p{
    visibility:visible
}
</style>

The above works well in latest Thunderbird also.

Execute function after Ajax call is complete

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

How do I get interactive plots again in Spyder/IPython/matplotlib?

This is actually pretty easy to fix and doesn't take any coding:

1.Click on the Plots tab above the console. 2.Then at the top right corner of the plots screen click on the options button. 3.Lastly uncheck the "Mute inline plotting" button

Now re-run your script and your graphs should show up in the console.

Cheers.

how do I set height of container DIV to 100% of window height?

You can net set it to view height

html, body
{
    height: 100vh;
}

What are .a and .so files?

Archive libraries (.a) are statically linked i.e when you compile your program with -c option in gcc. So, if there's any change in library, you need to compile and build your code again.

The advantage of .so (shared object) over .a library is that they are linked during the runtime i.e. after creation of your .o file -o option in gcc. So, if there's any change in .so file, you don't need to recompile your main program. But make sure that your main program is linked to the new .so file with ln command.

This will help you to build the .so files. http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

Hope this helps.

Which @NotNull Java annotation should I use?

Eclipse has also its own annotations.

org.eclipse.jdt.annotation.NonNull

See at http://wiki.eclipse.org/JDT_Core/Null_Analysis for details.

javascript - replace dash (hyphen) with a space

Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.

var str = "This-is---a--news-----item----";

Then to replace all dashes with single spaces, you could do this:

var newStr = str.split('-').filter(function(item) {
  item = item ? item.replace(/-/g, ''): item
  return item;
}).join(' ');

Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:

item = item ? item.replace(/-/g, ''): item

The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.

Then when your string join runs on the filtered elements, you end up with this output:

"This is a news item"

Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.

Remove space above and below <p> tag HTML

Look here: http://www.w3schools.com/tags/tag_p.asp

The p element automatically creates some space before and after itself. The space is automatically applied by the browser, or you can specify it in a style sheet.

you could remove the extra space by using css

p {
   margin: 0px;
   padding: 0px;
}

or use the element <span> which has no default margins and is an inline element.