Programs & Examples On #Referrals

How to change the docker image installation directory?

On openSUSE Leap 42.1

$cat /etc/sysconfig/docker 
## Path           : System/Management
## Description    : Extra cli switches for docker daemon
## Type           : string
## Default        : ""
## ServiceRestart : docker
#
DOCKER_OPTS="-g /media/data/installed/docker"

Note that DOCKER_OPTS was initially empty and all I did was add in the argument to make docker use my new directory

jquery mobile background image

Try this. This should work:

<div data-role="page" id="page" style="background-image: url('#URL'); background-attachment: fixed; background-repeat: no-repeat; background-size: 100% 100%;"
    data-theme="a">

getCurrentPosition() and watchPosition() are deprecated on insecure origins

I know that the geoLocation API is better but for people whom can't use an SSL, you can still use some sort of services such as geopluginService.

as specified in the documentation you simply send a request with the ip to the service url http://www.geoplugin.net/php.gp?ip=xx.xx.xx.xx the output is a serialized array so you must need to unserialize it before using it.

Remember this service is not very accurate as the geoLocation is, but it is still an easy and fast solution.

Ignoring SSL certificate in Apache HttpClient 4.3

You can use following code snippet for get the HttpClient instance without ssl certification checking.

private HttpClient getSSLHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        LogLoader.serverLog.trace("In getSSLHttpClient()");

        SSLContext context = SSLContext.getInstance("SSL");

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        context.init(null, new TrustManager[] { tm }, null);

        HttpClientBuilder builder = HttpClientBuilder.create();
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context);
        builder.setSSLSocketFactory(sslConnectionFactory);

        PlainConnectionSocketFactory plainConnectionSocketFactory = new PlainConnectionSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory).register("http", plainConnectionSocketFactory).build();

        PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(registry);
        ccm.setMaxTotal(BaseConstant.CONNECTION_POOL_SIZE);
        ccm.setDefaultMaxPerRoute(BaseConstant.CONNECTION_POOL_SIZE);
        builder.setConnectionManager((HttpClientConnectionManager) ccm);

        builder.disableRedirectHandling();

        LogLoader.serverLog.trace("Out getSSLHttpClient()");

        return builder.build();
    }

Floating elements within a div, floats outside of div. Why?

You can easily do with first you can make the div flex and apply justify content right or left and your problem is solved.

_x000D_
_x000D_
<div style="display: flex;padding-bottom: 8px;justify-content: flex-end;">_x000D_
     <button style="font-weight: bold;outline: none;background-color: #2764ff;border-radius: 3px;margin-left: 12px;border: none;padding: 3px 6px;color: white;text-align: center;font-family: 'Open Sans', sans-serif;text-decoration: none;margin-right: 14px;">Sense</button>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

Submit button not working in Bootstrap form

The .btn classes are designed for , or elements (though some browsers may apply a slightly different rendering).

If you’re using .btn classes on elements that are used to trigger functionality ex. collapsing content, these links should be given a role="button" to adequately communicate their meaning to assistive technologies such as screen readers. I hope this help.

How to manually update datatables table with new JSON data

You can use:

$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);

Jsfiddle

Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.

Multiple Buttons' OnClickListener() android

You can use this

    TextView output = (TextView) findViewById(R.id.output);
    one.setOnClickListener(youractivity.this);
    // set the onclicklistener for other buttons also

    @Override
    public void onClick(View v) {
      int id = v.getId();
    switch(id) {
    case R.id.oneButton:      
       append("1",output);
       break;
    case R.id.twoButton:
        append("2",output);
       break;
    case R.id.threeButton:
        append("3",output);
       break;
     } 
      }

 private void append(String s,TextView t){
  t.setText(s); 
}

you can identify the views in your activity in a separate method.

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

How To Pass GET Parameters To Laravel From With GET Method ?

An alternative to msturdy's solution is using the request helper method available to you.

This works in exactly the same way, without the need to import the Input namespace use Illuminate\Support\Facades\Input at the top of your controller.

For example:

class SearchController extends BaseController {

    public function search()
    {
        $category = request('category', 'default');
        $term = request('term'); // no default defined

        ...
    }
}

django MultiValueDictKeyError error, how do I deal with it

Another thing to remember is that request.POST['keyword'] refers to the element identified by the specified html name attribute keyword.

So, if your form is:

<form action="/login/" method="POST">
  <input type="text" name="keyword" placeholder="Search query">
  <input type="number" name="results" placeholder="Number of results">
</form>

then, request.POST['keyword'] and request.POST['results'] will contain the value of the input elements keyword and results, respectively.

how to use free cloud database with android app?

Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.

Here are some providers which have a "free-tier" (may change in future):

  1. Firebase (Google) - https://firebase.google.com/
  2. AWS Mobile (Amazon) - https://aws.amazon.com/mobile/
  3. Azure Mobile (Microsoft) - https://azure.microsoft.com/en-in/services/app-service/mobile/
  4. MongoDB Realm (MongoDB) - https://www.mongodb.com/realm
  5. Back4app (Popular) - https://www.back4app.com/

Open source solutions:

  1. Parse - http://parseplatform.org/
  2. Apache User Grid - https://usergrid.apache.org/
  3. SupaBase (under development) - https://supabase.io/

Loop in Jade (currently known as "Pug") template engine

An unusual but pretty way of doing it

Without index:

each _ in Array(5)
  = 'a'

Will print: aaaaa

With index:

each _, i in Array(5)
  = i

Will print: 01234

Notes: In the examples above, I have assigned the val parameter of jade's each iteration syntax to _ because it is required, but will always return undefined.

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

AngularJS - ng-if check string empty value

This is what may be happening, if the value of item.photo is undefined then item.photo != '' will always show as true. And if you think logically it actually makes sense, item.photo is not an empty string (so this condition comes true) since it is undefined.

Now for people who are trying to check if the value of input is empty or not in Angular 6, can go by this approach.

Lets say this is the input field -

_x000D_
_x000D_
<input type="number" id="myTextBox" name="myTextBox"_x000D_
 [(ngModel)]="response.myTextBox"_x000D_
            #myTextBox="ngModel">
_x000D_
_x000D_
_x000D_

To check if the field is empty or not this should be the script.

_x000D_
_x000D_
<div *ngIf="!myTextBox.value" style="color:red;">_x000D_
 Your field is empty_x000D_
</div>
_x000D_
_x000D_
_x000D_

Do note the subtle difference between the above answer and this answer. I have added an additional attribute .value after my input name myTextBox.
I don't know if the above answer worked for above version of Angular, but for Angular 6 this is how it should be done.

How to register multiple implementations of the same interface in Asp.Net Core?

A factory approach is certainly viable. Another approach is to use inheritance to create individual interfaces that inherit from IService, implement the inherited interfaces in your IService implementations, and register the inherited interfaces rather than the base. Whether adding an inheritance hierarchy or factories is the "right" pattern all depends on who you speak to. I often have to use this pattern when dealing with multiple database providers in the same application that uses a generic, such as IRepository<T>, as the foundation for data access.

Example interfaces and implementations:

public interface IService 
{
}

public interface IServiceA: IService
{}

public interface IServiceB: IService
{}

public IServiceC: IService
{}

public class ServiceA: IServiceA 
{}

public class ServiceB: IServiceB
{}

public class ServiceC: IServiceC
{}

Container:

container.Register<IServiceA, ServiceA>();
container.Register<IServiceB, ServiceB>();
container.Register<IServiceC, ServiceC>();

Best solution to protect PHP code without encryption

in my opinion is, but just in case if your php code program is written for standalone model... best solutions is c) You could wrap the php in a container like Phalanger (.NET). as everyone knows it's bind tightly to the system especially if your program is intended for windows users. you just can make your own protection algorithm in windows programming language like .NET/VB/C# or whatever you know in .NET prog.lang.family sets.

Remove a character at a certain position in a string - javascript

If you omit the particular index character then use this method

function removeByIndex(str,index) {
      return str.slice(0,index) + str.slice(index+1);
}
    
var str = "Hello world", index=3;
console.log(removeByIndex(str,index));

// Output: "Helo world"

recyclerview No adapter attached; skipping layout

I lost 16 minutes of my life with this issue, so I'll just admit to this incredibly embarrassing mistake that I was making- I'm using Butterknife and I bind the view in onCreateView in this fragment.

It took a long time to figure out why I had no layoutmanager - but obviously the views are injected so they won't actually be null, so the the recycler will never be null .. whoops!

@BindView(R.id.recycler_view)
RecyclerView recyclerView;

    @Override
public View onCreateView(......) {
    View v = ...;
    ButterKnife.bind(this, v);
    setUpRecycler()
 }

public void setUpRecycler(Data data)
   if (recyclerView == null) {
 /*very silly because this will never happen*/
       LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
       //more setup
       //...
    }
    recyclerView.setAdapter(new XAdapter(data));
}

If you are getting an issue like this trace your view and use something like uiautomatorviewer

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

I think it's best to explicitly state where the form posts. If you want to be totally safe, enter the same URL the form is on in the action attribute if you want it to submit back to itself. Although mainstream browsers evaluate "" to the same page, you can't guarantee that non-mainstream browsers will.

And of course, the entire URL including GET data like Juddling points out.

Can I open a dropdownlist using jQuery

One thing that this doesn't answer is what happens when you click on one of the options in the select list after you have done your size = n and made it absolute positioning.

Because the blur event makes it size = 1 and changes it back to how it looks, you should have something like this as well

$("option").click(function(){
    $(this).parent().blur();
});

Also, if you're having issues with the absolute positioned select list showing behind other elements, just put a

z-index: 100;

or something like that in the style of the select.

batch file to list folders within a folder to one level

Dir

Use the dir command. Type in dir /? for help and options.

dir /a:d /b

Redirect

Then use a redirect to save the list to a file.

> list.txt

Together

dir /a:d /b > list.txt

This will output just the names of the directories. if you want the full path of the directories use this below.


Full Path

for /f "delims=" %%D in ('dir /a:d /b') do echo %%~fD

Alternative

other method just using the for command. See for /? for help and options. This can output just the name %%~nxD or the full path %%~fD

for /d %%D in (*) do echo %%~fD

Notes

To use these commands directly on the command line, change the double percent signs to single percent signs. %% to %

To redirect the for methods, just add the redirect after the echo statements. Use the double arrow >> redirect here to append to the file, else only the last statement will be written to the file due to overwriting all the others.

... echo %%~fD>> list.txt

How to obtain image size using standard Python class (without using external library)?

Here's a python 3 script that returns a tuple containing an image height and width for .png, .gif and .jpeg without using any external libraries (ie what Kurt McKee referenced above). Should be relatively easy to transfer it to Python 2.

import struct
import imghdr

def get_image_size(fname):
    '''Determine the image type of fhandle and return its size.
    from draco'''
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            return
        if imghdr.what(fname) == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                return
            width, height = struct.unpack('>ii', head[16:24])
        elif imghdr.what(fname) == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif imghdr.what(fname) == 'jpeg':
            try:
                fhandle.seek(0) # Read 0xff next
                size = 2
                ftype = 0
                while not 0xc0 <= ftype <= 0xcf:
                    fhandle.seek(size, 1)
                    byte = fhandle.read(1)
                    while ord(byte) == 0xff:
                        byte = fhandle.read(1)
                    ftype = ord(byte)
                    size = struct.unpack('>H', fhandle.read(2))[0] - 2
                # We are at a SOFn block
                fhandle.seek(1, 1)  # Skip `precision' byte.
                height, width = struct.unpack('>HH', fhandle.read(4))
            except Exception: #IGNORE:W0703
                return
        else:
            return
        return width, height

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

How can I check for Python version in a program that uses new language features?

As noted above, syntax errors occur at compile time, not at run time. While Python is an "interpreted language", Python code is not actually directly interpreted; it's compiled to byte code, which is then interpreted. There is a compile step that happens when a module is imported (if there is no already-compiled version available in the form of a .pyc or .pyd file) and that's when you're getting your error, not (quite exactly) when your code is running.

You can put off the compile step and make it happen at run time for a single line of code, if you want to, by using eval, as noted above, but I personally prefer to avoid doing that, because it causes Python to perform potentially unnecessary run-time compilation, for one thing, and for another, it creates what to me feels like code clutter. (If you want, you can generate code that generates code that generates code - and have an absolutely fabulous time modifying and debugging that in 6 months from now.) So what I would recommend instead is something more like this:

import sys
if sys.hexversion < 0x02060000:
    from my_module_2_5 import thisFunc, thatFunc, theOtherFunc
else:
    from my_module import thisFunc, thatFunc, theOtherFunc

.. which I would do even if I only had one function that used newer syntax and it was very short. (In fact I would take every reasonable measure to minimize the number and size of such functions. I might even write a function like ifTrueAElseB(cond, a, b) with that single line of syntax in it.)

Another thing that might be worth pointing out (that I'm a little amazed no one has pointed out yet) is that while earlier versions of Python did not support code like

value = 'yes' if MyVarIsTrue else 'no'

..it did support code like

value = MyVarIsTrue and 'yes' or 'no'

That was the old way of writing ternary expressions. I don't have Python 3 installed yet, but as far as I know, that "old" way still works to this day, so you can decide for yourself whether or not it's worth it to conditionally use the new syntax, if you need to support the use of older versions of Python.

Stop floating divs from wrapping

The CSS property display: inline-block was designed to address this need. You can read a bit about it here: http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

Below is an example of its use. The key elements are that the row element has white-space: nowrap and the cell elements have display: inline-block. This example should work on most major browsers; a compatibility table is available here: http://caniuse.com/#feat=inline-block

<html>
<body>
<style>

.row {
    float:left;
    border: 1px solid yellow;
    width: 100%;
    overflow: auto;
    white-space: nowrap;
}

.cell {
    display: inline-block;
    border: 1px solid red;
    width: 200px;
    height: 100px;
}
</style>

<div class="row">
    <div class="cell">a</div>
    <div class="cell">b</div>
    <div class="cell">c</div>
</div>


</body>
</html>

How to overcome root domain CNAME restrictions?

Sipwiz is correct the only way to do this properly is the HTTP and DNS hybrid approach. My registrar is a re-seller for Tucows and they offer root domain forwarding as a free value added service.

If your domain is blah.com they will ask you where you would like the domain forwarded to, and you type in www.blah.com. They assign the A record to their apache server and automaticly add blah.com as a DNS vhost. The vhost responds with an HTTP 302 error redirecting them to the proper URL. It's simple to script/setup and can be handled by low end would otherwise be scrapped hardware.

Run the following command for an example: curl -v eclecticengineers.com

How to create a self-signed certificate for a domain name for development?

With IIS's self-signed certificate feature, you cannot set the common name (CN) for the certificate, and therefore cannot create a certificate bound to your choice of subdomain.

One way around the problem is to use makecert.exe, which is bundled with the .Net 2.0 SDK. On my server it's at:

C:\Program Files\Microsoft.Net\SDK\v2.0 64bit\Bin\makecert.exe

You can create a signing authority and store it in the LocalMachine certificates repository as follows (these commands must be run from an Administrator account or within an elevated command prompt):

makecert.exe -n "CN=My Company Development Root CA,O=My Company,
 OU=Development,L=Wallkill,S=NY,C=US" -pe -ss Root -sr LocalMachine
 -sky exchange -m 120 -a sha1 -len 2048 -r

You can then create a certificate bound to your subdomain and signed by your new authority:

(Note that the the value of the -in parameter must be the same as the CN value used to generate your authority above.)

makecert.exe -n "CN=subdomain.example.com" -pe -ss My -sr LocalMachine
 -sky exchange -m 120 -in "My Company Development Root CA" -is Root
 -ir LocalMachine -a sha1 -eku 1.3.6.1.5.5.7.3.1

Your certificate should then appear in IIS Manager to be bound to your site as explained in Tom Hall's post.

All kudos for this solution to Mike O'Brien for his excellent blog post at http://www.mikeobrien.net/blog/creating-self-signed-wildcard

How can I edit a view using phpMyAdmin 3.2.4?

try running SHOW CREATE VIEW my_view_name in the sql portion of phpmyadmin and you will have a better idea of what is inside the view

CSS selector - element with a given child

Update 2019

The :has() pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.

To use it, we will write something like:

.foo > .bar:has(> .baz) { /* style here */ }

In a structure like:

<div class="foo">
  <div class="bar">
    <div class="baz">Baz!</div>
  </div>
</div>

This CSS will target the .bar div - because it both has a parent .foo and from its position in the DOM, > .baz resolves to a valid element target.


Original Answer (left for historical purposes) - this portion is no longer accurate

For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:

!div > span { /* style here */

The ! before the div selector indicates that it is the element to be styled, rather than the span. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.

How to understand nil vs. empty vs. blank in Ruby

nil? is a standard Ruby method that can be called on all objects and returns true if the object is nil:

b = nil
b.nil? # => true

empty? is a standard Ruby method that can be called on some objects such as Strings, Arrays and Hashes and returns true if these objects contain no element:

a = []
a.empty? # => true

b = ["2","4"]
b.empty? # => false

empty? cannot be called on nil objects.

blank? is a Rails method that can be called on nil objects as well as empty objects.

How can I make an EXE file from a Python program?

I found this presentation to be very helpfull.

How I Distribute Python applications on Windows - py2exe & InnoSetup

From the site:

There are many deployment options for Python code. I'll share what has worked well for me on Windows, packaging command line tools and services using py2exe and InnoSetup. I'll demonstrate a simple build script which creates windows binaries and an InnoSetup installer in one step. In addition, I'll go over common errors which come up when using py2exe and hints on troubleshooting them. This is a short talk, so there will be a follow-up Open Space session to share experience and help each other solve distribution problems.

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.

How to measure time in milliseconds using ANSI C?

Implementing a portable solution

As it was already mentioned here that there is no proper ANSI solution with sufficient precision for the time measurement problem, I want to write about the ways how to get a portable and, if possible, a high-resolution time measurement solution.

Monotonic clock vs. time stamps

Generally speaking there are two ways of time measurement:

  • monotonic clock;
  • current (date)time stamp.

The first one uses a monotonic clock counter (sometimes it is called a tick counter) which counts ticks with a predefined frequency, so if you have a ticks value and the frequency is known, you can easily convert ticks to elapsed time. It is actually not guaranteed that a monotonic clock reflects the current system time in any way, it may also count ticks since a system startup. But it guarantees that a clock is always run up in an increasing fashion regardless of the system state. Usually the frequency is bound to a hardware high-resolution source, that's why it provides a high accuracy (depends on hardware, but most of the modern hardware has no problems with high-resolution clock sources).

The second way provides a (date)time value based on the current system clock value. It may also have a high resolution, but it has one major drawback: this kind of time value can be affected by different system time adjustments, i.e. time zone change, daylight saving time (DST) change, NTP server update, system hibernation and so on. In some circumstances you can get a negative elapsed time value which can lead to an undefined behavior. Actually this kind of time source is less reliable than the first one.

So the first rule in time interval measuring is to use a monotonic clock if possible. It usually has a high precision, and it is reliable by design.

Fallback strategy

When implementing a portable solution it is worth to consider a fallback strategy: use a monotonic clock if available and fallback to time stamps approach if there is no monotonic clock in the system.

Windows

There is a great article called Acquiring high-resolution time stamps on MSDN about time measurement on Windows which describes all the details you may need to know about software and hardware support. To acquire a high precision time stamp on Windows you should:

  • query a timer frequency (ticks per second) with QueryPerformanceFrequency:

    LARGE_INTEGER tcounter;
    LARGE_INTEGER freq;    
    
    if (QueryPerformanceFrequency (&tcounter) != 0)
        freq = tcounter.QuadPart;
    

    The timer frequency is fixed on the system boot so you need to get it only once.

  • query the current ticks value with QueryPerformanceCounter:

    LARGE_INTEGER tcounter;
    LARGE_INTEGER tick_value;
    
    if (QueryPerformanceCounter (&tcounter) != 0)
        tick_value = tcounter.QuadPart;
    
  • scale the ticks to elapsed time, i.e. to microseconds:

    LARGE_INTEGER usecs = (tick_value - prev_tick_value) / (freq / 1000000);
    

According to Microsoft you should not have any problems with this approach on Windows XP and later versions in most cases. But you can also use two fallback solutions on Windows:

  • GetTickCount provides the number of milliseconds that have elapsed since the system was started. It wraps every 49.7 days, so be careful in measuring longer intervals.
  • GetTickCount64 is a 64-bit version of GetTickCount, but it is available starting from Windows Vista and above.

OS X (macOS)

OS X (macOS) has its own Mach absolute time units which represent a monotonic clock. The best way to start is the Apple's article Technical Q&A QA1398: Mach Absolute Time Units which describes (with the code examples) how to use Mach-specific API to get monotonic ticks. There is also a local question about it called clock_gettime alternative in Mac OS X which at the end may leave you a bit confused what to do with the possible value overflow because the counter frequency is used in the form of numerator and denominator. So, a short example how to get elapsed time:

  • get the clock frequency numerator and denominator:

    #include <mach/mach_time.h>
    #include <stdint.h>
    
    static uint64_t freq_num   = 0;
    static uint64_t freq_denom = 0;
    
    void init_clock_frequency ()
    {
        mach_timebase_info_data_t tb;
    
        if (mach_timebase_info (&tb) == KERN_SUCCESS && tb.denom != 0) {
            freq_num   = (uint64_t) tb.numer;
            freq_denom = (uint64_t) tb.denom;
        }
    }
    

    You need to do that only once.

  • query the current tick value with mach_absolute_time:

    uint64_t tick_value = mach_absolute_time ();
    
  • scale the ticks to elapsed time, i.e. to microseconds, using previously queried numerator and denominator:

    uint64_t value_diff = tick_value - prev_tick_value;
    
    /* To prevent overflow */
    value_diff /= 1000;
    
    value_diff *= freq_num;
    value_diff /= freq_denom;
    

    The main idea to prevent an overflow is to scale down the ticks to desired accuracy before using the numerator and denominator. As the initial timer resolution is in nanoseconds, we divide it by 1000 to get microseconds. You can find the same approach used in Chromium's time_mac.c. If you really need a nanosecond accuracy consider reading the How can I use mach_absolute_time without overflowing?.

Linux and UNIX

The clock_gettime call is your best way on any POSIX-friendly system. It can query time from different clock sources, and the one we need is CLOCK_MONOTONIC. Not all systems which have clock_gettime support CLOCK_MONOTONIC, so the first thing you need to do is to check its availability:

  • if _POSIX_MONOTONIC_CLOCK is defined to a value >= 0 it means that CLOCK_MONOTONIC is avaiable;
  • if _POSIX_MONOTONIC_CLOCK is defined to 0 it means that you should additionally check if it works at runtime, I suggest to use sysconf:

    #include <unistd.h>
    
    #ifdef _SC_MONOTONIC_CLOCK
    if (sysconf (_SC_MONOTONIC_CLOCK) > 0) {
        /* A monotonic clock presents */
    }
    #endif
    
  • otherwise a monotonic clock is not supported and you should use a fallback strategy (see below).

Usage of clock_gettime is pretty straight forward:

  • get the time value:

    #include <time.h>
    #include <sys/time.h>
    #include <stdint.h>
    
    uint64_t get_posix_clock_time ()
    {
        struct timespec ts;
    
        if (clock_gettime (CLOCK_MONOTONIC, &ts) == 0)
            return (uint64_t) (ts.tv_sec * 1000000 + ts.tv_nsec / 1000);
        else
            return 0;
    }
    

    I've scaled down the time to microseconds here.

  • calculate the difference with the previous time value received the same way:

    uint64_t prev_time_value, time_value;
    uint64_t time_diff;
    
    /* Initial time */
    prev_time_value = get_posix_clock_time ();
    
    /* Do some work here */
    
    /* Final time */
    time_value = get_posix_clock_time ();
    
    /* Time difference */
    time_diff = time_value - prev_time_value;
    

The best fallback strategy is to use the gettimeofday call: it is not a monotonic, but it provides quite a good resolution. The idea is the same as with clock_gettime, but to get a time value you should:

#include <time.h>
#include <sys/time.h>
#include <stdint.h>

uint64_t get_gtod_clock_time ()
{
    struct timeval tv;

    if (gettimeofday (&tv, NULL) == 0)
        return (uint64_t) (tv.tv_sec * 1000000 + tv.tv_usec);
    else
        return 0;
}

Again, the time value is scaled down to microseconds.

SGI IRIX

IRIX has the clock_gettime call, but it lacks CLOCK_MONOTONIC. Instead it has its own monotonic clock source defined as CLOCK_SGI_CYCLE which you should use instead of CLOCK_MONOTONIC with clock_gettime.

Solaris and HP-UX

Solaris has its own high-resolution timer interface gethrtime which returns the current timer value in nanoseconds. Though the newer versions of Solaris may have clock_gettime, you can stick to gethrtime if you need to support old Solaris versions.

Usage is simple:

#include <sys/time.h>

void time_measure_example ()
{
    hrtime_t prev_time_value, time_value;
    hrtime_t time_diff;

    /* Initial time */
    prev_time_value = gethrtime ();

    /* Do some work here */

    /* Final time */
    time_value = gethrtime ();

    /* Time difference */
    time_diff = time_value - prev_time_value;
}

HP-UX lacks clock_gettime, but it supports gethrtime which you should use in the same way as on Solaris.

BeOS

BeOS also has its own high-resolution timer interface system_time which returns the number of microseconds have elapsed since the computer was booted.

Example usage:

#include <kernel/OS.h>

void time_measure_example ()
{
    bigtime_t prev_time_value, time_value;
    bigtime_t time_diff;

    /* Initial time */
    prev_time_value = system_time ();

    /* Do some work here */

    /* Final time */
    time_value = system_time ();

    /* Time difference */
    time_diff = time_value - prev_time_value;
}

OS/2

OS/2 has its own API to retrieve high-precision time stamps:

  • query a timer frequency (ticks per unit) with DosTmrQueryFreq (for GCC compiler):

    #define INCL_DOSPROFILE
    #define INCL_DOSERRORS
    #include <os2.h>
    #include <stdint.h>
    
    ULONG freq;
    
    DosTmrQueryFreq (&freq);
    
  • query the current ticks value with DosTmrQueryTime:

    QWORD    tcounter;
    unit64_t time_low;
    unit64_t time_high;
    unit64_t timestamp;
    
    if (DosTmrQueryTime (&tcounter) == NO_ERROR) {
        time_low  = (unit64_t) tcounter.ulLo;
        time_high = (unit64_t) tcounter.ulHi;
    
        timestamp = (time_high << 32) | time_low;
    }
    
  • scale the ticks to elapsed time, i.e. to microseconds:

    uint64_t usecs = (prev_timestamp - timestamp) / (freq / 1000000);
    

Example implementation

You can take a look at the plibsys library which implements all the described above strategies (see ptimeprofiler*.c for details).

ImportError: No module named google.protobuf

The reason for this would be mostly due to the evil command pip install google. I was facing a similar issue for google-cloud, but the same steps are true for protobuf as well. Both of our issues deal with a namespace conflict over the 'google' namespace.

If you executed the pip install google command like I did then you are in the correct place. The google package is actually not owned by Google which can be confirmed by the command pip show google which outputs:

 Name: google
 Version: 1.9.3
 Summary: Python bindings to the Google search engine.
 Home-page: http://breakingcode.wordpress.com/
 Author: Mario Vilas
 Author-email: [email protected]
 License: UNKNOWN
 Location: <Path where this package is installed>
 Requires: beautifulsoup4

Because of this package, the google namespace is reserved and coincidentally google-cloud also expects namespace google > cloud and it results in a namespace collision for these two packages.

See in below screenshot namespace of google-protobuf as google > protobuf

google-cloud namespace screenshot google > cloud > datastore

Solution :- Unofficial google package need to be uninstalled which can be done by using pip uninstall google after this you can reinstall google-cloud using pip install google-cloud or protobuf using pip install protobuf

FootNotes :- Assuming you have installed the unofficial google package by mistake and you don't actually need it along with google-cloud package. If you need both unofficial google and google-cloud above solution won't work.

Furthermore, the unofficial 'google' package installs with it 'soupsieve' and 'beautifulsoup4'. You may want to also uninstall those packages.

Let me know if this solves your particular issue.

Trigger validation of all fields in Angular Form submit

You can use Angular-Validator to do what you want. It's stupid simple to use.

It will:

  • Only validate the fields on $dirty or on submit
  • Prevent the form from being submitted if it is invalid
  • Show custom error message after the field is $dirty or the form is submitted

See the demo

Example

<form angular-validator 
       angular-validator-submit="myFunction(myBeautifulForm)"
       name="myBeautifulForm">
       <!-- form fields here -->
    <button type="submit">Submit</button>
</form>

If the field does not pass the validator then the user will not be able to submit the form.

Check out angular-validator use cases and examples for more information.

Disclaimer: I am the author of Angular-Validator

How to check if any value is NaN in a Pandas DataFrame

I've been using the following and type casting it to a string and checking for the nan value

   (str(df.at[index, 'column']) == 'nan')

This allows me to check specific value in a series and not just return if this is contained somewhere within the series.

A server with the specified hostname could not be found

First of all check your internet connection.. go to safari and check by searching something on google(dont try google.com only.. because it can be cached). If it is working fine, then try now in your app. It must work. This is fired while not having proper internet connection.

Unix command to check the filesize

stat -c %s file.txt

This command will give you the size of the file in bytes. You can learn more about why you should avoid parsing output of ls command over here: http://mywiki.wooledge.org/ParsingLs

Undefined reference to sqrt (or other mathematical functions)

I had the same issue, but I simply solved it by adding -lm after the command that runs my code. Example. gcc code.c -lm

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

Heap space out of memory

I would like to add that this problem is similar to common Java memory leaks.

When the JVM garbage collector is unable to clear the "waste" memory of your Java / Java EE application over time, OutOfMemoryError: Java heap space will be the outcome.

It is important to perform a proper diagnostic first:

  • Enable verbose:gc. This will allow you to understand the memory growing pattern over time.
  • Generate and analyze a JVM Heap Dump. This will allow you to understand your application memory footprint and pinpoint the source of the memory leak(s).
  • You can also use Java profilers and runtime memory leak analyzer such as Plumbr as well to help you with this task.

Angular 6: How to set response type as text while making http call

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}

Allow click on twitter bootstrap dropdown toggle link?

Just add disabled as a class on your anchor:

<a class="dropdown-toggle disabled" href="http://google.com">
    Dropdown <b class="caret"></b></a>

So all together something like:

<ul class="nav">
    <li class="dropdown">
        <a class="dropdown-toggle disabled" href="http://google.com">
            Dropdown <b class="caret"></b>
        </a>
        <ul class="dropdown-menu">
            <li><a href="#">Link 1</a></li>
            <li><a href="#">Link 2</a></li>
        </ul>
    </li>
</ul>

SPAN vs DIV (inline-block)

I think it will help you to understand the basic differences between Inline-Elements (e.g. span) and Block-Elements (e.g. div), in order to understand why "display: inline-block" is so useful.

Problem: inline elements (e.g. span, a, button, input etc.) take "margin" only horizontally (margin-left and margin-right) on, not vertically. Vertical spacing works only on block elements (or if "display:block" is set)

Solution: Only through "display: inline-block" will also take the vertical distance (top and bottom). Reason: Inline element Span, behaves now like a block element to the outside, but like an inline element inside

Here Code Examples:

_x000D_
_x000D_
 /* Inlineelement */

        div,
        span {
            margin: 30px;
        }

        span {
            outline: firebrick dotted medium;
            background-color: antiquewhite;
        }

        span.mitDisplayBlock {
            background: #a2a2a2;
            display: block;
            width: 200px;
            height: 200px;
        }

        span.beispielMargin {
            margin: 20px;
        }

        span.beispielMarginDisplayInlineBlock {
            display: inline-block;
        }

        span.beispielMarginDisplayInline {
            display: inline;
        }

        span.beispielMarginDisplayBlock {
            display: block;
        }

        /* Blockelement */

        div {
            outline: orange dotted medium;
            background-color: deepskyblue;
        }

        .paddingDiv {
            padding: 20px;
            background-color: blanchedalmond;
        }

        .marginDivWrapper {
            background-color: aliceblue;

        }

        .marginDiv {
            margin: 20px;
            background-color: blanchedalmond;
        }
    </style>
    <style>
        /* Nur für das w3school Bild */

        #w3_DIV_1 {
            bottom: 0px;
            box-sizing: border-box;
            height: 391px;
            left: 0px;
            position: relative;
            right: 0px;
            text-size-adjust: 100%;
            top: 0px;
            width: 913.984px;
            perspective-origin: 456.984px 195.5px;
            transform-origin: 456.984px 195.5px;
            background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
            border: 2px dashed rgb(187, 187, 187);
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            padding: 45px;
            transition: all 0.25s ease-in-out 0s;
        }

        /*#w3_DIV_1*/

        #w3_DIV_1:before {
            bottom: 349.047px;
            box-sizing: border-box;
            content: '"Margin"';
            display: block;
            height: 31px;
            left: 0px;
            position: absolute;
            right: 0px;
            text-align: center;
            text-size-adjust: 100%;
            top: 6.95312px;
            width: 909.984px;
            perspective-origin: 454.984px 15.5px;
            transform-origin: 454.984px 15.5px;
            font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
        }

        /*#w3_DIV_1:before*/

        #w3_DIV_2 {
            bottom: 0px;
            box-sizing: border-box;
            color: black;
            height: 297px;
            left: 0px;
            position: relative;
            right: 0px;
            text-decoration: none solid rgb(255, 255, 255);
            text-size-adjust: 100%;
            top: 0px;
            width: 819.984px;
            column-rule-color: rgb(255, 255, 255);
            perspective-origin: 409.984px 148.5px;
            transform-origin: 409.984px 148.5px;
            caret-color: rgb(255, 255, 255);
            background: rgb(76, 175, 80) none repeat scroll 0% 0% / auto padding-box border-box;
            border: 0px none rgb(255, 255, 255);
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            outline: rgb(255, 255, 255) none 0px;
            padding: 45px;
        }

        /*#w3_DIV_2*/

        #w3_DIV_2:before {
            bottom: 258.578px;
            box-sizing: border-box;
            content: '"Border"';
            display: block;
            height: 31px;
            left: 0px;
            position: absolute;
            right: 0px;
            text-align: center;
            text-size-adjust: 100%;
            top: 7.42188px;
            width: 819.984px;
            perspective-origin: 409.984px 15.5px;
            transform-origin: 409.984px 15.5px;
            font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
        }

        /*#w3_DIV_2:before*/

        #w3_DIV_3 {
            bottom: 0px;
            box-sizing: border-box;
            height: 207px;
            left: 0px;
            position: relative;
            right: 0px;
            text-size-adjust: 100%;
            top: 0px;
            width: 729.984px;
            perspective-origin: 364.984px 103.5px;
            transform-origin: 364.984px 103.5px;
            background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            padding: 45px;
        }

        /*#w3_DIV_3*/

        #w3_DIV_3:before {
            bottom: 168.344px;
            box-sizing: border-box;
            content: '"Padding"';
            display: block;
            height: 31px;
            left: 3.64062px;
            position: absolute;
            right: -3.64062px;
            text-align: center;
            text-size-adjust: 100%;
            top: 7.65625px;
            width: 729.984px;
            perspective-origin: 364.984px 15.5px;
            transform-origin: 364.984px 15.5px;
            font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
        }

        /*#w3_DIV_3:before*/

        #w3_DIV_4 {
            bottom: 0px;
            box-sizing: border-box;
            height: 117px;
            left: 0px;
            position: relative;
            right: 0px;
            text-size-adjust: 100%;
            top: 0px;
            width: 639.984px;
            perspective-origin: 319.984px 58.5px;
            transform-origin: 319.984px 58.5px;
            background: rgb(191, 201, 101) none repeat scroll 0% 0% / auto padding-box border-box;
            border: 2px dashed rgb(187, 187, 187);
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            padding: 20px;
        }

        /*#w3_DIV_4*/

        #w3_DIV_4:before {
            box-sizing: border-box;
            content: '"Content"';
            display: block;
            height: 73px;
            text-align: center;
            text-size-adjust: 100%;
            width: 595.984px;
            perspective-origin: 297.984px 36.5px;
            transform-origin: 297.984px 36.5px;
            font: normal normal 400 normal 21px / 73.5px Lato, sans-serif;
        }

        /*#w3_DIV_4:before*/
_x000D_
   <h1> The Box model - content, padding, border, margin</h1>
    <h2> Inline element - span</h2>
    <span>Info: A span element can not have height and width (not without "display: block"), which means it takes the fixed inline size </span>

    <span class="beispielMargin">
        <b>Problem:</b> inline elements (eg span, a, button, input etc.) take "margin" only vertically (margin-left and margin-right)
        on, not horizontal. Vertical spacing works only on block elements (or if display: block is set) </span>

    <span class="beispielMarginDisplayInlineBlock">
        <b>Solution</b> Only through
        <b> "display: inline-block" </ b> will also take the vertical distance (top and bottom). Reason: Inline element Span,
        behaves now like a block element to the outside, but like an inline element inside</span>

    <span class="beispielMarginDisplayInline">Example: here "display: inline". See the margin with Inspector!</span>

    <span class="beispielMarginDisplayBlock">Example: here "display: block". See the margin with Inspector!</span>

    <span class="beispielMarginDisplayInlineBlock">Example: here "display: inline-block". See the margin with Inspector! </span>

    <span class="mitDisplayBlock">Only with the "Display" -property and "block" -Value in addition, a width and height can be assigned. "span" is then like
        a "div" block element.  </span>

    <h2>Inline-Element - Div</h2>
    <div> A div automatically takes "display: block." </ div>
    <div class = "paddingDiv"> Padding is for padding </ div>

    <div class="marginDivWrapper">
Wrapper encapsulates the example "marginDiv" to clarify the "margin" (distance from inner element "marginDiv" to the text)
        of the outer element "marginDivWrapper". Here 20px;)
        
    <div class = "marginDiv"> margin is for the margins </ div>
        And there, too, 20px;
    </div>

    <h2>w3school sample image </h2>
    source:
    <a href="https://www.w3schools.com/css/css_boxmodel.asp">CSS Box Model</a>
    <div id="w3_DIV_1">
        <div id="w3_DIV_2">
            <div id="w3_DIV_3">
                <div id="w3_DIV_4">
                </div>
            </div>
        </div>
    </div>
_x000D_
_x000D_
_x000D_

How to import JSON File into a TypeScript file?

In angular7, I simply used

let routesObject = require('./routes.json');

My routes.json file looks like this

{

    "routeEmployeeList":    "employee-list",
    "routeEmployeeDetail":      "employee/:id"
}

You access json items using

routesObject.routeEmployeeList

powershell is missing the terminator: "

Look closely at the two dashes in

unzipRelease –Src '$ReleaseFile' -Dst '$Destination'

This first one is not a normal dash but an en-dash (&ndash; in HTML). Replace that with the dash found before Dst.

HTML table needs spacing between columns, not rows

This can be achieved by putting padding between the columns using CSS. You can either add padding to the left of all columns except the first, or add padding to the right of all columns except the last. You should avoid adding padding to the right of the last column or to the left of the first as this will insert redundant white space. You should also avoid being too prescriptive with classes to specify which columns should have the additional padding as this will make maintenance harder if you later add a new column.

The 'lobotomised owl selector' allows you to select all siblings, regardless of if they are a th, td or something else.

_x000D_
_x000D_
tr > * + * {
  padding-left: 4em;
}
_x000D_
<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Git ignore local file changes

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

Remove your uncommitted changes

Tracked files

git checkout -f

Untracked files

git clean -fd

Save your changes for later

Tracked files

git stash

Tracked files and untracked files

git stash -u

Reapply your latest stash after git pull:

git stash pop

java.util.regex - importance of Pattern.compile()?

It is matter of performance and memory usage, compile and keep the complied pattern if you need to use it a lot. A typical usage of regex is to validated user input (format), and also format output data for users, in these classes, saving the complied pattern, seems quite logical as they usually called a lot.

Below is a sample validator, which is really called a lot :)

public class AmountValidator {
    //Accept 123 - 123,456 - 123,345.34
    private static final String AMOUNT_REGEX="\\d{1,3}(,\\d{3})*(\\.\\d{1,4})?|\\.\\d{1,4}";
    //Compile and save the pattern  
    private static final Pattern AMOUNT_PATTERN = Pattern.compile(AMOUNT_REGEX);


    public boolean validate(String amount){

         if (!AMOUNT_PATTERN.matcher(amount).matches()) {
            return false;
         }    
        return true;
    }    
}

As mentioned by @Alan Moore, if you have reusable regex in your code, (before a loop for example), you must compile and save pattern for reuse.

postgresql return 0 if returned value is null

I can think of 2 ways to achieve this:

  • IFNULL():

    The IFNULL() function returns a specified value if the expression is NULL.If the expression is NOT NULL, this function returns the expression.

Syntax:

IFNULL(expression, alt_value)

Example of IFNULL() with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND IFNULL( price, 0 ) > ( SELECT AVG( IFNULL( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND IFNULL( price, 0 ) < ( SELECT AVG( IFNULL( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5
  • COALESCE()

    The COALESCE() function returns the first non-null value in a list.

Syntax:

COALESCE(val1, val2, ...., val_n)

Example of COALESCE() with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

How to call servlet through a JSP page

Why would you want to do this? You shouldn't be executing controller code in the view, and most certainly shouldn't be trying to pull code inside of another servlet into the view either.

Do all of your processing and refactoring of the application first, then just pass off the results to a view. Make the view as dumb as possible and you won't even run into these problems.

If this kind of design is hard for you, try Freemarker or even something like Velocity (although I don't recommend it) to FORCE you to do this. You never have to do this sort of thing ever.

To put it more accurately, the problem you are trying to solve is just a symptom of a greater problem - your architecture/design of your servlets.

Change the Blank Cells to "NA"

While many options above function well, I found coercion of non-target variables to chr problematic. Using ifelse and grepl within lapply resolves this off-target effect (in limited testing). Using slarky's regular expression in grepl:

set.seed(42)
x1 <- sample(c("a","b"," ", "a a", NA), 10, TRUE)
x2 <- sample(c(rnorm(length(x1),0, 1), NA), length(x1), TRUE)

df <- data.frame(x1, x2, stringsAsFactors = FALSE)

The problem of coercion to character class:

df2 <- lapply(df, function(x) gsub("^$|^ $", NA, x))
lapply(df2, class)

$x1 [1] "character"

$x2 [1] "character"

Resolution with use of ifelse:

df3 <- lapply(df, function(x) ifelse(grepl("^$|^ $", x)==TRUE, NA, x))
lapply(df3, class)

$x1 [1] "character"

$x2 [1] "numeric"

Gerrit error when Change-Id in commit messages are missing

under my .git/hooks folder, some sample files were missing. like commit-msg,post-commit.sample,post-update.sample...adding these files resolved my change id missing issue.

Do the parentheses after the type name make a difference with new?

Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

  • In C++1998 there are 2 types of initialization: zero and default
  • In C++2003 a 3rd type of initialization, value initialization was added.

Assume:

struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m

In a C++98 compiler, the following should occur:

  • new A - indeterminate value
  • new A() - zero-initialize

  • new B - default construct (B::m is uninitialized)

  • new B() - default construct (B::m is uninitialized)

  • new C - default construct (C::m is zero-initialized)

  • new C() - default construct (C::m is zero-initialized)

In a C++03 conformant compiler, things should work like so:

  • new A - indeterminate value
  • new A() - value-initialize A, which is zero-initialization since it's a POD.

  • new B - default-initializes (leaves B::m uninitialized)

  • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

  • new C - default-initializes C, which calls the default ctor.

  • new C() - value-initializes C, which calls the default ctor.

So in all versions of C++ there's a difference between new A and new A() because A is a POD.

And there's a difference in behavior between C++98 and C++03 for the case new B().

This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.

check if a key exists in a bucket in s3 using boto3

Try This simple

import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket_name') # just Bucket name
file_name = 'A/B/filename.txt'      # full file path
obj = list(bucket.objects.filter(Prefix=file_name))
if len(obj) > 0:
    print("Exists")
else:
    print("Not Exists")

What's the difference between "Solutions Architect" and "Applications Architect"?

There are no industry standard definitions for Architect job titles -- Application/System/Software/Solution Architect all refer in general to a senior developer with strong design and leadership skills. The balance of design, strategy, development (often of core services or frameworks) and management differ based on the organization and project.

The only "Architect" job title that really has a different meaning for me is "Enterprise Architect", which I see as more of a IT strategy position.

How do I create and access the global variables in Groovy?

Just declare the variable at class or script scope, then access it from inside your methods or closures. Without an example, it's hard to be more specific for your particular problem though.

However, global variables are generally considered bad form.

Why not return the variable from one function, then pass it into the next?

Difference between Encapsulation and Abstraction

Just a few more points to make thing clear,

One must not confuse data abstraction and the abstract class. They are different.

Generally we say abstract class or method is to basically hide something. But no.. That is wrong. What is the word abstract means ? Google search says the English word abstraction means

"Existing in thought or as an idea but not having a physical or concrete existence."

And thats right in case of abstract class too. It is not hiding the content of the method but the method's content is already empty (not having a physical or concrete existence) but it determines how a method should be (existing in thought or as an idea) or a method should be in the calss.

So when do you actually use abstract methods ?

  • When a method from base class will differ in each child class that extends it.
  • And so you want to make sure the child class have this function implemented.
  • This also ensures that method, to have compulsory signature like, it must have n number of parameters.

So about abstract class! - An Abstract class cannot be instantiated only extended! But why ?

  • A class with abstract method must be prevented from creating its own instance because the abstract methods in it, are not having any meaningful implementation.
  • You can even make a class abstract, if for some reason you find that it is meaning less to have a instance of your that class.

An Abstract class help us avoid creating new instance of it!

An abstract method in a class forces the child class to implement that function for sure with the provided signature!

TypeError: Object of type 'bytes' is not JSON serializable

I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json). my_json_object in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.

The way I ended up solving it: the write_to_file.json will have everything up to the bytes object that is causing the issue.

In my particular case this was a line obtained through

for line in text:
    json_object['line'] = line.strip()

I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:

for line in text:
    json_object['line'] = line.strip().decode()

CSS: fixed position on x-axis but not y?

Its a simple technique using the script also. You can check a demo here too.

JQuery

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

CSS

#header {
    top: 15px;
    left: 15px;
    position: absolute;
}

Update Credit: @PierredeLESPINAY

As commented, to make the script support the changes in the css without having to recode them in the script. You can use the following.

var leftOffset = parseInt($("#header").css('left')); //Grab the left position left first
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + leftOffset //Use it later
    });
});

Demo :)

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

Try this

SELECT CONVERT(varchar(11),getdate(),101) -- Converts to 'mm/dd/yyyy'

SELECT CONVERT(varchar(11),getdate(),103) -- Converts to 'dd/mm/yyyy'

More info here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

Page vs Window in WPF?

A Window is always shown independently, A Page is intended to be shown inside a Frame or inside a NavigationWindow.

Encrypting & Decrypting a String in C#

If you need to store a password in memory and would like to have it encrypted you should use SecureString:

http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx

For more general uses I would use a FIPS approved algorithm such as Advanced Encryption Standard, formerly known as Rijndael. See this page for an implementation example:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:

Producer:

@Service
public void FooServiceImpl implements FooService{}

Consumer:

@Autowired
private FooService fooService;

or

@Autowired
private void setFooService(FooService fooService) {}

but not ok if you use it by name:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");

It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined In this case, assigning name to @Service("fooService") would make it work.

How can I set the aspect ratio in matplotlib?

A simple option using plt.gca() to get current axes and set aspect

        plt.gca().set_aspect('equal')

in place of your last line

How to plot two columns of a pandas data frame using points?

You can specify the style of the plotted line when calling df.plot:

df.plot(x='col_name_1', y='col_name_2', style='o')

The style argument can also be a dict or list, e.g.:

import numpy as np
import pandas as pd

d = {'one' : np.random.rand(10),
     'two' : np.random.rand(10)}

df = pd.DataFrame(d)

df.plot(style=['o','rx'])

All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot.

Output

Conditional HTML Attributes using Razor MVC3

I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

@{
 var htmlAttr = new Dictionary<string, object>();
 htmlAttr.Add("id", strElementId);
 if (!CSSClass.IsEmpty())
 {
   htmlAttr.Add("class", strCSSClass);
 }
}

@* ... *@

@Html.TextBox("somename", "", htmlAttr)

If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

How to get AM/PM from a datetime in PHP

$currentDateTime = $row['date'];
echo $newDateTime = date('l jS \of F Y h:i:s A', strtotime($currentDateTime));

View RDD contents in Python Spark?

By latest document, you can use rdd.collect().foreach(println) on the driver to display all, but it may cause memory issues on the driver, best is to use rdd.take(desired_number)

https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html

To print all elements on the driver, one can use the collect() method to first bring the RDD to the driver node thus: rdd.collect().foreach(println). This can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use the take(): rdd.take(100).foreach(println).

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

Ok, so the answer was derived from some other posts about this problem and it is:

If your ViewData contains a SelectList with the same name as your DropDownList i.e. "submarket_0", the Html helper will automatically populate your DropDownList with that data if you don't specify the 2nd parameter which in this case is the source SelectList.

What happened with my error was:

Because the table containing the drop down lists was in a partial view and the ViewData had been changed and no longer contained the SelectList I had referenced, the HtmlHelper (instead of throwing an error) tried to find the SelectList called "submarket_0" in the ViewData (GRRRR!!!) which it STILL couldnt find, and then threw an error on that :)

Please correct me if im wrong

SQL - Select first 10 rows only?

What you're looking for is a LIMIT clause.

SELECT a.names,
         COUNT(b.post_title) AS num
    FROM wp_celebnames a
    JOIN wp_posts b ON INSTR(b.post_title, a.names) > 0
    WHERE b.post_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
GROUP BY a.names
ORDER BY num DESC
   LIMIT 10

Unable to compile class for JSP

From the error it seems that you are trying to import something which is not a class.

If your MyFunctions is a class, you should import it like this:

<%@page import="com.TransportPortal.MyFunctions"%>

If it is a package and you want to import everything in the package you should do like this:

<%@page import="com.TransportPortal.MyFunctions.* "%>

Edit:

There are two cases which will give you this error, edited to cover both.

Using classes with the Arduino

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230935955 states:

By default, the Arduino IDE and libraries does not use the operator new and operator delete. It does support malloc() and free(). So the solution is to implement new and delete operators for yourself, to use these functions.

Code:

#include <stdlib.h> // for malloc and free
void* operator new(size_t size) { return malloc(size); } 
void operator delete(void* ptr) { free(ptr); }

This let's you create objects, e.g.

C* c; // declare variable
c = new C(); // create instance of class C
c->M(); // call method M
delete(c); // free memory

Regards, tamberg

Spark : how to run spark file from spark shell

You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven

<repository>
      <id>Spark repository</id>
      <url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>

And then the dependency:

<dependency>
      <groupId>spark</groupId>
      <artifactId>spark</artifactId>
      <version>1.2.0</version>
</dependency>

In terms of running a file with spark commands: you can simply do this:

echo"
   import org.apache.spark.sql.*
   ssc = new SQLContext(sc)
   ssc.sql("select * from mytable").collect
" > spark.input

Now run the commands script:

cat spark.input | spark-shell

Handling JSON Post Request in Go

There are two reasons why json.Decoder should be preferred over json.Unmarshal - that are not addressed in the most popular answer from 2013:

  1. February 2018, go 1.10 introduced a new method json.Decoder.DisallowUnknownFields() which addresses the concern of detecting unwanted JSON-input
  2. req.Body is already an io.Reader. Reading its entire contents and then performing json.Unmarshal wastes resources if the stream was, say a 10MB block of invalid JSON. Parsing the request body, with json.Decoder, as it streams in would trigger an early parse error if invalid JSON was encountered. Processing I/O streams in realtime is the preferred go-way.

Addressing some of the user comments about detecting bad user input:

To enforce mandatory fields, and other sanitation checks, try:

d := json.NewDecoder(req.Body)
d.DisallowUnknownFields() // catch unwanted fields

// anonymous struct type: handy for one-time use
t := struct {
    Test *string `json:"test"` // pointer so we can test for field absence
}{}

err := d.Decode(&t)
if err != nil {
    // bad JSON or unrecognized json field
    http.Error(rw, err.Error(), http.StatusBadRequest)
    return
}

if t.Test == nil {
    http.Error(rw, "missing field 'test' from JSON object", http.StatusBadRequest)
    return
}

// optional extra check
if d.More() {
    http.Error(rw, "extraneous data after JSON object", http.StatusBadRequest)
    return
}

// got the input we expected: no more, no less
log.Println(*t.Test)

Playground

Typical output:

$ curl -X POST -d "{}" http://localhost:8082/strict_test

expected json field 'test'

$ curl -X POST -d "{\"Test\":\"maybe?\",\"Unwanted\":\"1\"}" http://localhost:8082/strict_test

json: unknown field "Unwanted"

$ curl -X POST -d "{\"Test\":\"oops\"}g4rB4g3@#$%^&*" http://localhost:8082/strict_test

extraneous data after JSON

$ curl -X POST -d "{\"Test\":\"Works\"}" http://localhost:8082/strict_test 

log: 2019/03/07 16:03:13 Works

Can we define min-margin and max-margin, max-padding and min-padding in css?

Late to the party, but I'd like to share my simple solution. I'm gonna assume that if we want something that would work like a min-margin, it's because we have a margin: auto; in the first place, and we don't want that margin auto being smaller than a certain number.

We can do that with two div, one inside another.

Here is an example with horizontal margins.

<div class="margin-auto">
  <div class="min-margin">
    <p>Lorem Ipsum etc</p>
  </div>
</div>

As for the css:

.margin-auto {
  margin: 0 auto;
}

.min-margin {
  margin: 0 16px;
  max-width: 300px;
}

How to get full file path from file name?

I know my answer it's too late, but it might helpful to other's
Try,

Void Main()
{
string filename = @"test.txt";
string filePath= AppDomain.CurrentDomain.BaseDirectory + filename ;
Console.WriteLine(filePath);
}

Java: Add elements to arraylist with FOR loop where element name has increasing number

Thomas's solution is good enough for this matter.

If you want to use loop to access these three Answers, you first need to put there three into an array-like data structure ---- kind of like a principle. So loop is used for operating on an array-like data structure, not just simply to simplify typing task. And you cannot use FOR loop by simply just giving increasing-number-names to the elements.

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

This should be lightning fast:

int msb(unsigned int v) {
  static const int pos[32] = {0, 1, 28, 2, 29, 14, 24, 3,
    30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19,
    16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
  v |= v >> 1;
  v |= v >> 2;
  v |= v >> 4;
  v |= v >> 8;
  v |= v >> 16;
  v = (v >> 1) + 1;
  return pos[(v * 0x077CB531UL) >> 27];
}

Removing input background colour for Chrome autocomplete?

Adding one hour delay would pause any css changes on the input element.
This is more better rather than adding transition animation or inner shadow.

input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill{
  transition-delay: 3600s;
}

Grouping into interval of 5 minutes within a time range

I came across the same issue.

I found that it is easy to group by any minute interval is just dividing epoch by minutes in amount of seconds and then either rounding or using floor to get ride of the remainder. So if you want to get interval in 5 minutes you would use 300 seconds.

    SELECT COUNT(*) cnt, 
    to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300) 
    AT TIME ZONE 'UTC' as interval_alias
    FROM TABLE_NAME GROUP BY interval_alias
interval_alias       cnt
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:45:00  8
2010-11-16 10:55:00  11 

This will return the data correctly group by the selected minutes interval; however, it will not return the intervals that don't contains any data. In order to get those empty intervals we can use the function generate_series.

    SELECT generate_series(MIN(date_trunc('hour',timestamp_column)),
    max(date_trunc('minute',timestamp_column)),'5m') as interval_alias FROM 
    TABLE_NAME

Result:

interval_alias       
-------------------    
2010-11-16 10:30:00  
2010-11-16 10:35:00
2010-11-16 10:40:00   
2010-11-16 10:45:00
2010-11-16 10:50:00   
2010-11-16 10:55:00   

Now to get the result with interval with zero occurrences we just outer join both result sets.

    SELECT series.minute as interval,  coalesce(cnt.amnt,0) as count from 
       (
       SELECT count(*) amnt,
       to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
       AT TIME ZONE 'UTC' as interval_alias
       from TABLE_NAME  group by interval_alias
       ) cnt
    
    RIGHT JOIN 
       (    
       SELECT generate_series(min(date_trunc('hour',timestamp_column)),
       max(date_trunc('minute',timestamp_column)),'5m') as minute from TABLE_NAME 
       ) series
  on series.minute = cnt.interval_alias

The end result will include the series with all 5 minute intervals even those that have no values.

interval             count
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:40:00  0
2010-11-16 10:45:00  8
2010-11-16 10:50:00  0 
2010-11-16 10:55:00  11 

The interval can be easily changed by adjusting the last parameter of generate_series. In our case we use '5m' but it could be any interval we want.

Visual Studio: ContextSwitchDeadlock

If you don't want to disable this exception, all you need to do is to let your application pump some messages at least once every 60 seconds. It will prevent this exception to happen. Try calling System.Threading.Thread.CurrentThread.Join(10) once in a while. There are other calls you can do that let the messages pump.

List file using ls command in Linux with full path

For listing everything with full path, only in current directory

find $PWD -maxdepth 1

Same as above but only matches a particular extension, case insensitive (.sh files in this case)

find $PWD -maxdepth 1 -iregex '.+\.sh'

$PWD is for current directory, it can be replaced with any directory

mydir="/etc/sudoers.d/" ; find $mydir -maxdepth 1

maxdepth prevents find from going into subdirectories, for example you can set it to "2" for listing items in children as well. Simply remove it if you need it recursive.

To limit it to only files, can use -type f option.

find $PWD -maxdepth 1 -type f

Simplest way to detect a mobile device in PHP

<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))
{
    echo('This is mobile device');
}
else
{
   echo('This is Desktop/Laptop device');
}
?>

How to remove close button on the jQuery UI dialog?

document.querySelector('.ui-dialog-titlebar-close').style.display = 'none'

Setting the default page for ASP.NET (Visual Studio) server configuration

If you are running against IIS rather than the VS webdev server, ensure that Index.aspx is one of your default files and that directory browsing is turned off.

How to group by week in MySQL?

Figured it out... it's a little cumbersome, but here it is.

FROM_DAYS(TO_DAYS(TIMESTAMP) -MOD(TO_DAYS(TIMESTAMP) -1, 7))

And, if your business rules say your weeks start on Mondays, change the -1 to -2.


Edit

Years have gone by and I've finally gotten around to writing this up. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

"ImportError: No module named" when trying to run Python script

I have found that the solution to this problem was extensively documented here:

https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/

Basically, you must install the packages within the Jupyter environment, issuing shell commands like:

!{sys.executable} -m pip install numpy

Please check the above link for an authoritative full answer.

Saving ssh key fails

You have to create the .ssh folder yourself for saving ssh keys.

By the way, I used this path style: C:/Users/you/.ssh/id_rsa

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

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

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

Another feature is the returnStatus option.

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

These options where added based on this issue.

See official documentation for the sh command.

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

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

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

How do I use jQuery to redirect?

This is a shorthand Ajax function, which is equivalent to:

$.ajax({  type: "POST",
           url: url,  
          data: { username: value_login.val(), firstname: value_firstname.val(), 
                  lastname: value_lastname.val(), email: value_email.val(),
                  password: value_password.val()
                },
          dataType: "json"
       success: success// -> call your func here  
      });

Hope This helps

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

Mailto on submit button

Or you can create a form with action:mailto

<form action="mailto:[email protected]"> 

check this out.

http://webdesign.about.com/od/forms/a/aa072699mailto.htm

But this actually submits a form via email.Is this what you wanted? You can also use just

<button onclick=""> and then some javascript with it to ahieve this.

And you can make a <a> look like button. There can be a lot of ways to work this around. Do a little search.

Change Timezone in Lumen or Laravel 5

There are two ways to update your code. 1. Please open the file app.php file present in config directory at lool of your project. Go down the page and check Application Timezone where you will find

'timezone' => 'UTC',

Here you can add your timezone like

'timezone' => 'Europe/Paris',

If you want to manage your timezone from .env file, then you can add below code in your config.php file.

'timezone' => env('APP_TIMEZONE', 'UTC'),

and add the below line in your .env file.

APP_TIMEZONE='Europe/Paris'

Please check the link below for more information: https://laravel.com/docs/5.6/configuration#accessing-configuration-values

Twitter Bootstrap date picker

Some people posted the link to this bootstrap-datepicker.js implementation. I used that one in the following way, it works with Bootstrap 3.

This is the markup I used:

<div class="input-group date col-md-3" data-date-format="dd-mm-yyyy" data-date="01-01-2014">                        
    <input id="txtHomeLoanStartDate" class="form-control" type="text" readonly="" value="01-01-2014" size="14" />
    <span class="input-group-addon add-on">
        <span class="glyphicon glyphicon-calendar"</span>
    </span>
</div>

This is the javascript:

$('.date').datepicker();

I also included the javascript file downloaded from the link above, along with it's css file, and of course, you should remove any bootstrap grid classes like the col-md-3 to suit your needs.

How to use if-else logic in Java 8 stream forEach

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.


Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:

    animalMap.forEach(
            (key, value) -> {
                if (value != null) {
                    myMap.put(key, value);
                } else {
                    myList.add(key);
                }
            }
    );

Streaming via RTSP or RTP in HTML5

Chrome will never implement support RTSP streaming.

At least, in the words of a Chromium developer here:

we're never going to add support for this

Filtering array of objects with lodash based on property value

_x000D_
_x000D_
let myArr = [_x000D_
    { name: "john", age: 23 },_x000D_
    { name: "john", age: 43 },_x000D_
    { name: "jim", age: 101 },_x000D_
    { name: "bob", age: 67 },_x000D_
];_x000D_
_x000D_
// this will return old object (myArr) with items named 'john'_x000D_
let list = _.filter(myArr, item => item.name === 'jhon');_x000D_
_x000D_
//  this will return new object referenc (new Object) with items named 'john' _x000D_
let list = _.map(myArr, item => item.name === 'jhon').filter(item => item.name);
_x000D_
_x000D_
_x000D_

Array versus linked-list

It's really a matter of efficiency, the overhead to insert, remove or move (where you are not simply swapping) elements inside a linked list is minimal, i.e. the operation itself is O(1), verses O(n) for an array. This can make a significant difference if you are operating heavily on a list of data. You chose your data-types based on how you will be operating on them and choose the most efficient for the algorithm you are using.

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

Why are empty catch blocks a bad idea?

There are rare instances where it can be justified. In Python you often see this kind of construction:

try:
    result = foo()
except ValueError:
    result = None

So it might be OK (depending on your application) to do:

result = bar()
if result == None:
    try:
        result = foo()
    except ValueError:
        pass # Python pass is equivalent to { } in curly-brace languages
 # Now result == None if bar() returned None *and* foo() failed

In a recent .NET project, I had to write code to enumerate plugin DLLs to find classes that implement a certain interface. The relevant bit of code (in VB.NET, sorry) is:

    For Each dllFile As String In dllFiles
        Try
            ' Try to load the DLL as a .NET Assembly
            Dim dll As Assembly = Assembly.LoadFile(dllFile)
            ' Loop through the classes in the DLL
            For Each cls As Type In dll.GetExportedTypes()
                ' Does this class implement the interface?
                If interfaceType.IsAssignableFrom(cls) Then

                    ' ... more code here ...

                End If
            Next
        Catch ex As Exception
            ' Unable to load the Assembly or enumerate types -- just ignore
        End Try
    Next

Although even in this case, I'd admit that logging the failure somewhere would probably be an improvement.

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

Create table variable in MySQL

TO answer your question: no, MySQL does not support Table-typed variables in the same manner that SQL Server (http://msdn.microsoft.com/en-us/library/ms188927.aspx) provides. Oracle provides similar functionality but calls them Cursor types instead of table types (http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems012.htm).

Depending your needs you can simulate table/cursor-typed variables in MySQL using temporary tables in a manner similar to what is provided by both Oracle and SQL Server.

However, there is an important difference between the temporary table approach and the table/cursor-typed variable approach and it has a lot of performance implications (this is the reason why Oracle and SQL Server provide this functionality over and above what is provided with temporary tables).

Specifically: table/cursor-typed variables allow the client to collate multiple rows of data on the client side and send them up to the server as input to a stored procedure or prepared statement. What this eliminates is the overhead of sending up each individual row and instead pay that overhead once for a batch of rows. This can have a significant impact on overall performance when you are trying to import larger quantities of data.

A possible work-around:

What you may want to try is creating a temporary table and then using a LOAD DATA (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) command to stream the data into the temporary table. You could then pass them name of the temporary table into your stored procedure. This will still result in two calls to the database server, but if you are moving enough rows there may be a savings there. Of course, this is really only beneficial if you are doing some kind of logic inside the stored procedure as you update the target table. If not, you may just want to LOAD DATA directly into the target table.

Update OpenSSL on OS X with Homebrew

I had problems installing some Wordpress plugins on my local server running php56 on OSX10.11. They failed connection on the external API over SSL.

Installing openSSL didn't solved my problem. But then I figured out that CURL also needed to be reinstalled.

This solved my problem using Homebrew.

brew rm curl && brew install curl --with-openssl

brew uninstall php56 && brew install php56 --with-homebrew-curl --with-openssl

Sharing link on WhatsApp from mobile website (not application) for Android

Recently WhatsApp updated on its official website that we need to use this HTML tag in order to make it shareable to mobile sites:

_x000D_
_x000D_
<a href="whatsapp://send?text=Hello%20World!">Hello, world!</a>
_x000D_
_x000D_
_x000D_

You can replace text= to have your link or any text content

Do subclasses inherit private fields?

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

How do I kill background processes / jobs when my shell script exits?

trap 'kill $(jobs -p)' EXIT

I would make only minor changes to Johannes' answer and use jobs -pr to limit the kill to running processes and add a few more signals to the list:

trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

What is the use of System.in.read()?

system.in.read() method reads a byte and returns as an integer but if you enter a no between 1 to 9 ,it will return 48+ values because in ascii code table ,ascii values of 1-9 are 48-57 . hope , it will help.

Extracting the last n characters from a string in R

Try this:

x <- "some text in a string"
n <- 5
substr(x, nchar(x)-n, nchar(x))

It shoudl give:

[1] "string"

How to add a footer in ListView?

The activity in which you want to add listview footer and i have also generate an event on listview footer click.

  public class MainActivity extends Activity
{

        @Override
        protected void onCreate(Bundle savedInstanceState)
         {

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

            ListView  list_of_f = (ListView) findViewById(R.id.list_of_f);

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

            View view = inflater.inflate(R.layout.web_view, null);  // i have open a webview on the listview footer

            RelativeLayout  layoutFooter = (RelativeLayout) view.findViewById(R.id.layoutFooter);

            list_of_f.addFooterView(view);

        }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg" >

    <ImageView
        android:id="@+id/dept_nav"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/dept_nav" />

    <ListView
        android:id="@+id/list_of_f"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/dept_nav"
        android:layout_margin="5dp"
        android:layout_marginTop="10dp"
        android:divider="@null"
        android:dividerHeight="0dp"
        android:listSelector="@android:color/transparent" >
    </ListView>

</RelativeLayout>

The remote host closed the connection. The error code is 0x800704CD

One can reproduce the error with the code below:

public ActionResult ClosingTheConnectionAction(){
   try
   {
      //we need to set buffer to false to
      //make sure data is written in chunks
      Response.Buffer = false;  
      var someText = "Some text here to make things happen ;-)";
      var content = GetBytes( someText );

      for(var i=0; i < 100; i++)
      {
         Response.OutputStream.Write(content, 0, content.Length);
      }

      return View();
   }
   catch(HttpException hex)
   {
      if (hex.Message.StartsWith("The remote host closed the connection. The error code is 0x800704CD."))
            {
                //react on remote host closed the connection exception.
                var msg = hex.Message;
            }  
   }
   catch(Exception somethingElseHappened)
   {
      //handle it with some other code
   }

   return View();
} 

Now run the website in debug mode. Put a breakpoint in the loop that writes to the output stream. Go to that action method and after the first iteration passed close the tab of the browser. Hit F10 to continue the loop. After it hit the next iteration you will see the exception. Enjoy your exception :-)

How to remove new line characters from data rows in mysql?

Playing with above answers, this one works for me

REPLACE(REPLACE(column_name , '\n', ''), '\r', '')

How to disable textbox from editing?

The TextBox has a property called ReadOnly. If you set that property to true then the TextBox will still be able to scroll but the user wont be able to change the value.

Where are SQL Server connection attempts logged?

Another way to check on connection attempts is to look at the server's event log. On my Windows 2008 R2 Enterprise machine I opened the server manager (right-click on Computer and select Manage. Then choose Diagnostics -> Event Viewer -> Windows Logs -> Applcation. You can filter the log to isolate the MSSQLSERVER events. I found a number that looked like this

Login failed for user 'bogus'. The user is not associated with a trusted SQL Server connection. [CLIENT: 10.12.3.126]

Read files from a Folder present in project

Copy Always to output directory is set then try the following:

 Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
 String Root = Directory.GetCurrentDirectory();

How to load URL in UIWebView in Swift?

Swift 4 Update Creating a WebView programatically.

import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {

var webView: WKWebView!

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.uiDelegate = self
    view = webView
}
override func viewDidLoad() {
    super.viewDidLoad()

    let myURL = URL(string: "https://www.apple.com")
    let myRequest = URLRequest(url: myURL!)
    webView.loadRequest(myRequest)
}}

what is the use of xsi:schemaLocation?

If you go into any of those locations, then you will find what is defined in those schema. For example, it tells you what is the data type of the ini-method key words value.

How to host a Node.Js application in shared hosting

A2 Hosting permits node.js on their shared hosting accounts. I can vouch that I've had a positive experience with them.

Here are instructions in their KnowledgeBase for installing node.js using Apache/LiteSpeed as a reverse proxy: https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts . It takes about 30 minutes to set up the configuration, and it'll work with npm, Express, MySQL, etc.

See a2hosting.com.

How to set default values for Angular 2 component properties?

That is interesting subject. You can play around with two lifecycle hooks to figure out how it works: ngOnChanges and ngOnInit.

Basically when you set default value to Input that's mean it will be used only in case there will be no value coming on that component. And the interesting part it will be changed before component will be initialized.

Let's say we have such components with two lifecycle hooks and one property coming from input.

@Component({
  selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
  @Input() property: string = 'default';

  ngOnChanges(changes) {
    console.log('Changed', changes.property.currentValue, changes.property.previousValue);
  }

  ngOnInit() {
    console.log('Init', this.property);
  }

}

Situation 1

Component included in html without defined property value

As result we will see in console: Init default

That's mean onChange was not triggered. Init was triggered and property value is default as expected.

Situation 2

Component included in html with setted property <cmp [property]="'new value'"></cmp>

As result we will see in console:

Changed new value Object {}

Init new value

And this one is interesting. Firstly was triggered onChange hook, which setted property to new value, and previous value was empty object! And only after that onInit hook was triggered with new value of property.

Check if an apt-get package is installed and then install it if it's not on Linux

UpAndAdam wrote:

However you can't simply rely on return codes here for scripting

In my experience you can rely on dkpg's exit codes.

The return code of dpkg -s is 0 if the package is installed and 1 if it's not, so the simplest solution I found was:

dpkg -s <pkg-name> 2>/dev/null >/dev/null || sudo apt-get -y install <pkg-name>

Works fine for me...

undefined reference to WinMain@16 (codeblocks)

Well I know this answer is not an experienced programmer's approach and of an Old It consultant , but it worked for me .

the answer is "TRY TURNING IT ON AND OFF" . restart codeblocks and it works well reminds me of the 2006 comedy show It Crowd .

How to create timer in angular2

You can simply use setInterval utility and use arrow function as callback so that this will point to the component instance.

For ex:

this.interval = setInterval( () => { 
    // call your functions like 
    this.getList();
    this.updateInfo();
});

Inside your ngOnDestroy lifecycle hook, clear the interval.

ngOnDestroy(){
    clearInterval(this.interval);
}

Ansible: filter a list by its attributes

To filter a list of dicts you can use the selectattr filter together with the equalto test:

network.addresses.private_man | selectattr("type", "equalto", "fixed")

The above requires Jinja2 v2.8 or later (regardless of Ansible version).


Ansible also has the tests match and search, which take regular expressions:

match will require a complete match in the string, while search will require a match inside of the string.

network.addresses.private_man | selectattr("type", "match", "^fixed$")

To reduce the list of dicts to a list of strings, so you only get a list of the addr fields, you can use the map filter:

... | map(attribute='addr') | list

Or if you want a comma separated string:

... | map(attribute='addr') | join(',')

Combined, it would look like this.

- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}

Generate list of all possible permutations of a string

Here is a simple solution in C#.

It generates only the distinct permutations of a given string.

    static public IEnumerable<string> permute(string word)
    {
        if (word.Length > 1)
        {

            char character = word[0];
            foreach (string subPermute in permute(word.Substring(1)))
            {

                for (int index = 0; index <= subPermute.Length; index++)
                {
                    string pre = subPermute.Substring(0, index);
                    string post = subPermute.Substring(index);

                    if (post.Contains(character))
                            continue;                       

                    yield return pre + character + post;
                }

            }
        }
        else
        {
            yield return word;
        }
    }

What is the opposite of evt.preventDefault();

this code worked for me to re-instantiate the event after i had used :

event.preventDefault(); to disable the event.


event.preventDefault = false;

Resetting a form in Angular 2 after submit

Use NgForm's .resetForm() rather than .reset() because it is the method that is officially documented in NgForm's public api. (Ref [1])

<form (ngSubmit)="mySubmitHandler(); myNgForm.resetForm()" #myNgForm="ngForm">

The .resetForm() method will reset the NgForm's FormGroup and set it's submit flag to false (See [2]).

Tested in @angular versions 2.4.8 and 4.0.0-rc3

MSIE and addEventListener Problem in Javascript?

Internet Explorer (IE8 and lower) doesn't support addEventListener(...). It has its own event model using the attachEvent method. You could use some code like this:

var element = document.getElementById('container');
if (document.addEventListener){
    element .addEventListener('copy', beforeCopy, false); 
} else if (el.attachEvent){
    element .attachEvent('oncopy', beforeCopy);
}

Though I recommend avoiding writing your own event handling wrapper and instead use a JavaScript framework (such as jQuery, Dojo, MooTools, YUI, Prototype, etc) and avoid having to create the fix for this on your own.

By the way, the third argument in the W3C model of events has to do with the difference between bubbling and capturing events. In almost every situation you'll want to handle events as they bubble, not when they're captured. It is useful when using event delegation on things like "focus" events for text boxes, which don't bubble.

Strip first and last character from C string

The most efficient way:

//Note destroys the original string by removing it's last char
// Do not pass in a string literal.
char * getAllButFirstAndLast(char *input)
{
  int len = strlen(input); 
  if(len > 0)
    input++;//Go past the first char
  if(len > 1)
    input[len - 2] = '\0';//Replace the last char with a null termination
  return input;
}


//...
//Call it like so
char str[512];
strcpy(str, "hello world");
char *pMod = getAllButFirstAndLast(str);

The safest way:

void getAllButFirstAndLast(const char *input, char *output)
{
  int len = strlen(input);
  if(len > 0)
    strcpy(output, ++input);
  if(len > 1)
    output[len - 2] = '\0';
}


//...
//Call it like so
char mod[512];
getAllButFirstAndLast("hello world", mod);

The second way is less efficient but it is safer because you can pass in string literals into input. You could also use strdup for the second way if you didn't want to implement it yourself.

How to disable a ts rule for a specific line?

You can use /* tslint:disable-next-line */ to locally disable tslint. However, as this is a compiler error disabling tslint might not help.

You can always temporarily cast $ to any:

delete ($ as any).summernote.options.keyMap.pc.TAB

which will allow you to access whatever properties you want.


Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:

if (false) {
    // @ts-ignore: Unreachable code error
    console.log("hello");
}

Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any instead as that better expresses intent.

How to get file path from OpenFileDialog and FolderBrowserDialog?

you can store the Path into string variable like

string s = choofdlog.FileName;

Convert between UIImage and Base64 string

Swift 4.2 | Xcode 10

extension UIImage {

    /// EZSE: Returns base64 string
    public var base64: String {
        return self.jpegData(compressionQuality: 1.0)!.base64EncodedString()
    }
}

Export query result to .csv file in SQL Server 2008

Using the native SQL Server Management Studio technique to export to CSV (as @8kb suggested) doesn't work if your values contain commas, because SSMS doesn't wrap values in double quotes. A more robust way that worked for me is to simply copy the results (click inside the grid and then CTRL-A, CTRL-C) and paste it into Excel. Then save as CSV file from Excel.

How to pass a PHP variable using the URL

just put

$a='Link1';
$b='Link2';

in your pass.php and you will get your answer and do a double quotation in your link.php:

echo '<a href="pass.php?link=' . $a . '">Link 1</a>';

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

Enable the display of line numbers in Visual Studio

You should edit "settings.json". In that add, "editor.lineNumbers":"on", . You can check comments for various options you have.

In Visual Studio Code - 2017, you can also directly go to a given line number. There are following three ways to do that.

  1. Directly use keyboard shortcut - Ctrl + G.
  2. Under menu Go, use Go to Line - Go > Go to Line
  3. Search for Go to Line in Command Pallete (Cmd + Shift + P).

PDO get the last ID inserted

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

Like this $lid = $conn->lastInsertId();

Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

How to get whole and decimal part of a number?

Just to be different :)

list($whole, $decimal) = sscanf(1.5, '%d.%d');

CodePad.

As an added benefit, it will only split where both sides consist of digits.

svn list of files that are modified in local copy

Using Powershell you can do this:

# Checks for updates and changes in working copy.
# Regex: Excludes unmodified (first 7 columns blank). To exclude more add criteria to negative look ahead.
# -u: svn gets updates
$regex = '^(?!\s{7}).{7}\s+(.+)';
svn status -u | %{ if($_ -match $regex){ $_ } };

This will include property changes. These show in column 2. It will also catch other differences in files that show in columns 3-7.

Sources:

How to secure an ASP.NET Web API

If you want to secure your API in a server to server fashion (no redirection to website for 2 legged authentication). You can look at OAuth2 Client Credentials Grant protocol.

https://dev.twitter.com/docs/auth/application-only-auth

I have developed a library that can help you easily add this kind of support to your WebAPI. You can install it as a NuGet package:

https://nuget.org/packages/OAuth2ClientCredentialsGrant/1.0.0.0

The library targets .NET Framework 4.5.

Once you add the package to your project, it will create a readme file in the root of your project. You can look at that readme file to see how to configure/use this package.

Cheers!

Automated way to convert XML files to SQL database?

If there is XML file with 2 different tables then will:

LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1 
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2

work

Compare a date string to datetime in SQL Server?

Just compare the year, month and day values.

Declare @DateToSearch DateTime
Set @DateToSearch = '14 AUG 2008'

SELECT * 
FROM table1
WHERE Year(column_datetime) = Year(@DateToSearch)
      AND Month(column_datetime) = Month(@DateToSearch)
      AND Day(column_datetime) = Day(@DateToSearch)

git diff between cloned and original remote repository

Another reply to your questions (assuming you are on master and already did "git fetch origin" to make you repo aware about remote changes):

1) Commits on remote branch since when local branch was created:

git diff HEAD...origin/master

2) I assume by "working copy" you mean your local branch with some local commits that are not yet on remote. To see the differences of what you have on your local branch but that does not exist on remote branch run:

git diff origin/master...HEAD

3) See the answer by dbyrne.

AngularJS: Insert HTML from a string

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

Select where count of one field is greater than one

I give an example up on Group By between two table in Sql:

Select cn.name,ct.name,count(ct.id) totalcity from city ct left join country cn on ct.countryid = cn.id Group By cn.name,ct.name Having totalcity > 2


Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

I had a similar issue, but I was not using ASP.Net 1.1 nor updating a control via javascript. My problem only happened on Firefox and not on IE (!).

I added options to a DropDownList on the PreRender event like this:

DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string[] opcoes = HF.value.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);

My "HF" (hiddenfield) had the options separated by the newline, like this:

HF.value = "option 1\n\roption 2\n\roption 3";

The problem was that the HTML page was broken (I mean had newlines) on the options of the "select" that represented the DropDown.

So I resolved my my problem adding one line:

DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string dados = HF.Value.Replace("\r", "");
string[] opcoes = dados.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);

Hope this help someone.

Single vs Double quotes (' vs ")

Double quotes are used for strings (i.e., "this is a string") and single quotes are used for a character (i.e., 'a', 'b' or 'c'). Depending on the programming language and context, you can get away with using double quotes for a character but not single quotes for a string.

HTML doesn't care about which one you use. However, if you're writing HTML inside a PHP script, you should stick with double quotes as you will need to escape them (i.e., \"whatever\") to avoid confusing yourself and PHP.

mysql SELECT IF statement with OR

Presumably this would work:

IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment

What is the difference between Serialization and Marshaling?

Marshalling is usually between relatively closely associated processes; serialization does not necessarily have that expectation. So when marshalling data between processes, for example, you may wish to merely send a REFERENCE to potentially expensive data to recover, whereas with serialization, you would wish to save it all, to properly recreate the object(s) when deserialized.

How do you stash an untracked file?

In git bash, stashing of untracked files is achieved by using the command

git stash --include-untracked
# or
git stash -u

http://git-scm.com/docs/git-stash

git stash removes any untracked or uncommited files from your workspace. And you can revert git stash by using following commands

git stash pop

This will place the file back in your local workspace.

My experience

I had to perform a modification to my gitIgnore file to avoid movement of .classpath and .project files into remote repo. I am not allowed to move this modified .gitIgnore in remote repo as of now.

.classpath and .project files are important for eclipse - which is my java editor.

I first of all selectively added my rest of the files and committed for staging. However, final push cannot be performed unless the modified .gitIgnore fiels and the untracked files viz. .project and .classpath are not stashed.

I used

git stash

for stashing the modified .gitIgnore file.

For stashing .classpath and .project file, I used

git stash --include-untracked

and it removed the files from my workspace. Absence of these files takes away my capability of working on my work location in eclipse. I proceeded on with completing the procedure for pushing the committed files to remote. Once this was done successfully, I used

git stash pop

This pasted the same files back in my workspace. This gave back to me my ability to work on the same project in eclipse. Hope this brushes aside misconceptions.

SQL Server Convert Varchar to Datetime

Try the below

select Convert(Varchar(50),yourcolumn,103) as Converted_Date from yourtbl

How to make div same height as parent (displayed as table-cell)

The child can only take a height if the parent has one already set. See this exaple : Vertical Scrolling 100% height

 html, body {
        height: 100%;
        margin: 0;
    }
    .header{
        height: 10%;
        background-color: #a8d6fe;
    }
    .middle {
        background-color: #eba5a3;
        min-height: 80%;
    }
    .footer {
        height: 10%;
        background-color: #faf2cc;
    }

_x000D_
_x000D_
    $(function() {_x000D_
      $('a[href*="#nav-"]').click(function() {_x000D_
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {_x000D_
          var target = $(this.hash);_x000D_
          target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');_x000D_
          if (target.length) {_x000D_
            $('html, body').animate({_x000D_
              scrollTop: target.offset().top_x000D_
            }, 500);_x000D_
            return false;_x000D_
          }_x000D_
        }_x000D_
      });_x000D_
    });
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.header {_x000D_
  height: 100%;_x000D_
  background-color: #a8d6fe;_x000D_
}_x000D_
.middle {_x000D_
  background-color: #eba5a3;_x000D_
  min-height: 100%;_x000D_
}_x000D_
.footer {_x000D_
  height: 100%;_x000D_
  background-color: #faf2cc;_x000D_
}_x000D_
nav {_x000D_
  position: fixed;_x000D_
  top: 10px;_x000D_
  left: 0px;_x000D_
}_x000D_
nav li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
  <nav>_x000D_
    <ul>_x000D_
      <li>_x000D_
        <a href="#nav-a">got to a</a>_x000D_
      </li>_x000D_
      <li>_x000D_
        <a href="#nav-b">got to b</a>_x000D_
      </li>_x000D_
      <li>_x000D_
        <a href="#nav-c">got to c</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </nav>_x000D_
  <div class="header" id="nav-a">_x000D_
_x000D_
  </div>_x000D_
  <div class="middle" id="nav-b">_x000D_
_x000D_
  </div>_x000D_
  <div class="footer" id="nav-c">_x000D_
_x000D_
  </div>
_x000D_
_x000D_
_x000D_

How can we run a test method with multiple parameters in MSTest?

MSTest has a powerful attribute called DataSource. Using this you can perform data-driven tests as you asked. You can have your test data in XML, CSV, or in a database. Here are few links that will guide you

Special characters like @ and & in cURL POST data

cURL > 7.18.0 has an option --data-urlencode which solves this problem. Using this, I can simply send a POST request as

curl -d name=john --data-urlencode passwd=@31&3*J https://www.mysite.com

Git adding files to repo

I had an issue with connected repository. What's how I fixed:

I deleted manually .git folder under my project folder, run git init and then it all worked.

How to show "if" condition on a sequence diagram?

Very simple , using Alt fragment

Lets take an example of sequence diagram for an ATM machine.Let's say here you want

IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"

Then here is the sequence diagram for the same

ATM machine sequence diagram

Hope this helps!

Why isn't .ico file defined when setting window's icon?

from tkinter import *
from PIL import ImageTk, Image

Tk.call('wm', 'iconphoto', Tk._w, ImageTk.PhotoImage(Image.open('./resources/favicon.ico')))

The above worked for me.

Git: Cannot see new remote branch

What ended up finally working for me was to add the remote repository name to the git fetch command, like this:

git fetch core

Now you can see all of them like this:

git branch --all

How does one capture a Mac's command key via JavaScript?

You can also look at the event.metaKey attribute on the event if you are working with keydown events. Worked wonderfully for me! You can try it here.

How to convert an array to object in PHP?

Little complicated but easy to extend technique:

Suppose you have an array

$a = [
     'name' => 'ankit',
     'age' => '33',
     'dob' => '1984-04-12'
];

Suppose you have have a Person class which may have more or less attributes from this array. for example

class Person 
{
    private $name;
    private $dob;
    private $age;
    private $company;
    private $city;
}

If you still wanna change your array to the person object. You can use ArrayIterator Class.

$arrayIterator = new \ArrayIterator($a); // Pass your array in the argument.

Now you have iterator object.

Create a class extending FilterIterator Class; where you have to define the abstract method accept. Follow the example

class PersonIterator extends \FilterIterator
{
    public function accept()
    {
        return property_exists('Person', parent::current());
    }
}

The above impelmentation will bind the property only if it exists in the class.

Add one more method in the class PersonIterator

public function getObject(Person $object)
{
        foreach ($this as $key => $value)
        {
            $object->{'set' . underscoreToCamelCase($key)}($value);
        }
        return $object;
}

Make sure you have mutators defined in your class. Now you are ready to call these function where you want to create object.

$arrayiterator = new \ArrayIterator($a);
$personIterator = new \PersonIterator($arrayiterator);

$personIterator->getObject(); // this will return your Person Object. 

Using lambda expressions for event handlers

No performance implications that I'm aware of or have ever run into, as far as I know its just "syntactic sugar" and compiles down to the same thing as using delegate syntax, etc.

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

You can use a vector. Instead of worry about different screen sizes you only need to create an .svg file and import it to your project using Vector Asset Studio.

Differences between socket.io and websockets

https://socket.io/docs/#What-Socket-IO-is-not (with my emphasis)

What Socket.IO is not

Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the packet id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server either. Please see the protocol specification here.

// WARNING: the client will NOT be able to connect!
const client = io('ws://echo.websocket.org');

Extract digits from a string in Java

Use regular expression to match your requirement.

String num,num1,num2;
String str = "123-456-789";
String regex ="(\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
num = matcher.group();     
System.out.print(num);                 
}

How to force maven update?

I've got the same error with android-maps-utils dependency. Using aar type package in dependency section solve my problem. By default type is jar so It might be checked what type of dependency in repository is downloaded.

Creating PHP class instance with a string

have a look at example 3 from http://www.php.net/manual/en/language.oop5.basic.php

$className = 'Foo';
$instance = new $className(); // Foo()

What's the difference between equal?, eql?, ===, and ==?

I wrote a simple test for all the above.

def eq(a, b)
  puts "#{[a, '==',  b]} : #{a == b}"
  puts "#{[a, '===', b]} : #{a === b}"
  puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
  puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end

eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)

Set height of chart in Chart.js

Seems like var ctx = $('#myChart'); is returning a list of elements. You would need to reference the first by using ctx[0]. Also height is a property, not a function.

I did it this way in my code:

var ctx = document.getElementById("myChart");
ctx.height = 500;

Powershell script does not run via Scheduled Tasks

NOTE: Please ensure that you select Create a Basic task Action and NOT the Create Task Action.

I found the following solution:

1) Make powershell.exe run as administrator for this

  1. right-click on the powershell.exe icon
  2. click on properties under the shortcut key menu
  3. click on the advance button; check that "run as administrator" is checked.

2) in the task scheduler window under the action pane add the following script as a new command

%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -ExecutionPolicy Bypass -noexit -File "C:\ps1\BackUp.ps1"

enter image description here

How to center a subview of UIView

Objective-C

yourSubView.center = CGPointMake(yourView.frame.size.width  / 2, 
                                 yourView.frame.size.height / 2);

Swift

yourSubView.center = CGPoint(x: yourView.frame.size.width  / 2,
                             y: yourView.frame.size.height / 2)

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

I use three flags to resolve the problem:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                Intent.FLAG_ACTIVITY_CLEAR_TASK | 
                Intent.FLAG_ACTIVITY_NEW_TASK);

Node.js EACCES error when listening on most ports

OMG!! In my case I was doing ....listen(ip, port) instead of ...listen(port, ip) and that was throwing up the error msg: Error: listen EACCES localhost

I was using port numbers >= 3000 and even tried with admin access. Nothing worked out. Then with a closer relook, I noticed the issue. Changed it to ...listen(port, ip) and everything started working fine!!

Just calling this out in case if its useful to someone else...

In Go's http package, how do I get the query string on a POST request?

Below is an example:

value := r.FormValue("field")

for more info. about http package, you could visit its documentation here. FormValue basically returns POST or PUT values, or GET values, in that order, the first one that it finds.

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):

virtualenv is a tool to create isolated Python environments.

The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

That's why people consider insert(0, to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.

How can I set up an editor to work with Git on Windows?

I also use Cygwin on Windows, but with gVim (as opposed to the terminal-based Vim).

To make this work, I have done the following:

  1. Created a one-line batch file (named git_editor.bat) which contains the following: "C:/Program Files/Vim/vim72/gvim.exe" --nofork "%*"
  2. Placed git_editor.bat on in my PATH.
  3. Set GIT_EDITOR=git_editor.bat

With this done, git commit, etc. will correctly invoke the gVim executable.

NOTE 1: The --nofork option to gVim ensures that it blocks until the commit message has been written.

NOTE 2: The quotes around the path to gVim is required if you have spaces in the path.

NOTE 3: The quotes around "%*" are needed just in case Git passes a file path with spaces.

Keep SSH session alive

putty settings

FYI Putty Users can set the options here

multiple axis in matplotlib with different scales

If I understand the question, you may interested in this example in the Matplotlib gallery.

enter image description here

Yann's comment above provides a similar example.


Edit - Link above fixed. Corresponding code copied from the Matplotlib gallery:

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right", axes=par2,
                                        offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())

plt.draw()
plt.show()

#plt.savefig("Test")

How to initialize an array's length in JavaScript?

var arr=[];
arr[5]=0;
alert("length="+arr.length); // gives 6

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

How to remove button shadow (android)

A simpler way to do is adding this tag to your button:

android:stateListAnimator="@null"

though it requires API level 21 or more..

Saving excel worksheet to CSV files with filename+worksheet name using VB

The code above works perfectly with one minor flaw; the resulting file is not saved with a .csv extension. – Tensigh 2 days ago

I added the following to code and it saved my file as a csv. Thanks for this bit of code.It all worked as expected.

ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ThisWorkbook.Name & "-" & WS.Name & ".csv", FileFormat:=xlCSV

Android SDK Manager Not Installing Components

I had a similar issue - very slow xml downloads followed by an empty package list. The SDK, it seems, was trying to use legacy Java installation. Setting the JAVA_HOME to the 1.6 jdk did the trick.

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

How to parse a month name (string) to an integer for comparison in C#?

You don't have to create a DateTime instance to do this. It's as simple as this:

public static class Month
{
    public static int ToInt(this string month)
    {
        return Array.IndexOf(
            CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
            month.ToLower(CultureInfo.CurrentCulture))
            + 1;
    }
}

I'm running on the da-DK culture, so this unit test passes:

[Theory]
[InlineData("Januar", 1)]
[InlineData("Februar", 2)]
[InlineData("Marts", 3)]
[InlineData("April", 4)]
[InlineData("Maj", 5)]
[InlineData("Juni", 6)]
[InlineData("Juli", 7)]
[InlineData("August", 8)]
[InlineData("September", 9)]
[InlineData("Oktober", 10)]
[InlineData("November", 11)]
[InlineData("December", 12)]
public void Test(string monthName, int expected)
{
    var actual = monthName.ToInt();
    Assert.Equal(expected, actual);
}

I'll leave it as an exercise to the reader to create an overload where you can pass in an explicit CultureInfo.

How can I create a marquee effect?

The following should do what you want.

@keyframes marquee {
    from  { text-indent:  100% }
    to    { text-indent: -100% }
}

How to set cookie in node js using express framework?

Set Cookie?

res.cookie('cookieName', 'cookieValue')

Read Cookie?

req.cookies

Demo

const express('express')
    , cookieParser = require('cookie-parser'); // in order to read cookie sent from client

app.get('/', (req,res)=>{

    // read cookies
    console.log(req.cookies) 

    let options = {
        maxAge: 1000 * 60 * 15, // would expire after 15 minutes
        httpOnly: true, // The cookie only accessible by the web server
        signed: true // Indicates if the cookie should be signed
    }

    // Set cookie
    res.cookie('cookieName', 'cookieValue', options) // options is optional
    res.send('')

})

Simulator or Emulator? What is the difference?

This question is probably best answered by taking a look at historical practice.

In the past, I've seen gaming console emulators on PC for the PlayStation & SEGA.

Simulators are commonplace when referring to software that tries to mimic real life actions, such as driving or flying. Gran Turismo and Microsoft Flight Simulator spring to mind as classic examples of simulators.

As for the linguistic difference, emulation usually refers to the action of copying someone's (or something's) praiseworthy characteristics or behaviors. Emulation is distinct from imitation, in which a person is copied for the purpose of mockery.

The linguistic meaning of the verb 'simulation' is essentially to pretend or mimic someone or something.

Checking if jquery is loaded using Javascript

As per this link:

if (typeof jQuery == 'undefined') {
    // jQuery IS NOT loaded, do stuff here.
}


there are a few more in comments of the link as well like,

if (typeof jQuery == 'function') {...}

//or

if (typeof $== 'function') {...}

// or

if (jQuery) {
    alert("jquery is loaded");
} else {
    alert("Not loaded");
}


Hope this covers most of the good ways to get this thing done!!

How to make Python script run as service?

I use this code to daemonize my applications. It allows you start/stop/restart the script using the following commands.

python myscript.py start
python myscript.py stop
python myscript.py restart

In addition to this I also have an init.d script for controlling my service. This allows you to automatically start the service when your operating system boots-up.

Here is a simple example to get your going. Simply move your code inside a class, and call it from the run function inside MyDeamon.

import sys
import time

from daemon import Daemon


class YourCode(object):
    def run(self):
        while True:
            time.sleep(1)


class MyDaemon(Daemon):
    def run(self):
        # Or simply merge your code with MyDaemon.
        your_code = YourCode()
        your_code.run()


if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)

Upstart

If you are running an operating system that is using Upstart (e.g. CentOS 6) - you can also use Upstart to manage the service. If you use Upstart you can keep your script as is, and simply add something like this under /etc/init/my-service.conf

start on started sshd
stop on runlevel [!2345]

exec /usr/bin/python /opt/my_service.py
respawn

You can then use start/stop/restart to manage your service.

e.g.

start my-service
stop my-service
restart my-service

A more detailed example of working with upstart is available here.

Systemd

If you are running an operating system that uses Systemd (e.g. CentOS 7) you can take a look at the following Stackoverflow answer.

Invoking modal window in AngularJS Bootstrap UI using JavaScript

Different version similar to the one offered by Maxim Shoustin

I liked the answer but the part that bothered me was the use of <script id="..."> as a container for the modal's template.

I wanted to place the modal's template in a hidden <div> and bind the inner html with a scope variable called modal_html_template mainly because i think it more correct (and more comfortable to process in WebStorm/PyCharm) to place the template's html inside a <div> instead of <script id="...">

this variable will be used when calling $modal({... 'template': $scope.modal_html_template, ...})

in order to bind the inner html, i created inner-html-bind which is a simple directive

check out the example plunker

<div ng-controller="ModalDemoCtrl">

    <div inner-html-bind inner-html="modal_html_template" class="hidden">
        <div class="modal-header">
            <h3>I'm a modal!</h3>
        </div>
        <div class="modal-body">
            <ul>
                <li ng-repeat="item in items">
                    <a ng-click="selected.item = item">{{ item }}</a>
                </li>
            </ul>
            Selected: <b>{{ selected.item }}</b>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" ng-click="ok()">OK</button>
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        </div>
    </div>

    <button class="btn" ng-click="open()">Open me!</button>
    <div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>

inner-html-bind directive:

app.directive('innerHtmlBind', function() {
  return {
    restrict: 'A',
    scope: {
      inner_html: '=innerHtml'
    },
    link: function(scope, element, attrs) {
      scope.inner_html = element.html();
    }
  }
});

Why does "return list.sort()" return None, not the list?

Here is an email from Guido van Rossum in Python's dev list explaining why he choose not to return self on operations that affects the object and don't return a new one.

This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:

 x.compress().chop(y).sort(z)

which would be the same as

  x.compress()
  x.chop(y)
  x.sort(z)

I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else.

I'd like to reserve chaining for operations that return new values, like string processing operations:

 y = x.rstrip("\n").split(":").lower()

Creating a very simple 1 username/password login in php

<?php
session_start();
  mysql_connect('localhost','root','');
    mysql_select_db('database name goes here');
    $error_msg=NULL;
    //log out code
    if(isset($_REQUEST['logout'])){
                unset($_SESSION['user']);
                unset($_SESSION['username']);
                unset($_SESSION['id']);
                unset($_SESSION['role']);
        session_destroy();
    }
    //

    if(!empty($_POST['submit'])){
        if(empty($_POST['username']))
            $error_msg='please enter username';
        if(empty($_POST['password']))
            $error_msg='please enter password';
        if(empty($error_msg)){
            $sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
            $sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
            $records=mysql_query($sql) or die(mysql_error());

            if($record_new=mysql_fetch_array($records)){

                $_SESSION['user']=$record_new;
                $_SESSION['id']=$record_new['id'];
                $_SESSION['username']=$record_new['username'];
                $_SESSION['role']=$record_new['role'];
                header('location:index.php');
                $error_msg='welcome';
                exit();
            }else{
                $error_msg='invalid details';
            }
        }       
    }

?>

// replace the location with whatever page u want the user to visit when he/she log in