Programs & Examples On #Threadcontext

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

Swift do-try-catch syntax

Swift is worry that your case statement is not covering all cases, to fix it you need to create a default case:

do {
    let sandwich = try makeMeSandwich(kitchen)
    print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
    print("Not me error")
} catch SandwichError.DoItYourself {
    print("do it error")
} catch Default {
    print("Another Error")
}

Check if a class `active` exist on element with jquery

I think you want to use hasClass()

$('li.menu').hasClass('active');

HTTP authentication logout via PHP

The simple answer is that you can't reliably log out of http-authentication.

The long answer:
Http-auth (like the rest of the HTTP spec) is meant to be stateless. So being "logged in" or "logged out" isn't really a concept that makes sense. The better way to see it is to ask, for each HTTP request (and remember a page load is usually multiple requests), "are you allowed to do what you're requesting?". The server sees each request as new and unrelated to any previous requests.

Browsers have chosen to remember the credentials you tell them on the first 401, and re-send them without the user's explicit permission on subsequent requests. This is an attempt at giving the user the "logged in/logged out" model they expect, but it's purely a kludge. It's the browser that's simulating this persistence of state. The web server is completely unaware of it.

So "logging out", in the context of http-auth is purely a simulation provided by the browser, and so outside the authority of the server.

Yes, there are kludges. But they break RESTful-ness (if that's of value to you) and they are unreliable.

If you absolutely require a logged-in/logged-out model for your site authentication, the best bet is a tracking cookie, with the persistence of state stored on the server in some manner (mysql, sqlite, flatfile, etc). This will require all requests to be evaluated, for instance, with PHP.

A keyboard shortcut to comment/uncomment the select text in Android Studio

At least in Android Studio 2.2.3 with default key mapping, to comment or uncomment a select text, same hotkeys are used as Toggle. Using the hotkeys changes the state from comment to uncomment, and next time Uncomment to comment on next and vice versa.

1. Comment / uncomment a block of code

Comment sample: /* --- Code block ---- */

Hotkey: Ctrl + Shift + "/"

Using the same key combinations again will "toggle" commenting or uncommenting the selection.

2. Comment / uncomment a line of code

Comment sample: // -- Code ---

Hotkey: Ctrl + "/"

Using the same key combinations again will "toggle" commenting or uncommenting the selection.

Note: Key mapping can be changed to different schemes like eclipse, visual studio... or to the custom hotkeys in File -> Settings -> Keymap

Deserialize JSON string to c# object

I believe you are looking for this:

string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

Pandas "Can only compare identically-labeled DataFrame objects" error

At the time when this question was asked there wasn't another function in Pandas to test equality, but it has been added a while ago: pandas.equals

You use it like this:

df1.equals(df2)

Some differenes to == are:

  • You don't get the error described in the question
  • It returns a simple boolean.
  • NaN values in the same location are considered equal
  • 2 DataFrames need to have the same dtype to be considered equal, see this stackoverflow question

How to add headers to a multicolumn listbox in an Excel userform using VBA

Simple answer: no.

What I've done in the past is load the headings into row 0 then set the ListIndex to 0 when displaying the form. This then highlights the "headings" in blue, giving the appearance of a header. The form action buttons are ignored if the ListIndex remains at zero, so these values can never be selected.

Of course, as soon as another list item is selected, the heading loses focus, but by this time their job is done.

Doing things this way also allows you to have headings that scroll horizontally, which is difficult/impossible to do with separate labels that float above the listbox. The flipside is that the headings do not remain visible if the listbox needs to scroll vertically.

Basically, it's a compromise that works in the situations I've been in.

Node.js Web Application examples/tutorials

I would suggest you check out the various tutorials that are coming out lately. My current fav is:

http://nodetuts.com/

Hope this helps.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

The problem is due to older version of ojdbc - ojdbc14.

Place the latest version of ojdbc jar file in your application or shared library. (Only one version should be there and it should be the latest one) As of today - ojdbc6.jar

Check the application libraries and shared libraries on server.

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

Small update: Incase if you get below error in regard to node-sass follow the steps given below.

code EPERM
npm ERR! syscall unlink

steps to solve the issue:

  1. close visual studio
  2. manually remove .node-sass.DELETE from node_modules
  3. open visual studio
  4. npm cache verify
  5. npm install [email protected]

How to make popup look at the centre of the screen?

These are the changes to make:

CSS:

#container {
    width: 100%;
    height: 100%;
    top: 0;
    position: absolute;
    visibility: hidden;
    display: none;
    background-color: rgba(22,22,22,0.5); /* complimenting your modal colors */
}
#container:target {
    visibility: visible;
    display: block;
}
.reveal-modal {
    position: relative;
    margin: 0 auto;
    top: 25%;
}
    /* Remove the left: 50% */

HTML:

<a href="#container">Reveal</a>
<div id="container">
    <div id="exampleModal" class="reveal-modal">
    ........
    <a href="#">Close Modal</a>
    </div>
</div>

JSFiddle - Updated with CSS only

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has an AjaxSetup() function that allows you to register global ajax handlers such as beforeSend and complete for all ajax calls as well as allow you to access the xhr object to do the progress that you are looking for

C++ terminate called without an active exception

When a thread object goes out of scope and it is in joinable state, the program is terminated. The Standard Committee had two other options for the destructor of a joinable thread. It could quietly join -- but join might never return if the thread is stuck. Or it could detach the thread (a detached thread is not joinable). However, detached threads are very tricky, since they might survive till the end of the program and mess up the release of resources. So if you don't want to terminate your program, make sure you join (or detach) every thread.

TypeError: 'float' object not iterable

use

range(count)

int and float are not iterable

Create folder with batch but only if it doesn't already exist

This should work for you:

IF NOT EXIST "\path\to\your\folder" md \path\to\your\folder

However, there is another method, but it may not be 100% useful:

md \path\to\your\folder >NUL 2>NUL

This one creates the folder, but does not show the error output if folder exists. I highly recommend that you use the first one. The second one is if you have problems with the other.

kubectl apply vs kubectl create?

kubectl create can work with one object configuration file at a time. This is also known as imperative management

kubectl create -f filename|url

kubectl apply works with directories and its sub directories containing object configuration yaml files. This is also known as declarative management. Multiple object configuration files from directories can be picked up. kubectl apply -f directory/

Details :
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/ https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-config/

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

def upper(name: String) : String = { 
var uppper : String  =  name.toUpperCase()
uppper
}

val toUpperName = udf {(EmpName: String) => upper(EmpName)}
val emp_details = """[{"id": "1","name": "James Butt","country": "USA"},
{"id": "2", "name": "Josephine Darakjy","country": "USA"},
{"id": "3", "name": "Art Venere","country": "USA"},
{"id": "4", "name": "Lenna Paprocki","country": "USA"},
{"id": "5", "name": "Donette Foller","country": "USA"},
{"id": "6", "name": "Leota Dilliard","country": "USA"}]"""

val df_emp = spark.read.json(Seq(emp_details).toDS())
val df_name=df_emp.select($"id",$"name")
val df_upperName= df_name.withColumn("name",toUpperName($"name")).filter("id='5'")
display(df_upperName)

this will give error org.apache.spark.SparkException: Task not serializable at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:304)

Solution -

import java.io.Serializable;

object obj_upper extends Serializable { 
  def upper(name: String) : String = 
  {
    var uppper : String  =  name.toUpperCase()
    uppper
  }
val toUpperName = udf {(EmpName: String) => upper(EmpName)}
}

val df_upperName= 
df_name.withColumn("name",obj_upper.toUpperName($"name")).filter("id='5'")
display(df_upperName)

What is the size of an enum in C?

An enum is only guaranteed to be large enough to hold int values. The compiler is free to choose the actual type used based on the enumeration constants defined so it can choose a smaller type if it can represent the values you define. If you need enumeration constants that don't fit into an int you will need to use compiler-specific extensions to do so.

How can I find the product GUID of an installed MSI setup?

There is also a very helpful GUI tool called Product Browser which appears to be made by Microsoft or at least an employee of Microsoft.

It can be found on Github here Product Browser

I personally had a very easy time locating the GUID I needed with this.

set column width of a gridview in asp.net

Add HeaderStyle-Width and ItemStyle-width to TemplateFiels

 <asp:GridView ID="grdCanceled" runat="server" AutoGenerateColumns="false" OnPageIndexChanging="grdCanceled_PageIndexChanging"  AllowPaging="true" PageSize="15"
         CssClass="table table-condensed table-striped table-bordered" GridLines="None">
             <HeaderStyle BackColor="#00BCD4"  ForeColor="White" />
             <PagerStyle CssClass="pagination-ys" />
               <Columns>
            <asp:TemplateField HeaderText="Mobile NO" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                <ItemTemplate>
                  <%#Eval("mobile") %>
                </ItemTemplate>
               </asp:TemplateField>
           <asp:TemplateField HeaderText="Name" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                <ItemTemplate>
                    <%#Eval("name") %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                <ItemTemplate>
                    <%#Eval("city") %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Reason" HeaderStyle-Width="25%" ItemStyle-Width="25%">
                 <ItemTemplate>
                    <%#Eval("reson") %>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Agent" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                 <ItemTemplate>
                     <%#Eval("Agent") %>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Date" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                 <ItemTemplate>
                   <%#Eval("date","{0:dd-MMM-yy}") %>
                 </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderText="DList" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                  <ItemTemplate>
                      <%#Eval("service") %>
                  </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderText="EndDate" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                  <ItemTemplate>
                      <%#Eval("endDate","{0:dd-MMM-yy}") %>
                  </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderStyle-Width="5%" ItemStyle-Width="5%">
                  <ItemTemplate>
                       <asp:CheckBox data-needed='<%#Eval("userId") %>' ID="chkChecked" runat="server" />
                   </ItemTemplate>
               </asp:TemplateField>
             </Columns>
          </asp:GridView>

Advantages of std::for_each over for loop

With C++11 and two simple templates, you can write

        for ( auto x: range(v1+4,v1+6) ) {
                x*=2;
                cout<< x <<' ';
        }

as a replacement for for_each or a loop. Why choose it boils down to brevity and safety, there's no chance of error in an expression that's not there.

For me, for_each was always better on the same grounds when the loop body is already a functor, and I'll take any advantage I can get.

You still use the three-expression for, but now when you see one you know there's something to understand there, it's not boilerplate. I hate boilerplate. I resent its existence. It's not real code, there's nothing to learn by reading it, it's just one more thing that needs checking. The mental effort can be measured by how easy it is to get rusty at checking it.

The templates are

template<typename iter>
struct range_ { 
                iter begin() {return __beg;}    iter end(){return __end;}
            range_(iter const&beg,iter const&end) : __beg(beg),__end(end) {}
            iter __beg, __end;
};

template<typename iter>
range_<iter> range(iter const &begin, iter const &end)
    { return range_<iter>(begin,end); }

Stopping python using ctrl+c

The interrupt process is hardware and OS dependent. So you will have very different behavior depending on where you run your python script. For example, on Windows machines we have Ctrl+C (SIGINT) and Ctrl+Break (SIGBREAK).

So while SIGINT is present on all systems and can be handled and caught, the SIGBREAK signal is Windows specific (and can be disabled in CONFIG.SYS) and is really handled by the BIOS as an interrupt vector INT 1Bh, which is why this key is much more powerful than any other. So if you're using some *nix flavored OS, you will get different results depending on the implementation, since that signal is not present there, but others are. In Linux you can check what signals are available to you by:

$ kill -l
 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
 6) SIGABRT      7) SIGEMT       8) SIGFPE       9) SIGKILL     10) SIGBUS
11) SIGSEGV     12) SIGSYS      13) SIGPIPE     14) SIGALRM     15) SIGTERM
16) SIGURG      17) SIGSTOP     18) SIGTSTP     19) SIGCONT     20) SIGCHLD
21) SIGTTIN     22) SIGTTOU     23) SIGIO       24) SIGXCPU     25) SIGXFSZ
26) SIGVTALRM   27) SIGPROF     28) SIGWINCH    29) SIGPWR      30) SIGUSR1
31) SIGUSR2     32) SIGRTMAX

So if you want to catch the CTRL+BREAK signal on a linux system you'll have to check to what POSIX signal they have mapped that key. Popular mappings are:

CTRL+\     = SIGQUIT 
CTRL+D     = SIGQUIT
CTRL+C     = SIGINT
CTRL+Z     = SIGTSTOP 
CTRL+BREAK = SIGKILL or SIGTERM or SIGSTOP

In fact, many more functions are available under Linux, where the SysRq (System Request) key can take on a life of its own...

Getting MAC Address

The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in this activestate recipe

#!/usr/bin/python

import fcntl, socket, struct

def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    return ':'.join(['%02x' % ord(char) for char in info[18:24]])

print getHwAddr('eth0')

This is the Python 3 compatible code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import fcntl
import socket
import struct


def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
    return ':'.join('%02x' % b for b in info[18:24])


def main():
    print(getHwAddr('enp0s8'))


if __name__ == "__main__":
    main()

Mocking methods of local scope objects with Mockito

You could avoid changing the code (although I recommend Boris' answer) and mock the constructor, like in this example for mocking the creation of a File object inside a method. Don't forget to put the class that will create the file in the @PrepareForTest.

package hello.easymock.constructor;

import java.io.File;

import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
    
@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {
        
    @Test
    public void testMockFile() throws Exception {

        // first, create a mock for File
        final File fileMock = EasyMock.createMock(File.class);
        EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
        EasyMock.replay(fileMock);

        // then return the mocked object if the constructor is invoked
        Class<?>[] parameterTypes = new Class[] { String.class };
        PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
        PowerMock.replay(File.class); 
    
        // try constructing a real File and check if the mock kicked in
        final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
        Assert.assertEquals("/my/fake/file/path", mockedFilePath);
    }
}

how to call a variable in code behind to aspx page

The field must be declared public for proper visibility from the ASPX markup. In any case, you could declare a property:


private string clients;
public string Clients { get { return clients; } }

UPDATE: It can also be declared as protected, as stated in the comments below.

Then, to call it on the ASPX side:

<%=Clients%>

Note that this won't work if you place it on a server tag attribute. For example:

<asp:Label runat="server" Text="<%=Clients%>" />

This isn't valid. This is:

<div><%=Clients%></div>

How can I determine whether a specific file is open in Windows?

In OpenedFilesView, under the Options menu, there is a menu item named "Show Network Files". Perhaps with that enabled, the aforementioned utility is of some use.

How to make a round button?

You can use google's FloatingActionButton

XMl:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@android:drawable/ic_dialog_email" />

Java:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FloatingActionButton bold = (FloatingActionButton) findViewById(R.id.fab);
    bold.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        // Do Stuff
        }
    });
}

Gradle:

    compile 'com.android.support:design:23.4.0'

Get selected element's outer HTML

This is quite simple with vanilla JavaScript...

document.querySelector('#selector')

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

For Vb.Net Framework 4.0, U can use:

Alert("your message here", Boolean)

The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.

Convert a number into a Roman Numeral in javaScript

_x000D_
_x000D_
function convertToRoman(num) {_x000D_
    var arr = [];_x000D_
    for (var i = 0; i < num.toString().length; i++) {_x000D_
        arr.push(Number(num.toString().substr(i, 1)));_x000D_
    }_x000D_
    var romanArr = [_x000D_
        ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"],_x000D_
        ["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"],_x000D_
        ["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"],_x000D_
        ["M"]_x000D_
    ];_x000D_
    var roman = arr.reverse().map(function (val, i) {_x000D_
        if (val === 0) {_x000D_
            return "";_x000D_
        }_x000D_
        if (i === 3) {_x000D_
            var r = "";_x000D_
            for (var j = 0; j < val; j++) {_x000D_
                r += romanArr[i][0];_x000D_
            }_x000D_
            return r;_x000D_
        } else {_x000D_
            return romanArr[i][val - 1];_x000D_
        }_x000D_
    });_x000D_
    console.log(roman.reverse().join(""));_x000D_
    return roman.join("");_x000D_
}_x000D_
_x000D_
_x000D_
convertToRoman(10);
_x000D_
_x000D_
_x000D_

How to edit the size of the submit button on a form?

just use style attribute with height and width option

<input type="submit" id="search" value="Search"  style="height:50px; width:50px" />

How do I determine the current operating system with Node.js

You are looking for the OS native module for Node.js:

v4: https://nodejs.org/dist/latest-v4.x/docs/api/os.html#os_os_platform

or v5 : https://nodejs.org/dist/latest-v5.x/docs/api/os.html#os_os_platform

os.platform()

Returns the operating system platform. Possible values are 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of process.platform.

JBoss vs Tomcat again

First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.

Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.

How to decide whether to use Tomcat or a full stack Java EE application server:

When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:

  1. JMS messaging for asynchronous integration
  2. Web Services engine (JAX-WS and/or JAX-RS)
  3. Management capabilities like JMX and a scripted administration interface
  4. Advanced security, e.g. out-of-the-box integration with 3rd party directories
  5. EAR file instead of "only" WAR file support
  6. all the other "great" Java EE features I can't remember :-)

In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.

Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.

my 2 cent

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

The cause of this problem could be a property setting of the database (Sql2008R2 with .NET4).

  • Problem is reproducible at will when changing the COLLATION value of a database.

To display COLLLATION, use the Sql Server Mgmt Studio.

  • Right-click the database and select Properties -> General, Then look under Maintenance for the COLLATION value

To change COLLATION, (still) use the Sql Server Mgmt Studio.

  • Right-click the database and select Properties -> Options, From there, you can change the COLLATION value

Laravel 5: Retrieve JSON array from $request

You need to change your Ajax call to

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    contentType: "json",
    processData: false,
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

change the dataType to contentType and add the processData option.

To retrieve the JSON payload from your controller, use:

dd(json_decode($request->getContent(), true));

instead of

dd($request->all());

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How to update and order by using ms sql

As stated in comments below, you can use also the SET ROWCOUNT clause, but just for SQL Server 2014 and older.

SET ROWCOUNT 10

UPDATE messages
SET status = 10 
WHERE status = 0 

SET ROWCOUNT 0

More info: http://msdn.microsoft.com/en-us/library/ms188774.aspx

Or with a temp table

DECLARE @t TABLE (id INT)
INSERT @t (id)
SELECT TOP 10 id
FROM messages
WHERE status = 0
ORDER BY priority DESC

UPDATE messages
SET status = 10
WHERE id IN (SELECT id FROM @t)

How do I break out of a loop in Scala?

Close to your solution would be this:

var largest = 0
for (i <- 999 to 1 by -1;
  j <- i to 1 by -1;
  product = i * j;
  if (largest <= product && product.toString.reverse.equals (product.toString.reverse.reverse)))
    largest = product

println (largest)

The j-iteration is made without a new scope, and the product-generation as well as the condition are done in the for-statement (not a good expression - I don't find a better one). The condition is reversed which is pretty fast for that problem size - maybe you gain something with a break for larger loops.

String.reverse implicitly converts to RichString, which is why I do 2 extra reverses. :) A more mathematical approach might be more elegant.

Rails Active Record find(:all, :order => ) issue

Make sure to check the schema at the database level directly. I've gotten burned by this before, where, for example, a migration was initially written to create a :datetime column, and I ran it locally, then tweaked the migration to a :date before actually deploying. Thus everyone's database looks good except for mine, and the bugs are subtle.

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

I know this may sound absurd, but I solved a similar issue by creating the database as "phpMyAdmin" not "phpmyadmin" (note case) - perhaps there is something about case-sensitivity under Windows?

how to prevent adding duplicate keys to a javascript array

Generally speaking, this is better accomplished with an object instead since JavaScript doesn't really have associative arrays:

var foo = { bar: 0 };

Then use in to check for a key:

if ( !( 'bar' in foo ) ) {
    foo['bar'] = 42;
}

As was rightly pointed out in the comments below, this method is useful only when your keys will be strings, or items that can be represented as strings (such as numbers).

What does SQL clause "GROUP BY 1" mean?

That means sql group by 1st column in your select clause, we always use this GROUP BY 1 together with ORDER BY 1, besides you can also use like this GROUP BY 1,2,3.., of course it is convenient for us but you need to pay attention to that condition the result may be not what you want if some one has modified your select columns, and it's not visualized

How do I search a Perl array for a matching string?

For just a boolean match result or for a count of occurrences, you could use:

use 5.014; use strict; use warnings;
my @foo=('hello', 'world', 'foo', 'bar', 'hello world', 'HeLlo');
my $patterns=join(',',@foo);
for my $str (qw(quux world hello hEllO)) {
    my $count=map {m/^$str$/i} @foo;
    if ($count) {
        print "I found '$str' $count time(s) in '$patterns'\n";
    } else {
        print "I could not find '$str' in the pattern list\n"
    };
}

Output:

I could not find 'quux' in the pattern list
I found 'world' 1 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hello' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hEllO' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'

Does not require to use a module.
Of course it's less "expandable" and versatile as some code above.
I use this for interactive user answers to match against a predefined set of case unsensitive answers.

In plain English, what does "git reset" do?

The post Reset Demystified in the blog Pro Git gives a very no-brainer explanation on git reset and git checkout.

After all the helpful discussion at the top of that post, the author reduces the rules to the following simple three steps:

That is basically it. The reset command overwrites these three trees in a specific order, stopping when you tell it to.

  1. Move whatever branch HEAD points to (stop if --soft)
  2. THEN, make the Index look like that (stop here unless --hard)
  3. THEN, make the Working Directory look like that

There are also --merge and --keep options, but I would rather keep things simpler for now - that will be for another article.

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.

However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.

What's the best way to dedupe a table?

Deduping is rarely simple. That's because the records to be dedupped often have slightly different values is some of the fields. Therefore choose which record to keep can be problematic. Further, dups are often people records and it is hard to identify if the two John Smith's are two people or one person who is duplicated. So spend a lot (50% or more of the whole project) of your time defining what constitutes a dup and how to handle the differences and child records.

How do you know which is the correct value? Further dedupping requires that you handle all child records not orphaning any. What happens when you find that by changing the id on the child record you are suddenly violating one of the unique indexes or constraints - this will happen eventually and your process needs to handle it. If you have chosen foolishly to apply all your constraints only thorough the application, you may not even know the constraints are violated. When you have 10,000 records to dedup, you aren't going to go through the application to dedup one at a time. If the constraint isn't in the database, lots of luck in maintaining data integrity when you dedup.

A further complication is that dups don't always match exactly on the name or address. For instance a salesrep named Joan Martin may be a dup of a sales rep names Joan Martin-Jones especially if they have the same address and email. OR you could have John or Johnny in the name. Or the same street address except one record abbreveiated ST. and one spelled out Street. In SQL server you can use SSIS and fuzzy grouping to also identify near matches. These are often the most common dups as the fact that weren't exact matches is why they got put in as dups in the first place.

For some types of dedupping, you may need a user interface, so that the person doing the dedupping can choose which of two values to use for a particular field. This is especially true if the person who is being dedupped is in two or more roles. It could be that the data for a particular role is usually better than the data for another role. Or it could be that only the users will know for sure which is the correct value or they may need to contact people to find out if they are genuinely dups or simply two people with the same name.

FirstOrDefault returns NullReferenceException if no match is found

Simply use the question mark trick for null checks:

string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID))?.Value.DisplayName ?? "DEFINE A DEFAULT DISPLAY NAME HERE";

Why won't eclipse switch the compiler to Java 8?

This is a old topic but I just wanted to point out that I have searched enough to find that Indigo version can't be updated to S.E 1.8 here the link which is given on eclipse website to update the Execution Environment but if you try it will throw error for Indigo.

Image//wiki.eclipse.org/File:ExecutionEnvironmentDescriptionInstallation.png this is the link where the Information about execution environment is given.

https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler This shows the step by step to update Execution environment.

I have tried to update Execution environment and I got the same error.

Import Google Play Services library in Android Studio

Try this once and make sure you are not getting any error in project Structure saying that "ComGoogleAndroidGmsPlay not added"

Open File > Project Structure and check for below all. If error is shown click on Red bulb marked and click on "Add to dependency".

GMS dependency

This is a bug in Android Studio and fixed for the next release(0.4.3)

Common sources of unterminated string literal

Scan the code that comes before the line# mentioned by error message. Whatever is unterminated has resulted in something downstream, (the blamed line#), to be flagged.

What is the ultimate postal code and zip regex?

Somebody was asking about list of formatting mailing addresses, and I think this is what he was looking for...

Frank's Compulsive Guide to Postal Addresses: http://www.columbia.edu/~fdc/postal/ Doesn't help much with street-level issues, however.

My work uses a couple of tools to assist with this: - Lexis-Nexis services, including NCOA lookups (you'll get address standardization for "free") - "Melissa Data" http://www.melissadata.com

How do I get HTTP Request body content in Laravel?

Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:

public function foo(Request $request){
    $bodyContent = $request->getContent();
}

How to use JavaScript to change div backgroundColor

If you are willing to insert non-semantic nodes into your document, you can do this in a CSS-only IE-compatible manner by wrapping your divs in fake A tags.

<style type="text/css">
  .content {
    background: #ccc;
  }

  .fakeLink { /* This is to make the link not look like one */
    cursor: default;
    text-decoration: none;
    color: #000;
  }

  a.fakeLink:hover .content {
    background: #000;
    color: #fff;
  }

</style>
<div id="catestory">

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

</div>

Android view pager with page indicator

you have to do following:

1-Download the full project from here https://github.com/JakeWharton/ViewPagerIndicator ViewPager Indicator 2- Import into the Eclipse.

After importing if you want to make following type of screen then follow below steps -

Screen Shot

change in

Sample circles Default

  package com.viewpagerindicator.sample;
  import android.os.Bundle;  
  import android.support.v4.view.ViewPager;
  import com.viewpagerindicator.CirclePageIndicator;

  public class SampleCirclesDefault extends BaseSampleActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_circles);

    mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
  //  mPager.setAdapter(mAdapter);

    ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
    mPager.setAdapter(adapter);


    mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
  }
}

ImageAdapter

 package com.viewpagerindicator.sample;

 import android.content.Context;
 import android.support.v4.view.PagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageView;
 import android.widget.TextView;

 public class ImageAdapter extends PagerAdapter {
 private Context mContext;

 private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
        R.drawable.about3, R.drawable.about4, R.drawable.about5,
        R.drawable.about6, R.drawable.about7

 };

 public ImageAdapter(Context context) {
    mContext = context;
 }

 public int getCount() {
    return mImageIds.length;
 }

 public Object getItem(int position) {
    return position;
 }

 public long getItemId(int position) {
    return position;
 }

 @Override
 public Object instantiateItem(ViewGroup container, final int position) {

    LayoutInflater inflater = (LayoutInflater) container.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View convertView = inflater.inflate(R.layout.gallery_view, null);

    ImageView view_image = (ImageView) convertView
            .findViewById(R.id.view_image);
    TextView description = (TextView) convertView
            .findViewById(R.id.description);

    view_image.setImageResource(mImageIds[position]);
    view_image.setScaleType(ImageView.ScaleType.FIT_XY);

    description.setText("The natural habitat of the Niligiri tahr,Rajamala          Rajamala is 2695 Mts above sea level"
        + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
                    + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");

    ((ViewPager) container).addView(convertView, 0);

    return convertView;
 }

 @Override
 public boolean isViewFromObject(View view, Object object) {
    return view == ((View) object);
 }

 @Override
 public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager) container).removeView((ViewGroup) object);
 }
}

gallery_view.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/about_bg"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/about_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <LinearLayout
        android:id="@+id/about_layout1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".4"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/view_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:background="@drawable/about1">
     </ImageView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/about_layout2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".6"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
            android:textColor="#000000"
            android:gravity="center"
            android:padding="18dp"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearance" />


        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:fillViewport="false"
            android:orientation="vertical"
            android:scrollbars="none"
            android:layout_marginBottom="10dp"
            android:padding="10dp" >

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="#000000"
                android:text="TextView" />

            </ScrollView>
    </LinearLayout>
 </LinearLayout>

SMTPAuthenticationError when sending mail using gmail and python

I have just sent an email with gmail through Python. Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.

So, you may get a chance with:

server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)

As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.

Get protocol + host name from URL

It could be solved by re.search()

import re
url = 'https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1'
result = re.search(r'^http[s]*:\/\/[\w\.]*', url).group()
print(result)

#result
'https://docs.google.com'

Get selected row item in DataGrid WPF

There are a lot of answers here that probably work in a specific context, but I was simply trying to get the text value of the first cell in a selected row. While the accepted answer here was the closest for me, it still required creating a type and casting the row into that type. I was looking for a simpler solution, and this is what I came up with:

MessageBox.Show(((DataRowView)DataGrid.SelectedItem).Row[0].ToString());

This gives me the first column in the selected row. Hopefully this helps someone else.

How to make a JSON call to a url?

It seems they offer a js option for the format parameter, which will return JSONP. You can retrieve JSONP like so:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  

Issue with adding common code as git submodule: "already exists in the index"

I got it working by doing it the other way around. Starting with an empty repo, adding the submodule in a new folder called "projectfolder/common_code". After that it was possible to add the project code in projectfolder. The details are shown below.

In an empty repo type:

git submodule add url_to_repo projectfolder/common_code

That will create the desired folder structure:

repo
|-- projectfolder
    |-- common_code

It is now possible to add more submodules, and the project code can be added to projectfolder.

I can't yet say why it worked this way around and not the other.

Large Numbers in Java

Depending on what you're doing you might like to take a look at GMP (gmplib.org) which is a high-performance multi-precision library. To use it in Java you need JNI wrappers around the binary library.

See some of the Alioth Shootout code for an example of using it instead of BigInteger to calculate Pi to an arbitrary number of digits.

https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/pidigits-java-2.html

How to config routeProvider and locationProvider in angularJS?

The only issue I see are relative links and templates not being properly loaded because of this.

from the docs regarding HTML5 mode

Relative links

Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (<base href="/my-base">) or you must use absolute urls (starting with /) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.

In your case you can add a forward slash / in href attributes ($location.path does this automatically) and also to templateUrl when configuring routes. This avoids routes like example.com/tags/another and makes sure templates load properly.

Here's an example that works:

<div>
    <a href="/">Home</a> | 
    <a href="/another">another</a> | 
    <a href="/tags/1">tags/1</a>
</div>
<div ng-view></div>

And

app.config(function($locationProvider, $routeProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
    .when('/', {
      templateUrl: '/partials/template1.html', 
      controller: 'ctrl1'
    })
    .when('/tags/:tagId', {
      templateUrl: '/partials/template2.html', 
      controller:  'ctrl2'
    })
    .when('/another', {
      templateUrl: '/partials/template1.html', 
      controller:  'ctrl1'
    })
    .otherwise({ redirectTo: '/' });
});

If using Chrome you will need to run this from a server.

Swift - iOS - Dates and times in different format

Here is a solution that works with Xcode 10.1 (FEB 23 2019) :

func getCurrentDateTime() {

    let now = Date()
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "fr_FR")
    formatter.dateFormat = "EEEE dd MMMM YYYY"
    labelDate.text = formatter.string(from: now)
    labelDate.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
    labelDate.textColor = UIColor.lightGray

    let text = formatter.string(from: now)
    labelDate.text = text.uppercased()
}

The "Accueil" Label is not connected to the code.

Java - Reading XML file

Reading xml the easy way:

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

.

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

          } catch (JAXBException e) {
              e.printStackTrace();
          }

    }
}

How to maintain aspect ratio using HTML IMG tag

Set width and height of the images to auto, but limit both max-width and max-height:

img {
    max-width:64px;
    max-height:64px;
    width:auto;
    height:auto;
}

Fiddle

If you want to display images of arbitrary size in the 64x64px "frames", you can use inline-block wrappers and positioning for them, like in this fiddle.

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

How to read text files with ANSI encoding and non-English letters?

You get the question-mark-diamond characters when your textfile uses high-ANSI encoding -- meaning it uses characters between 127 and 255. Those characters have the eighth (i.e. the most significant) bit set. When ASP.NET reads the textfile it assumes UTF-8 encoding, and that most significant bit has a special meaning.

You must force ASP.NET to interpret the textfile as high-ANSI encoding, by telling it the codepage is 1252:

String textFilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath("~/textfiles/MyInputFile.txt");
String contents = File.ReadAllText(textFilePhysicalPath, System.Text.Encoding.GetEncoding(1252));
lblContents.Text = contents.Replace("\n", "<br />");  // change linebreaks to HTML

CSS "and" and "or"

To select properties a AND b of a X element:

X[a][b]

To select properties a OR b of a X element:

X[a],X[b]

Rock, Paper, Scissors Game Java

Before we try to solve the invalid character problem, the lack of curly braces around the if and else if statements is wreaking havoc on your program's logic. Change it to this:

if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}
else 
     System.out.println("Invalid user input.");

Much clearer! It's now actually a piece of cake to catch the bad characters. You need to move the else statement to somewhere that will catch the errors before you attempt to process anything else. So change everything to:

if( /* insert your check for bad characters here */ ) { 
     System.out.println("Invalid user input.");
}
else if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}

Reading a binary input stream into a single byte array in Java

Max value for array index is Integer.MAX_INT - it's around 2Gb (2^31 / 2 147 483 647). Your input stream can be bigger than 2Gb, so you have to process data in chunks, sorry.

        InputStream is;
        final byte[] buffer = new byte[512 * 1024 * 1024]; // 512Mb
        while(true) {
            final int read = is.read(buffer);
            if ( read < 0 ) {
                break;
            }
            // do processing 
        }

Get absolute path to workspace directory in Jenkins Pipeline plugin

For me WORKSPACE was a valid property of the pipeline itself. So when I handed over this to a Groovy method as parameter context from the pipeline script itself, I was able to access the correct value using "... ${context.WORKSPACE} ..."

(on Jenkins 2.222.3, Build Pipeline Plugin 1.5.8, Pipeline: Nodes and Processes 2.35)

How can I view an object with an alert()

Try this:

alert(JSON.parse(product) );

Difference between timestamps with/without time zone in PostgreSQL

Here is an example that should help. If you have a timestamp with a timezone, you can convert that timestamp into any other timezone. If you haven't got a base timezone it won't be converted correctly.

SELECT now(),
   now()::timestamp,
   now() AT TIME ZONE 'CST',
   now()::timestamp AT TIME ZONE 'CST'

Output:

-[ RECORD 1 ]---------------------------
now      | 2018-09-15 17:01:36.399357+03
now      | 2018-09-15 17:01:36.399357
timezone | 2018-09-15 08:01:36.399357
timezone | 2018-09-16 02:01:36.399357+03

Operator overloading on class templates

This helped me with the exact same problem.

Solution:

  1. Forward declare the friend function before the definition of the class itself. For example:

       template<typename T> class MyClass;  // pre-declare the template class itself
       template<typename T> std::ostream& operator<< (std::ostream& o, const MyClass <T>& x);
    
  2. Declare your friend function in your class with "<>" appended to the function name.

       friend std::ostream& operator<< <> (std::ostream& o, const Foo<T>& x);
    

Python 3 sort a dict by its values

To sort a dictionary and keep it functioning as a dictionary afterwards, you could use OrderedDict from the standard library.

If that's not what you need, then I encourage you to reconsider the sort functions that leave you with a list of tuples. What output did you want, if not an ordered list of key-value pairs (tuples)?

How to create a TextArea in Android

Its really simple, write this code in XML:

<EditText
    android:id="@+id/fname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="First Name"
/>

How to parse freeform street/postal address out of text, and into components

No code? For shame!

Here is a simple JavaScript address parser. It's pretty awful for every single reason that Matt gives in his dissertation above (which I almost 100% agree with: addresses are complex types, and humans make mistakes; better to outsource and automate this - when you can afford to).

But rather than cry, I decided to try:

This code works OK for parsing most Esri results for findAddressCandidate and also with some other (reverse)geocoders that return single-line address where street/city/state are delimited by commas. You can extend if you want or write country-specific parsers. Or just use this as case study of how challenging this exercise can be or at how lousy I am at JavaScript. I admit I only spent about thirty mins on this (future iterations could add caches, zip validation, and state lookups as well as user location context), but it worked for my use case: End user sees form that parses geocode search response into 4 textboxes. If address parsing comes out wrong (which is rare unless source data was poor) it's no big deal - the user gets to verify and fix it! (But for automated solutions could either discard/ignore or flag as error so dev can either support the new format or fix source data.)

_x000D_
_x000D_
/* _x000D_
address assumptions:_x000D_
- US addresses only (probably want separate parser for different countries)_x000D_
- No country code expected._x000D_
- if last token is a number it is probably a postal code_x000D_
-- 5 digit number means more likely_x000D_
- if last token is a hyphenated string it might be a postal code_x000D_
-- if both sides are numeric, and in form #####-#### it is more likely_x000D_
- if city is supplied, state will also be supplied (city names not unique)_x000D_
- zip/postal code may be omitted even if has city & state_x000D_
- state may be two-char code or may be full state name._x000D_
- commas: _x000D_
-- last comma is usually city/state separator_x000D_
-- second-to-last comma is possibly street/city separator_x000D_
-- other commas are building-specific stuff that I don't care about right now._x000D_
- token count:_x000D_
-- because units, street names, and city names may contain spaces token count highly variable._x000D_
-- simplest address has at least two tokens: 714 OAK_x000D_
-- common simple address has at least four tokens: 714 S OAK ST_x000D_
-- common full (mailing) address has at least 5-7:_x000D_
--- 714 OAK, RUMTOWN, VA 59201_x000D_
--- 714 S OAK ST, RUMTOWN, VA 59201_x000D_
-- complex address may have a dozen or more:_x000D_
--- MAGICICIAN SUPPLY, LLC, UNIT 213A, MAGIC TOWN MALL, 13 MAGIC CIRCLE DRIVE, LAND OF MAGIC, MA 73122-3412_x000D_
*/_x000D_
_x000D_
var rawtext = $("textarea").val();_x000D_
var rawlist = rawtext.split("\n");_x000D_
_x000D_
function ParseAddressEsri(singleLineaddressString) {_x000D_
  var address = {_x000D_
    street: "",_x000D_
    city: "",_x000D_
    state: "",_x000D_
    postalCode: ""_x000D_
  };_x000D_
_x000D_
  // tokenize by space (retain commas in tokens)_x000D_
  var tokens = singleLineaddressString.split(/[\s]+/);_x000D_
  var tokenCount = tokens.length;_x000D_
  var lastToken = tokens.pop();_x000D_
  if (_x000D_
    // if numeric assume postal code (ignore length, for now)_x000D_
    !isNaN(lastToken) ||_x000D_
    // if hyphenated assume long zip code, ignore whether numeric, for now_x000D_
    lastToken.split("-").length - 1 === 1) {_x000D_
    address.postalCode = lastToken;_x000D_
    lastToken = tokens.pop();_x000D_
  }_x000D_
_x000D_
  if (lastToken && isNaN(lastToken)) {_x000D_
    if (address.postalCode.length && lastToken.length === 2) {_x000D_
      // assume state/province code ONLY if had postal code_x000D_
      // otherwise it could be a simple address like "714 S OAK ST"_x000D_
      // where "ST" for "street" looks like two-letter state code_x000D_
      // possibly this could be resolved with registry of known state codes, but meh. (and may collide anyway)_x000D_
      address.state = lastToken;_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
    if (address.state.length === 0) {_x000D_
      // check for special case: might have State name instead of State Code._x000D_
      var stateNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found separator, ignore stuff on left side_x000D_
          tokens.push(lastToken); // put it back_x000D_
          break;_x000D_
        } else {_x000D_
          stateNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.state = stateNameParts.join(' ');_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
  }_x000D_
_x000D_
  if (lastToken) {_x000D_
    // here is where it gets trickier:_x000D_
    if (address.state.length) {_x000D_
      // if there is a state, then assume there is also a city and street._x000D_
      // PROBLEM: city may be multiple words (spaces)_x000D_
      // but we can pretty safely assume next-from-last token is at least PART of the city name_x000D_
      // most cities are single-name. It would be very helpful if we knew more context, like_x000D_
      // the name of the city user is in. But ignore that for now._x000D_
      // ideally would have zip code service or lookup to give city name for the zip code._x000D_
      var cityNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // assumption / RULE: street and city must have comma delimiter_x000D_
      // addresses that do not follow this rule will be wrong only if city has space_x000D_
      // but don't care because Esri formats put comma before City_x000D_
      var streetNameParts = [];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found end of street address (may include building, etc. - don't care right now)_x000D_
          // add token back to end, but remove trailing comma (it did its job)_x000D_
          tokens.push(lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken);_x000D_
          streetNameParts = tokens;_x000D_
          break;_x000D_
        } else {_x000D_
          cityNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.city = cityNameParts.join(' ');_x000D_
      address.street = streetNameParts.join(' ');_x000D_
    } else {_x000D_
      // if there is NO state, then assume there is NO city also, just street! (easy)_x000D_
      // reasoning: city names are not very original (Portland, OR and Portland, ME) so if user wants city they need to store state also (but if you are only ever in Portlan, OR, you don't care about city/state)_x000D_
      // put last token back in list, then rejoin on space_x000D_
      tokens.push(lastToken);_x000D_
      address.street = tokens.join(' ');_x000D_
    }_x000D_
  }_x000D_
  // when parsing right-to-left hard to know if street only vs street + city/state_x000D_
  // hack fix for now is to shift stuff around._x000D_
  // assumption/requirement: will always have at least street part; you will never just get "city, state"  _x000D_
  // could possibly tweak this with options or more intelligent parsing&sniffing_x000D_
  if (!address.city && address.state) {_x000D_
    address.city = address.state;_x000D_
    address.state = '';_x000D_
  }_x000D_
  if (!address.street) {_x000D_
    address.street = address.city;_x000D_
    address.city = '';_x000D_
  }_x000D_
_x000D_
  return address;_x000D_
}_x000D_
_x000D_
// get list of objects with discrete address properties_x000D_
var addresses = rawlist_x000D_
  .filter(function(o) {_x000D_
    return o.length > 0_x000D_
  })_x000D_
  .map(ParseAddressEsri);_x000D_
$("#output").text(JSON.stringify(addresses));_x000D_
console.log(addresses);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
13212 E SPRAGUE AVE, FAIR VALLEY, MD 99201_x000D_
1005 N Gravenstein Highway, Sebastopol CA 95472_x000D_
A. P. Croll &amp; Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947_x000D_
11522 Shawnee Road, Greenwood, DE 19950_x000D_
144 Kings Highway, S.W. Dover, DE 19901_x000D_
Intergrated Const. Services 2 Penns Way Suite 405, New Castle, DE 19720_x000D_
Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958_x000D_
Nichols Excavation 2742 Pulaski Hwy, Newark, DE 19711_x000D_
2284 Bryn Zion Road, Smyrna, DE 19904_x000D_
VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21_x000D_
580 North Dupont Highway, Dover, DE 19901_x000D_
P.O. Box 778, Dover, DE 19903_x000D_
714 S OAK ST_x000D_
714 S OAK ST, RUM TOWN, VA, 99201_x000D_
3142 E SPRAGUE AVE, WHISKEY VALLEY, WA 99281_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
</textarea>_x000D_
<div id="output">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to create an Oracle sequence starting with max value from a table?

If you can use PL/SQL, try (EDIT: Incorporates Neil's xlnt suggestion to start at next higher value):

SELECT 'CREATE SEQUENCE transaction_sequence MINVALUE 0 START WITH '||MAX(trans_seq_no)+1||' INCREMENT BY 1 CACHE 20'
  INTO v_sql
  FROM transaction_log;

EXECUTE IMMEDIATE v_sql;

Another point to consider: By setting the CACHE parameter to 20, you run the risk of losing up to 19 values in your sequence if the database goes down. CACHEd values are lost on database restarts. Unless you're hitting the sequence very often, or, you don't care that much about gaps, I'd set it to 1.

One final nit: the values you specified for CACHE and INCREMENT BY are the defaults. You can leave them off and get the same result.

unknown type name 'uint8_t', MinGW

EDIT:

To Be Clear: If the order of your #includes matters and it is not part of your design pattern (read: you don't know why), then you need to rethink your design. Most likely, this just means you need to add the #include to the header file causing problems.

At this point, I have little interest in discussing/defending the merits of the example but will leave it up as it illustrates some nuances in the compilation process and why they result in errors.

END EDIT

You need to #include the stdint.h BEFORE you #include any other library interfaces that need it.

Example:

My LCD library uses uint8_t types. I wrote my library with an interface (Display.h) and an implementation (Display.c)

In display.c, I have the following includes.

#include <stdint.h>
#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>

And this works.

However, if I re-arrange them like so:

#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>
#include <stdint.h>

I get the error you describe. This is because Display.h needs things from stdint.h but can't access it because that information is compiled AFTER Display.h is compiled.

So move stdint.h above any library that need it and you shouldn't get the error anymore.

RestSharp simple complete example

Changing

RestResponse response = client.Execute(request);

to

IRestResponse response = client.Execute(request);

worked for me.

how to know status of currently running jobs

I found a better answer by Kenneth Fisher. The following query returns only currently running jobs:

SELECT
    ja.job_id,
    j.name AS job_name,
    ja.start_execution_date,      
    ISNULL(last_executed_step_id,0)+1 AS current_executed_step_id,
    Js.step_name
FROM msdb.dbo.sysjobactivity ja 
LEFT JOIN msdb.dbo.sysjobhistory jh ON ja.job_history_id = jh.instance_id
JOIN msdb.dbo.sysjobs j ON ja.job_id = j.job_id
JOIN msdb.dbo.sysjobsteps js
    ON ja.job_id = js.job_id
    AND ISNULL(ja.last_executed_step_id,0)+1 = js.step_id
WHERE
  ja.session_id = (
    SELECT TOP 1 session_id FROM msdb.dbo.syssessions ORDER BY agent_start_date DESC
  )
AND start_execution_date is not null
AND stop_execution_date is null;

You can get more information about a job by adding more columns from msdb.dbo.sysjobactivity table in select clause.

c# foreach (property in object)... Is there a simple way of doing this?

A copy-paste solution (extension methods) mostly based on earlier responses to this question.

Also properly handles IDicitonary (ExpandoObject/dynamic) which is often needed when dealing with this reflected stuff.

Not recommended for use in tight loops and other hot paths. In those cases you're gonna need some caching/IL emit/expression tree compilation.

    public static IEnumerable<(string Name, object Value)> GetProperties(this object src)
    {
        if (src is IDictionary<string, object> dictionary)
        {
            return dictionary.Select(x => (x.Key, x.Value));
        }
        return src.GetObjectProperties().Select(x => (x.Name, x.GetValue(src)));
    }

    public static IEnumerable<PropertyInfo> GetObjectProperties(this object src)
    {
        return src.GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => !p.GetGetMethod().GetParameters().Any());
    }

Fling gesture detection on grid layout

You can use the droidQuery library to handle flings, clicks, long clicks, and custom events. The implementation is built on my previous answer below, but droidQuery provides a slick, simple syntax:

//global variables    private boolean isSwiping = false;
private SwipeDetector.Direction swipeDirection = null;
private View v;//must be instantiated before next call.

//swipe-handling code
$.with(v).swipe(new Function() {
    @Override
    public void invoke($ droidQuery, Object... params) {
        if (params[0] == SwipeDetector.Direction.START)
            isSwiping = true;
        else if (params[0] == SwipeDetector.Direction.STOP) {
            if (isSwiping) {                    isSwiping = false;
                if (swipeDirection != null) {
                    switch(swipeDirection) {
                        case DOWN :                                //TODO: Down swipe complete, so do something
                            break;
                        case UP :
                            //TODO: Up swipe complete, so do something
                            break;
                        case LEFT :
                            //TODO: Left swipe complete, so do something
                            break;
                        case RIGHT :
                            //TODO: Right swipe complete, so do something
                            break;
                        default :                                break;
                    }
                }                }
        }
        else {
            swipeDirection = (SwipeDetector.Direction) params[0];
        }
    }
});

Original Answer

This answer uses a combination of components from the other answers here. It consists of the SwipeDetector class, which has an inner interface for listening for events. I also provide a RelativeLayout to show how to override a View's onTouch method to allow both swipe events and other detected events (such as clicks or long clicks).

SwipeDetector

package self.philbrown;

import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

/**
 * Detect Swipes on a per-view basis. Based on original code by Thomas Fankhauser on StackOverflow.com,
 * with adaptations by other authors (see link).
 * @author Phil Brown
 * @see <a href="http://stackoverflow.com/questions/937313/android-basic-gesture-detection">android-basic-gesture-detection</a>
 */
public class SwipeDetector implements View.OnTouchListener
{
    /**
     * The minimum distance a finger must travel in order to register a swipe event.
     */
    private int minSwipeDistance;

    /** Maintains a reference to the first detected down touch event. */
    private float downX, downY;

    /** Maintains a reference to the first detected up touch event. */
    private float upX, upY;

    /** provides access to size and dimension contants */
    private ViewConfiguration config;

    /**
     * provides callbacks to a listener class for various swipe gestures.
     */
    private SwipeListener listener;

    public SwipeDetector(SwipeListener listener)
    {
        this.listener = listener;
    }


    /**
     * {@inheritDoc}
     */
    public boolean onTouch(View v, MotionEvent event)
    {
        if (config == null)
        {
                config = ViewConfiguration.get(v.getContext());
                minSwipeDistance = config.getScaledTouchSlop();
        }

        switch(event.getAction())
        {
        case MotionEvent.ACTION_DOWN:
            downX = event.getX();
            downY = event.getY();
            return true;
        case MotionEvent.ACTION_UP:
            upX = event.getX();
            upY = event.getY();

            float deltaX = downX - upX;
            float deltaY = downY - upY;

            // swipe horizontal?
            if(Math.abs(deltaX) > minSwipeDistance)
            {
                // left or right
                if (deltaX < 0)
                {
                        if (listener != null)
                        {
                                listener.onRightSwipe(v);
                                return true;
                        }
                }
                if (deltaX > 0)
                {
                        if (listener != null)
                        {
                                listener.onLeftSwipe(v);
                                return true;
                        }
                }
            }

            // swipe vertical?
            if(Math.abs(deltaY) > minSwipeDistance)
            {
                // top or down
                if (deltaY < 0)
                {
                        if (listener != null)
                        {
                                listener.onDownSwipe(v);
                                return true;
                        }
                }
                if (deltaY > 0)
                {
                        if (listener != null)
                        {
                                listener.onUpSwipe(v);
                                return true;
                        }
                }
            }
        }
        return false;
    }

    /**
     * Provides callbacks to a registered listener for swipe events in {@link SwipeDetector}
     * @author Phil Brown
     */
    public interface SwipeListener
    {
        /** Callback for registering a new swipe motion from the bottom of the view toward its top. */
        public void onUpSwipe(View v);
        /** Callback for registering a new swipe motion from the left of the view toward its right. */
        public void onRightSwipe(View v);
        /** Callback for registering a new swipe motion from the right of the view toward its left. */
        public void onLeftSwipe(View v);
        /** Callback for registering a new swipe motion from the top of the view toward its bottom. */
        public void onDownSwipe(View v);
    }
}

Swipe Interceptor View

package self.philbrown;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

import com.npeinc.module_NPECore.model.SwipeDetector;
import com.npeinc.module_NPECore.model.SwipeDetector.SwipeListener;

/**
 * View subclass used for handling all touches (swipes and others)
 * @author Phil Brown
 */
public class SwipeInterceptorView extends RelativeLayout
{
    private SwipeDetector swiper = null;

    public void setSwipeListener(SwipeListener listener)
    {
        if (swiper == null)
            swiper = new SwipeDetector(listener);
    }

    public SwipeInterceptorView(Context context) {
        super(context);
    }

    public SwipeInterceptorView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SwipeInterceptorView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e)
    {
        boolean swipe = false, touch = false;
        if (swiper != null)
            swipe = swiper.onTouch(this, e);
        touch = super.onTouchEvent(e);
        return swipe || touch;
    }
}

Read Post Data submitted to ASP.Net Form

NameValueCollection nvclc = Request.Form;
string   uName= nvclc ["txtUserName"];
string   pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);

How to check if a line has one of the strings in a list?

One approach is to combine the search strings into a regex pattern as in this answer.

Adding a column after another column within SQL

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:

ALTER TABLE name ALTER column POSITION new_position

I guess it may work in other cases as well.

Output data with no column headings using PowerShell

In your case, when you just select a single property, the easiest way is probably to bypass any formatting altogether:

get-qadgroupmember 'Domain Admins' | foreach { $_.Name }

This will get you a simple string[] without column headings or empty lines. The Format-* cmdlets are mainly for human consumption and thus their output is not designed to be easily machine-readable or -parseable.

For multiple properties I'd probably go with the -f format operator. Something along the lines of

alias | %{ "{0,-10}{1,-10}{2,-60}" -f $_.COmmandType,$_.Name,$_.Definition }

which isn't pretty but gives you easy and complete control over the output formatting. And no empty lines :-)

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

INSTALL_FAILED_VERSION_DOWNGRADE

All Android apps have a package name. The package name uniquely identifies the app on the device. If same packageName as app that's already installed on the device then this error Showing .

  1. You can uninstall the application from your device first and then install the fresh one .
  2. You could simply increase the number by one each time a new version is released.

Bind event to right mouse click

document.oncontextmenu = function() {return false;}; //disable the browser context menu
$('selector-name')[0].oncontextmenu = function(){} //set jquery element context menu 

Java Programming: call an exe from Java and passing parameters

Pass your arguments in constructor itself.

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();

querySelectorAll with multiple conditions

Is it possible to make a search by querySelectorAll using multiple unrelated conditions?

Yes, because querySelectorAll accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector. For instance:

var list = document.querySelectorAll("form, p, legend");

...will return a list containing any element that is a form or p or legend.

CSS also has the other concept: Restricting based on more criteria. You just combine multiple aspects of a selector. For instance:

var list = document.querySelectorAll("div.foo");

...will return a list of all div elements that also (and) have the class foo, ignoring other div elements.

You can, of course, combine them:

var list = document.querySelectorAll("div.foo, p.bar, div legend");

...which means "Include any div element that also has the foo class, any p element that also has the bar class, and any legend element that's also inside a div."

Laravel - Form Input - Multiple select for a one to many relationship

A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...

Form::select('sports[]', $sports, null, array('multiple'))

The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').

The second parameter is an array of selectable options.

The third parameter is an array of options you want pre-selected.

The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..

Favicon not showing up in Google Chrome

Cache

Clear your cache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser.

Some where able to get an updated favicon by adding an URL parameter: ?v=1 after the link href which changes the resource link and therefore loads the favicon without cache (thanks @Stanislav).

<link rel="icon" type="image/x-icon" href="favicon.ico?v=2"  />

Favicon Usage

How did you import the favicon? How you should add it.

Normal favicon:

<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

PNG/GIF favicon:

<link rel="icon" type="image/gif" href="favicon.gif" />
<link rel="icon" type="image/png" href="favicon.png" />

in the <head> Tag.

Chrome local problem

Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver). Only if the file/icon would be in the downloads directory chrome is allowed to load this data - more information about this can be found here: local (file://) website favicon works in Firefox, not in Chrome or Safari- why?

Renaming

Try to rename it from favicon.{whatever} to {yourfaviconname}.{whatever} but I would suggest you to still have the normal favicon. This has solved my issue on IE.

Base64 approach

Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:

<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />

Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp

Generate favicons

I can really suggest you this page: http://www.favicon-generator.org/ to create all types of favicons you need.

How to call an element in a numpy array?

Just use square brackets instead:

print arr[1,1]

Proper use of 'yield return'

Yield has two great uses

It helps to provide custom iteration with out creating temp collections. ( loading all data and looping)

It helps to do stateful iteration. ( streaming)

Below is a simple video which i have created with full demonstration in order to support the above two points

http://www.youtube.com/watch?v=4fju3xcm21M

VBA code to set date format for a specific column as "yyyy-mm-dd"

You are applying the formatting to the workbook that has the code, not the added workbook. You'll want to get in the habit of fully qualifying sheet and range references. The code below does that and works for me in Excel 2010:

Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
    .Range("A1") = "Acctdate"
    .Range("B1") = "Ledger"
    .Range("C1") = "CY"
    .Range("D1") = "BusinessUnit"
    .Range("E1") = "OperatingUnit"
    .Range("F1") = "LOB"
    .Range("G1") = "Account"
    .Range("H1") = "TreatyCode"
    .Range("I1") = "Amount"
    .Range("J1") = "TransactionCurrency"
    .Range("K1") = "USDEquivalentAmount"
    .Range("L1") = "KeyCol"
    .Range("A2", "A50000").Value = Me.TextBox3.Value
    .Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub

How do I authenticate a WebClient request?

What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient request.

At worst, it won't work.

How to extract file name from path?

Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory

Angularjs autocomplete from $http

I found this link helpful

$scope.loadSkillTags = function (query) {
var data = {qData: query};
   return SkillService.querySkills(data).then(function(response) {
   return response.data;
  });
 };

ng: command not found while creating new project using angular-cli

This worked for me:

  1. Go to C:\Users{{users}}\AppData\Roaming and delete the npm folder
  2. Uninstall node and install it again
  3. Run the command to install angular cli

    npm install -g @angular/cli
    

Redirect with CodeIgniter

first, you need to load URL helper like this type or you can upload within autoload.php file:

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

if (!$user_logged_in)
{
  redirect('/account/login', 'refresh');
}

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

You can try the expand option in Series.str.split('seperator', expand=True).
By default expand is False.

expand : bool, default False
Expand the splitted strings into separate columns.

  • If True, return DataFrame/MultiIndex expanding dimensionality.
  • If False, return Series/Index, containing lists of strings.

What is difference between png8 and png24

From the Web Designer’s Guide to PNG Image Format

PNG-8 and PNG-24

There are two PNG formats: PNG-8 and PNG-24. The numbers are shorthand for saying "8-bit PNG" or "24-bit PNG." Not to get too much into technicalities — because as a web designer, you probably don’t care — 8-bit PNGs mean that the image is 8 bits per pixel, while 24-bit PNGs mean 24 bits per pixel.

To sum up the difference in plain English: Let’s just say PNG-24 can handle a lot more color and is good for complex images with lots of color such as photographs (just like JPEG), while PNG-8 is more optimized for things with simple colors, such as logos and user interface elements like icons and buttons.

Another difference is that PNG-24 natively supports alpha transparency, which is good for transparent backgrounds. This difference is not 100% true because Adobe products’ Save for Web command allows PNG-8 with alpha transparency.

How to position background image in bottom right corner? (CSS)

Did you try something like:

body {background: url('[url to your image]') no-repeat right bottom;}

Wait until a process ends

Process.WaitForExit should be just what you're looking for I think.

What's a simple way to get a text input popup dialog box on an iPhone

Just wanted to add an important piece of information that I believe was left out perhaps with the assumption that the ones seeking answers might already know. This problem happens a lot and I too found myself stuck when I tried to implement the viewAlert method for the buttons of the UIAlertView message. To do this you need to 1st add the delegate class which may look something like this:

@interface YourViewController : UIViewController <UIAlertViewDelegate>

Also you can find a very helpful tutorial here!

Hope this helps.

jQuery duplicate DIV into another DIV

Copy code using clone and appendTo function :

Here is also working example jsfiddle

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="copy"><a href="http://brightwaay.com">Here</a> </div>
<br/>
<div id="copied"></div>
<script type="text/javascript">
    $(function(){
        $('#copy').clone().appendTo('#copied');
    });
</script>
</body>
</html>

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

IE7/8/9 seem to behave differently depending on whether the page has focus or not.

If you click on the page and CTRL+F5 then "Cache-Control: no-cache" is included in the request headers. If you click in the Location/Address bar then press CTRL+F5 it isn't.

(HTML) Download a PDF file instead of opening them in browser when clicked

The solution that worked best for me was the one written up by Nick on his blog

The basic idea of his solution is to use the Apache servers header mod and edit the .htaccess to include a FileMatch directive that the forces all *.pdf files to act as a stream instead of an attachment. While this doesn't actually involve editing HTML (as per the original question) it doesn't require any programming per se.

The first reason I preferred Nick's approach is because it allowed me to set it on a per folder basis so PDF's in one folder could still be opened in the browser while allowing others (the ones we would like users to edit and then re-upload) to be forced as downloads.

I would also like to add that there is an option with PDF's to post/submit fillable forms via an API to your servers, but that takes awhile to implement.

The second reason was because time is a consideration. Writing a PHP file handler to force the content disposition in the header() will also take less time than an API, but still longer than Nick's approach.

If you know how to turn on an Apache mod and edit the .htaccss you can get this in about 10 minutes. It requires Linux hosting (not Windows). This may not be appropriate approach for all uses as it requires high level server access to configure. As such, if you have said access it's probably because you already know how to do those two things. If not, check Nick's blog for more instructions.

How to install an APK file on an Android phone?

For what its worth, installing a system app to the /system/app directory will be:

adb push appname.apk /system/app/

Just ensure you're in the right directory where the target .apk file to be installed is, or you could just copy the .apk file to the platform-tools directory of the Android SDK and adb would definitely find it.

Controlling mouse with Python

Pynput is the best solution I have found, both for Windows and for Mac. Super easy to program, and works very well.

For example,

from pynput.mouse import Button, Controller

mouse = Controller()

# Read pointer position
print('The current pointer position is {0}'.format(
    mouse.position))

# Set pointer position
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
    mouse.position))

# Move pointer relative to current position
mouse.move(5, -5)

# Press and release
mouse.press(Button.left)
mouse.release(Button.left)

# Double click; this is different from pressing and releasing
# twice on Mac OSX
mouse.click(Button.left, 2)

# Scroll two steps down
mouse.scroll(0, 2)

Do you recommend using semicolons after every statement in JavaScript?

Yes, you should use semicolons after every statement in JavaScript.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

Finding the id of a parent div using Jquery

Try this:

$("button").click(function () {
    $(this).parents("div:first").html(...);
});

Understanding INADDR_ANY for socket programming

INADDR_ANY is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind(), the socket accepts connections to all the IPs of the machine.

Best way to remove items from a collection

If it's an ICollection then you won't have a RemoveAll method. Here's an extension method that will do it:

    public static void RemoveAll<T>(this ICollection<T> source, 
                                    Func<T, bool> predicate)
    {
        if (source == null)
            throw new ArgumentNullException("source", "source is null.");

        if (predicate == null)
            throw new ArgumentNullException("predicate", "predicate is null.");

        source.Where(predicate).ToList().ForEach(e => source.Remove(e));
    }

Based on: http://phejndorf.wordpress.com/2011/03/09/a-removeall-extension-for-the-collection-class/

Compiling Java 7 code via Maven

I had this problem when working with eclipse, I had to change the project's build path so that it refers to jre 7

AngularJS view not updating on model change

setTimout executes outside of angular. You need to use $timeout service for this to work:

var app = angular.module('test', []);

    app.controller('TestCtrl', function ($scope, $timeout) {
       $scope.testValue = 0;

        $timeout(function() {
            console.log($scope.testValue++);
        }, 500);
    });

The reason is that two-way binding in angular uses dirty checking. This is a good article to read about angular's dirty checking. $scope.$apply() kicks off a $digest cycle. This will apply the binding. $timeout handles the $apply for you so it is the recommended service to use when using timeouts.

Essentially, binding happens during the $digest cycle (if the value is seen to be different).

How to call a parent class function from derived class function?

Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
    virtual void print(int x);
};

class Child : public Parent {
    void print(int x) override;
};

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.

Triangle Draw Method

There is not a drawTriangle method neither in Graphics nor Graphics2D. You need to do it by yourself. You can draw three lines using the drawLine method or use one these methods:

These methods work with polygons. You may change the prefix draw to fill when you want to fill the polygon defined by the point set. I inserted the documentation links. Take a look to learn how to use them.

There is the GeneralPath class too. It can be used with Graphics2D, which is capable to draw Shapes. Take a look:

How to add a “readonly” attribute to an <input>?

Use the setAttribute property. Note in example that if select 1 apply the readonly attribute on textbox, otherwise remove the attribute readonly.

http://jsfiddle.net/baqxz7ym/2/

document.getElementById("box1").onchange = function(){
  if(document.getElementById("box1").value == 1) {
    document.getElementById("codigo").setAttribute("readonly", true);
  } else {
    document.getElementById("codigo").removeAttribute("readonly");
  }
};

<input type="text" name="codigo" id="codigo"/>

<select id="box1">
<option value="0" >0</option>
<option value="1" >1</option>
<option value="2" >2</option>
</select>

How to debug Spring Boot application with Eclipse?

There's section 19.2 in Spring Boot Reference that tells you about starting your application with remote debugging support enabled.

$ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
   -jar target/myproject-0.0.1-SNAPSHOT.jar

After you start your application just add that Remote Java Application configuration in Run/Debug configurations, select the port/address you defined when starting your app, and then you are free to debug.

set date in input type date

You can only use date in input type="date" as in format YYYY-MM-DD

I have implemented helper as formatDate in NODE.js express-handlebars, don't need to be worry ... just use format as described in first line.

e.g:

< input type="date" id="date" name="date" class="form-control" value="{{formatDate invoice.date 'YYYY-MM-DD'}}" />

The PowerShell -and conditional operator

The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":

$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False

Get a list of URLs from a site

Here is a list of sitemap generators (from which obviously you can get the list of URLs from a site): http://code.google.com/p/sitemap-generators/wiki/SitemapGenerators

Web Sitemap Generators

The following are links to tools that generate or maintain files in the XML Sitemaps format, an open standard defined on sitemaps.org and supported by the search engines such as Ask, Google, Microsoft Live Search and Yahoo!. Sitemap files generally contain a collection of URLs on a website along with some meta-data for these URLs. The following tools generally generate "web-type" XML Sitemap and URL-list files (some may also support other formats).

Please Note: Google has not tested or verified the features or security of the third party software listed on this site. Please direct any questions regarding the software to the software's author. We hope you enjoy these tools!

Server-side Programs

  • Enarion phpSitemapsNG (PHP)
  • Google Sitemap Generator (Linux/Windows, 32/64bit, open-source)
  • Outil en PHP (French, PHP)
  • Perl Sitemap Generator (Perl)
  • Python Sitemap Generator (Python)
  • Simple Sitemaps (PHP)
  • SiteMap XML Dynamic Sitemap Generator (PHP) $
  • Sitemap generator for OS/2 (REXX-script)
  • XML Sitemap Generator (PHP) $

CMS and Other Plugins:

  • ASP.NET - Sitemaps.Net
  • DotClear (Spanish)
  • DotClear (2)
  • Drupal
  • ECommerce Templates (PHP) $
  • Ecommerce Templates (PHP or ASP) $
  • LifeType
  • MediaWiki Sitemap generator
  • mnoGoSearch
  • OS Commerce
  • phpWebSite
  • Plone
  • RapidWeaver
  • Textpattern
  • vBulletin
  • Wikka Wiki (PHP)
  • WordPress

Downloadable Tools

  • GSiteCrawler (Windows)
  • GWebCrawler & Sitemap Creator (Windows)
  • G-Mapper (Windows)
  • Inspyder Sitemap Creator (Windows) $
  • IntelliMapper (Windows) $
  • Microsys A1 Sitemap Generator (Windows) $
  • Rage Google Sitemap Automator $ (OS-X)
  • Screaming Frog SEO Spider and Sitemap generator (Windows/Mac) $
  • Site Map Pro (Windows) $
  • Sitemap Writer (Windows) $
  • Sitemap Generator by DevIntelligence (Windows)
  • Sorrowmans Sitemap Tools (Windows)
  • TheSiteMapper (Windows) $
  • Vigos Gsitemap (Windows)
  • Visual SEO Studio (Windows)
  • WebDesignPros Sitemap Generator (Java Webstart Application)
  • Weblight (Windows/Mac) $
  • WonderWebWare Sitemap Generator (Windows)

Online Generators/Services

  • AuditMyPc.com Sitemap Generator
  • AutoMapIt
  • Autositemap $
  • Enarion phpSitemapsNG
  • Free Sitemap Generator
  • Neuroticweb.com Sitemap Generator
  • ROR Sitemap Generator
  • ScriptSocket Sitemap Generator
  • SeoUtility Sitemap Generator (Italian)
  • SitemapDoc
  • Sitemapspal
  • SitemapSubmit
  • Smart-IT-Consulting Google Sitemaps XML Validator
  • XML Sitemap Generator
  • XML-Sitemaps Generator

CMS with integrated Sitemap generators

  • Concrete5

Google News Sitemap Generators The following plugins allow publishers to update Google News Sitemap files, a variant of the sitemaps.org protocol that we describe in our Help Center. In addition to the normal properties of Sitemap files, Google News Sitemaps allow publishers to describe the types of content they publish, along with specifying levels of access for individual articles. More information about Google News can be found in our Help Center and Help Forums.

  • WordPress Google News plugin

Code Snippets / Libraries

  • ASP script
  • Emacs Lisp script
  • Java library
  • Perl script
  • PHP class
  • PHP generator script

If you believe that a tool should be added or removed for a legitimate reason, please leave a comment in the Webmaster Help Forum.

How can I mock an ES6 module import using Jest?

Fast forwarding to 2020, I found this blog post to be the solution: Jest mock default and named export

Using only ES6 module syntax:

// esModule.js
export default 'defaultExport';
export const namedExport = () => {};

// esModule.test.js
jest.mock('./esModule', () => ({
  __esModule: true, // this property makes it work
  default: 'mockedDefaultExport',
  namedExport: jest.fn(),
}));

import defaultExport, { namedExport } from './esModule';
defaultExport; // 'mockedDefaultExport'
namedExport; // mock function

Also one thing you need to know (which took me a while to figure out) is that you can't call jest.mock() inside the test; you must call it at the top level of the module. However, you can call mockImplementation() inside individual tests if you want to set up different mocks for different tests.

How do I serialize a Python dictionary into a string, and then back to a dictionary?

pyyaml should also be mentioned here. It is both human readable and can serialize any python object.
pyyaml is hosted here:
https://bitbucket.org/xi/pyyaml

Reordering arrays

Reorder its work This Way

 var tmpOrder = playlist[oldIndex];
    playlist.splice(oldIndex, 1);
    playlist.splice(newIndex, 0, tmpOrder);

I hope this will work

What is the maximum characters for the NVARCHAR(MAX)?

By default, nvarchar(MAX) values are stored exactly the same as nvarchar(4000) values would be, unless the actual length exceed 4000 characters; in that case, the in-row data is replaced by a pointer to one or more seperate pages where the data is stored.

If you anticipate data possibly exceeding 4000 character, nvarchar(MAX) is definitely the recommended choice.

Source: https://social.msdn.microsoft.com/Forums/en-US/databasedesign/thread/d5e0c6e5-8e44-4ad5-9591-20dc0ac7a870/

How do you add CSS with Javascript?

Here's my general-purpose function which parametrizes the CSS selector and rules, and optionally takes in a css filename (case-sensitive) if you wish to add to a particular sheet instead (otherwise, if you don't provide a CSS filename, it will create a new style element and append it to the existing head. It will make at most one new style element and re-use it on future function calls). Works with FF, Chrome, and IE9+ (maybe earlier too, untested).

function addCssRules(selector, rules, /*Optional*/ sheetName) {
    // We want the last sheet so that rules are not overridden.
    var styleSheet = document.styleSheets[document.styleSheets.length - 1];
    if (sheetName) {
        for (var i in document.styleSheets) {
            if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(sheetName) > -1) {
                styleSheet = document.styleSheets[i];
                break;
            }
        }
    }
    if (typeof styleSheet === 'undefined' || styleSheet === null) {
        var styleElement = document.createElement("style");
        styleElement.type = "text/css";
        document.head.appendChild(styleElement);
        styleSheet = styleElement.sheet;
    }

    if (styleSheet) {
        if (styleSheet.insertRule)
            styleSheet.insertRule(selector + ' {' + rules + '}', styleSheet.cssRules.length);
        else if (styleSheet.addRule)
            styleSheet.addRule(selector, rules);
    }
}

Passing a URL with brackets to curl

Never mind, I found it in the docs:

-g/--globoff
              This  option  switches  off  the "URL globbing parser". When you set this option, you can
              specify URLs that contain the letters {}[] without having them being interpreted by  curl
              itself.  Note  that  these  letters  are not normal legal URL contents but they should be
              encoded according to the URI standard.

Nodemailer with Gmail and NodeJS

first install nodemailer

npm install nodemailer  --save

import in to js file

const nodemailer = require("nodemailer");

const smtpTransport = nodemailer.createTransport({
    service: "Gmail",
    auth: {
        user: "[email protected]",
        pass: "password"
    },
    tls: {
        rejectUnauthorized: false
    }
});






 const mailOptions = {
        from: "[email protected]",
        to: [email protected],
        subject: "Welcome to ",
        text: 'hai send from me'.
    };


    smtpTransport.sendMail(mailOptions, function (error, response) {
        if (error) {
            console.log(error);
        }
        else {
            console.log("mail sent");
        }
    });

working in my application

Generating a PDF file from React Components

npm install jspdf --save

//code on react

import jsPDF from 'jspdf';


var doc = new jsPDF()


 doc.fromHTML("<div>JOmin</div>", 1, 1)


onclick //

 doc.save("name.pdf")

Using Thymeleaf when the value is null

This can also be handled using the elvis operator ?: which will add a default value when the field is null:

<span th:text="${object.property} ?: 'default value'"></span>

How to add url parameters to Django template url tag?

1: HTML

           <tbody>
            {% for ticket in tickets %}
              <tr>
                <td class="ticket_id">{{ticket.id}}</td>
                <td class="ticket_eam">{{ticket.eam}}</td>
                <td class="ticket_subject">{{ticket.subject}}</td>
                <td>{{ticket.zone}}</td>
                <td>{{ticket.plaza}}</td>
                <td>{{ticket.lane}}</td>
                <td>{{ticket.uptime}}</td>
                <td>{{ticket.downtime}}</td>
                <td><a href="{% url 'ticket_details' ticket_id=ticket.id %}"><button data-toggle="modal" data-target="#modaldemo3" class="value-modal"><i class="icon ion-edit"></a></i></button> <button><i class="fa fa-eye-slash"></i></button>
              </tr>
            {% endfor %}
            </tbody>

The {% url 'ticket_details' %} is the function name in your views

2: Views.py

def ticket_details(request, ticket_id):

   print(ticket_id)
   return render(request, ticket.html)

ticket_id is the parameter you will get from the ticket_id=ticket.id

3: URL.py

urlpatterns = [
path('ticket_details/?P<int:ticket_id>/', views.ticket_details, name="ticket_details") ]

/?P - where ticket_id is the name of the group and pattern is some pattern to match.

How to Convert the value in DataTable into a string array in c#

Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row:

List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
 MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}

You could then access one:

MyStringArrays.ElementAt(0)[1]

If you use linqpad, here is a very simple scenario of your example:

class Datatable
{
 public List<data> rows { get; set; }
 public Datatable(){
  rows = new List<data>();
 }
}

class data
{
 public string Name { get; set; }
 public string Address { get; set; }
 public int Age { get; set; }
}

void Main()
{
 var datatable = new Datatable();
 var r = new data();
 r.Name = "Jim";
 r.Address = "USA";
 r.Age = 23;
 datatable.rows.Add(r);
 List<string[]> MyStringArrays = new List<string[]>();
 foreach( var row in datatable.rows )//or similar
 {
  MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
 }
 var s = MyStringArrays.ElementAt(0)[1];
 Console.Write(s);//"USA"
}

Invalid application of sizeof to incomplete type with a struct

I think that the problem is that you put #ifdef instead of #ifndef at the top of your header.h file.

Select the values of one property on all objects of an array in PowerShell

As an even easier solution, you could just use:

$results = $objects.Name

Which should fill $results with an array of all the 'Name' property values of the elements in $objects.

JSON.net: how to deserialize without using the default constructor?

Json.Net prefers to use the default (parameterless) constructor on an object if there is one. If there are multiple constructors and you want Json.Net to use a non-default one, then you can add the [JsonConstructor] attribute to the constructor that you want Json.Net to call.

[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
    ...
}

It is important that the constructor parameter names match the corresponding property names of the JSON object (ignoring case) for this to work correctly. You do not necessarily have to have a constructor parameter for every property of the object, however. For those JSON object properties that are not covered by the constructor parameters, Json.Net will try to use the public property accessors (or properties/fields marked with [JsonProperty]) to populate the object after constructing it.

If you do not want to add attributes to your class or don't otherwise control the source code for the class you are trying to deserialize, then another alternative is to create a custom JsonConverter to instantiate and populate your object. For example:

class ResultConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Result));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load the JSON for the Result into a JObject
        JObject jo = JObject.Load(reader);

        // Read the properties which will be used as constructor parameters
        int? code = (int?)jo["Code"];
        string format = (string)jo["Format"];

        // Construct the Result object using the non-default constructor
        Result result = new Result(code, format);

        // (If anything else needs to be populated on the result object, do that here)

        // Return the result
        return result;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then, add the converter to your serializer settings, and use the settings when you deserialize:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Result result = JsonConvert.DeserializeObject<Result>(jsontext, settings);

How to list all tags along with the full message in git?

Use --format option

git tag -l --format='%(tag) %(subject)'

What is the difference between `let` and `var` in swift?

Found a good answer hope it can help :) enter image description here

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

You can wrap all tasks which can fail in block, and use ignore_errors: yes with that block.

tasks:
  - name: ls
    command: ls -la
  - name: pwd
    command: pwd

  - block:
    - name: ls non-existing txt file
      command: ls -la no_file.txt
    - name: ls non-existing pic
      command: ls -la no_pic.jpg
    ignore_errors: yes 

Read more about error handling in blocks here.

Passing data from controller to view in Laravel

public function showstudents() {
     $students = DB::table('student')->get();
     return (View::make("user/regprofile", compact('student')));
}

Strip out HTML and Special Characters

preg_replace('/[^a-zA-Z0-9\s]/', '',$string) this is using for removing special character only rather than space between the strings.

Error: No default engine was specified and no extension was provided

You can use express-error-handler to use static html pages for error handling and to avoid defining a view handler.

The error was probably caused by a 404, maybe a missing favicon (apparent if you had included the previous console message). The 'view handler' of 'html' doesn't seem to be valid in 4.x express.

Regardless of the cause, you can avoid defining a (valid) view handler as long as you modify additional elements of your configuration.

Your options are to fix this problem are:

  • Define a valid view handler as in other answers
  • Use send() instead of render to return the content directly

http://expressjs.com/en/api.html#res.render

Using render without a filepath automatically invokes a view handler as with the following two lines from your configuration:

res.render('404', { url: req.url });

and:

res.render('500);

Make sure you install express-error-handler with:

npm install --save express-error-handler

Then import it in your app.js

var ErrorHandler = require('express-error-handler');

Then change your error handling to use:

// define below all other routes
var errorHandler = ErrorHandler({
  static: {
    '404': 'error.html' // put this file in your Public folder
    '500': 'error.html' // ditto
});

// any unresolved requests will 404
app.use(function(req,res,next) {
  var err = new Error('Not Found');
  err.status(404);
  next(err);
}

app.use(errorHandler);

Create table in SQLite only if it doesn't exist already

From http://www.sqlite.org/lang_createtable.html:

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);

How do I declare a model class in my Angular 2 component using TypeScript?

The problem lies that you haven't added Model to either the bootstrap (which will make it a singleton), or to the providers array of your component definition:

@Component({
    selector: "testWidget",
    template: "<div>This is a test and {{param1}} is my param.</div>",
    providers : [
       Model
    ]
})

export class testWidget {
    constructor(private model: Model) {}
}

And yes, you should define Model above the Component. But better would be to put it in his own file.

But if you want it to be just a class from which you can create multiple instances, you better just use new.

@Component({
    selector: "testWidget",
    template: "<div>This is a test and {{param1}} is my param.</div>"
})

export class testWidget {

    private model: Model = new Model();

    constructor() {}
}

How to merge many PDF files into a single one?

First, get Pdftk:

sudo apt-get install pdftk

Now, as shown on example page, use

pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf

for merging pdf files into one.

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Clearing the contents of storage/framework/cache did the trick for me. Nothing else worked...

How do I create test and train samples from one dataframe with pandas?

If your wish is to have one dataframe in and two dataframes out (not numpy arrays), this should do the trick:

def split_data(df, train_perc = 0.8):

   df['train'] = np.random.rand(len(df)) < train_perc

   train = df[df.train == 1]

   test = df[df.train == 0]

   split_data ={'train': train, 'test': test}

   return split_data

List directory tree structure in python?

Here you can find code with output like this: https://stackoverflow.com/a/56622847/6671330

V .
|-> V folder1
|   |-> V folder2
|   |   |-> V folder3
|   |   |   |-> file3.txt
|   |   |-> file2.txt
|   |-> V folderX
|   |-> file1.txt
|-> 02-hw1_wdwwfm.py
|-> 06-t1-home1.py
|-> 06-t1-home2.py
|-> hw1.py

How is a JavaScript hash map implemented?

While plain old JavaScript objects can be used as maps, they are usually implemented in a way to preserve insertion-order for compatibility with most browsers (see Craig Barnes's answer) and are thus not simple hash maps.

ES6 introduces proper Maps (see MDN JavaScript Map) of which the standard says:

Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection.

For div to extend full height

In case also setting the height of the html and the body to 100% makes everything messier for you as it did for me, the following worked for me:

height: calc(100vh - 33rem)

The - 33rem is the height of the elements coming after the one we want to take full height, i.e., 100vh. By subtracting the height, we will make sure there is no overflow and it will always be responsive (assuming we are working with rem instead of px).

How can I set a cookie in react?

Use vanilla js, example

document.cookie = `referral_key=hello;max-age=604800;domain=example.com`

Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

Run AVD Emulator without Android Studio

cd C:\Users\{computer_user_name}\AppData\Local\Android\Sdk\emulator

then run:

./emulator -list-avds
or
emulator -list-avds

output:

PIXEL_2_API_29
PIXEL_2_XL_API_29

then run:

./emulator -avd PIXEL_2_XL_API_29
or
emulator -avd PIXEL_2_XL_API_29

That's it

Django ManyToMany filter()

Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct(). Otherwise you get one user multiple times:

users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()

How to style dt and dd so they are on the same line?

I need to do this and have the <dt> content vertically centered, relative to the <dd> content. I used display: inline-block, together with vertical-align: middle

See full example on Codepen here

.dl-horizontal {
  font-size: 0;
  text-align: center;

  dt, dd {
    font-size: 16px;
    display: inline-block;
    vertical-align: middle;
    width: calc(50% - 10px);
  }

  dt {
    text-align: right;
    padding-right: 10px;
  }

  dd {
    font-size: 18px;
    text-align: left;
    padding-left: 10px;
  } 
}

Parse JSON from HttpURLConnection object

You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

There is a sample of AuthMsg class:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

JSON returned by http://localhost/authmanager.php must look like this:

{"code":1,"message":"Logged in"}

Regards

How to convert int to date in SQL Server 2008

You have to first convert it into datetime, then to date.

Try this, it might be helpful:

Select Convert(DATETIME, LEFT(20130101, 8))

then convert to date.

http://localhost:50070 does not work HADOOP

  • step 1 : bin/stop-all.sh
  • step 2 : bin/hadoop namenode -format
  • step 3 : bin/start-all.sh

Serialize JavaScript object into JSON string

You can use a named function on the constructor.

MyClass1 = function foo(id, member) {
    this.id = id;
    this.member = member;
}

var myobject = new MyClass1("5678999", "text");

console.log( myobject.constructor );

//function foo(id, member) {
//    this.id = id;
//    this.member = member;
//}

You could use a regex to parse out 'foo' from myobject.constructor and use that to get the name.

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

How to reset or change the passphrase for a GitHub SSH key?

In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.

Linq code to select one item

Depends how much you like the linq query syntax, you can use the extension methods directly like:

var item = Items.First(i => i.Id == 123);

And if you don't want to throw an error if the list is empty, use FirstOrDefault which returns the default value for the element type (null for reference types):

var item = Items.FirstOrDefault(i => i.Id == 123);

if (item != null)
{
    // found it
}

Single() and SingleOrDefault() can also be used, but if you are reading from a database or something that already guarantees uniqueness I wouldn't bother as it has to scan the list to see if there's any duplicates and throws. First() and FirstOrDefault() stop on the first match, so they are more efficient.

Of the First() and Single() family, here's where they throw:

  • First() - throws if empty/not found, does not throw if duplicate
  • FirstOrDefault() - returns default if empty/not found, does not throw if duplicate
  • Single() - throws if empty/not found, throws if duplicate exists
  • SingleOrDefault() - returns default if empty/not found, throws if duplicate exists

Creating an IFRAME using JavaScript

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

<div id="placeholder"></div>

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>

Update some specific field of an entity in android Room

We need the primary key of that particular model that you want to update. For example:

 private fun update(Name: String?, Brand: String?) {
    val deviceEntity = remoteDao?.getRemoteId(Id)
    if (deviceEntity == null)
        remoteDao?.insertDevice(DeviceEntity(DeviceModel = DeviceName, DeviceBrand = DeviceBrand))
    else
        DeviceDao?.updateDevice(DeviceEntity(deviceEntity.id,remoteDeviceModel = DeviceName, DeviceBrand = DeviceBrand))
}

In this function, I am checking whether a particular entry exists in the database if exists pull the primary key which is id over here and perform update function.

This is the for fetching and update records:

@Query("SELECT * FROM ${DeviceDatabase.DEVICE_TABLE_NAME} WHERE ${DeviceDatabase.COLUMN_DEVICE_ID} = :DeviceId LIMIT 1")

fun getRemoteDeviceId(DeviceId: String?): DeviceEntity


@Update(onConflict = OnConflictStrategy.REPLACE)
fun updatDevice(item: DeviceEntity): Int

ng-options with simple array init

You can use ng-repeat with option like this:

<form>
    <select ng-model="yourSelect" 
        ng-options="option as option for option in ['var1', 'var2', 'var3']"
        ng-init="yourSelect='var1'"></select>
    <input type="hidden" name="yourSelect" value="{{yourSelect}}" />
</form>

When you submit your form you can get value of input hidden.


DEMO

ng-selected ng-repeat

Image height and width not working?

http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css

Line 11:

.postItem img {
    height: auto;
    width: 450px;
}

You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:

<img src="theSource" style="width:30px;" />

Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

In terms of Java heap size, in Linux, you can use

ps aux | grep java

or

ps -ef | grep java

and look for -Xms, -Xmx to find out the initial and maximum heap size specified.

However, if -Xms or -Xmx is absent for the Java process you are interested in, it means your Java process is using the default heap sizes. You can use the following command to find out the default sizes.

java -XX:+PrintFlagsFinal -version | grep HeapSize

or a particular jvm, for example,

/path/to/jdk1.8.0_102/bin/java -XX:+PrintFlagsFinal -version | grep HeapSize

and look for InitialHeapSize and MaxHeapSize, which is in bytes.

Stop node.js program from command line

on linux try: pkill node

on windows:

Taskkill /IM node.exe /F

or

from subprocess import call

call(['taskkill', '/IM', 'node.exe', '/F'])

Found conflicts between different versions of the same dependent assembly that could not be resolved

I'm using Visual Studio 2017 and encountered this when I updated some Nuget packages. What worked for me was to open my web.config file and find the <runtime><assemblyBinding> node and delete it. Save web.config and rebuild the project.

Look at the Error List window. You'll see what looks like a massively long warning about binding conflicts. Double-click it and it will automatically recreate the <runtime><assemblyBinding> block with the correct mappings.

log4j:WARN No appenders could be found for logger in web.xml

If still help, verify the name of archive, it must be exact "log4j.properties" or "log4j.xml" (case sensitive), and follow the hint by "Alain O'Dea". I was geting the same error, but after make these changes everthing works fine. just like a charm :-). hope this helps.

How do I clone a Django model instance object and save it to the database?

How to do this was added to the official Django docs in Django1.4

https://docs.djangoproject.com/en/1.10/topics/db/queries/#copying-model-instances

The official answer is similar to miah's answer, but the docs point out some difficulties with inheritance and related objects, so you should probably make sure you read the docs.

What is python's site-packages directory?

site-packages is the target directory of manually built Python packages. When you build and install Python packages from source (using distutils, probably by executing python setup.py install), you will find the installed modules in site-packages by default.

There are standard locations:

  • Unix (pure)1: prefix/lib/pythonX.Y/site-packages
  • Unix (non-pure): exec-prefix/lib/pythonX.Y/site-packages
  • Windows: prefix\Lib\site-packages

1 Pure means that the module uses only Python code. Non-pure can contain C/C++ code as well.

site-packages is by default part of the Python search path, so modules installed there can be imported easily afterwards.


Useful reading

JavaFX Application Icon

Full program for starters :) This program sets icon for StackOverflowIcon.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class StackoverflowIcon extends Application {

    @Override
    public void start(Stage stage) {
        StackPane root = new StackPane();
        // set icon
        stage.getIcons().add(new Image("/path/to/stackoverflow.jpg"));
        stage.setTitle("Wow!! Stackoverflow Icon");
        stage.setScene(new Scene(root, 300, 250));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Output Screnshot

JavaFX Screenshot

Updated for JavaFX 8

No need to change the code. It still works fine. Tested and verified in Java 1.8(1.8.0_45). Path can be set to local or remote both are supported.

stage.getIcons().add(new Image("/path/to/javaicon.png"));

OR

stage.getIcons().add(new Image("https://example.com/javaicon.png"));

enter image description here

Hope it helps. Thanks!!

Ajax passing data to php script

You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {
        content.html(response);
    }
});

What is sys.maxint in Python 3?

If you are looking for a number that is bigger than all others:

Method 1:

float('inf')

Method 2:

import sys
max = sys.maxsize

If you are looking for a number that is smaller than all others:

Method 1:

float('-inf')

Method 2:

import sys
min = -sys.maxsize - 1

Method 1 works in both Python2 and Python3. Method 2 works in Python3. I have not tried Method 2 in Python2.

How to search and replace text in a file?

You can also use pathlib.

from pathlib2 import Path
path = Path(file_to_search)
text = path.read_text()
text = text.replace(text_to_search, replacement_text)
path.write_text(text)

How do I call a JavaScript function on page load?

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

How do I exit a foreach loop in C#?

During testing I found that foreach loop after break go to the loop beging and not out of the loop. So I changed foreach into for and break in this case work correctly- after break program flow goes out of the loop.

Set up adb on Mac OS X

If you using zsh then you need do the add the following to your .zshrc

Steps: Step 1: Open your .zshrc profile

open -e .zshrc

Step 2: Add the following to the file

export PATH=$PATH:/Users/${YourUser}/Library/Android/sdk/platform-tools
export ANDROID_HOME=/Users/${YourUser}/Library/Android/sdk

Step 3: Save the file and close. Step 4: Reload the .zshrc

source .zshrc

Step 5: Check the devices connected

adb devices

How do you write multiline strings in Go?

you can use raw literals. Example

s:=`stack
overflow`

How to write DataFrame to postgres table?

This is how I did it.

It may be faster because it is using execute_batch:

# df is the dataframe
if len(df) > 0:
    df_columns = list(df)
    # create (col1,col2,...)
    columns = ",".join(df_columns)

    # create VALUES('%s', '%s",...) one '%s' per column
    values = "VALUES({})".format(",".join(["%s" for _ in df_columns])) 

    #create INSERT INTO table (columns) VALUES('%s',...)
    insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)

    cur = conn.cursor()
    psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
    conn.commit()
    cur.close()

Drop Down Menu/Text Field in one

I like jQuery Token input. Actually prefer the UI over some of the other options mentioned above.

http://loopj.com/jquery-tokeninput/

Also see: http://railscasts.com/episodes/258-token-fields for an explanation

ADB Android Device Unauthorized

I run into the same issues with nexus7.

Following worked for fixing this.

  1. Open Developer option in the Settings menu on your device.

  2. Switch off the button on the upper right of the screen.

  3. Delete all debug permission from the list of the menu.

  4. Switch on the button on the upper right of the screen.

now reconnect your device to your PC and everything should be fine.

Sorry for my poor english and some name of the menus(buttons) can be incorrect in your language because mine is Japanese.

Convert a String representation of a Dictionary to a dictionary?

using json.loads:

>>> import json
>>> h = '{"foo":"bar", "foo2":"bar2"}'
>>> d = json.loads(h)
>>> d
{u'foo': u'bar', u'foo2': u'bar2'}
>>> type(d)
<type 'dict'>

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

How to avoid Sql Query Timeout

Although there is clearly some kind of network instability or something interfering with your connection (15 minutes is possible that you could be crossing a NAT boundary or something in your network is dropping the session), I would think you want such a simple?) query to return well within any anticipated timeoue (like 1s).

I would talk to your DBA and get an index created on the underlying tables on MemberType, Status. If there isn't a single underlying table or these are more complex and created by the view or UDF, and you are running SQL Server 2005 or above, have him consider indexing the view (basically materializing the view in an indexed fashion).

What is char ** in C?

It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char* could indicate an array of chars, a char** could indicate that it points to and array of char*s.

How do I vertically center an H1 in a div?

You can achieve this with the display property:

html, body {
    height:100%;
    margin:0;
    padding:0;
}
#section1 {
    width:100%; /*full width*/
    min-height:90%;
    text-align:center;
    display:table; /*acts like a table*/
}
h1{
    margin:0;
    padding:0;
    vertical-align:middle; /*middle centred*/
    display:table-cell; /*acts like a table cell*/
}

Demo: http://jsfiddle.net/a3Kns/

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

You must to have installed php_openssl.dll, if you use wampserver it's pretty easy, search and apply the extension for PHP.

In the example change this:

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
    $mail->Port = 465;

    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';

and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications here https://www.google.com/settings/security/lesssecureapps

I recommend you change the password and encrypt it constantly

sizing div based on window width

html, body {
    height: 100%;
    width: 100%;
}

html {
    display: table;
    margin: auto;
}

body {
    padding-top: 50px;
    display: table-cell;
}

div {
    margin: auto;
}

This will center align objects and then also center align the items within them to center align multiple objects with different widths.

Example picture

Replace all occurrences of a String using StringBuilder?

java.util.regex.Pattern.matcher(CharSequence s) can use a StringBuilder as an argument so you can find and replace each occurence of your pattern using start() and end() without calling builder.toString()

cv2.imshow command doesn't work properly in opencv-python

error: (-215) size.width>0 && size.height>0 in function imshow

This error is produced because the image is not found. So it's not an error of imshow function.

How to create an empty array in PHP with predefined size?

There is also array_pad. You can use it like this:

$data = array_pad($data,$number_of_items,0);

For initializing with zeros the $number_of_items positions of the array $data.

Date only from TextBoxFor()

The DisplayFormat attribute did not work for me in either form upon initial load. I created an EditorTemplate instead:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%=
    Html.TextBox("", Model.ToShortDateString(), new { @class = "date-range" }) %>

How to present a simple alert message in java?

If you don't like "verbosity" you can always wrap your code in a short method:

private void msgbox(String s){
   JOptionPane.showMessageDialog(null, s);
}

and the usage:

msgbox("don't touch that!");

No module named Image

Problem:

~$ simple-image-reducer

Traceback (most recent call last):

  File "/usr/bin/simple-image-reducer", line 28, in <module>
    import Image

**ImportError: No module named Image**

Reason:

Image != image

Solution:

1) make sure it is available

python -m pip install  Image

2) where is it available?

sudo find ~ -name image -type d

-->> directory /home/MyHomeDir/.local/lib/python2.7/site-packages/image ->> OK

3) make simple-image-reducer understand via link:

ln -s ~/.local/lib/python2.7/site-packages/image
~/.local/lib/python2.7/site-packages/Image

4) invoke simple-image-reducer again. Works:-)