Programs & Examples On #Compositeusertype

CompositeUserType is a Java Interface provided by Hibernate that allows to define a custom type mapping.

How do you access the element HTML from within an Angular attribute directive?

Base on @Mark answer, I add the constructor to directive and it work with me.

I share a sample to whom concern.

constructor(private el: ElementRef, private renderer: Renderer) {
}

TS file

@Directive({ selector: '[accordion]' })
export class AccordionDirective {

  constructor(private el: ElementRef, private renderer: Renderer) {
  }

  @HostListener('click', ['$event']) onClick($event) {
    console.info($event);

    this.el.nativeElement.classList.toggle('is-open');

    var content = this.el.nativeElement.nextElementSibling;
    if (content.style.maxHeight) {
      // accordion is currently open, so close it
      content.style.maxHeight = null;
    } else {
      // accordion is currently closed, so open it
      content.style.maxHeight = content.scrollHeight + "px";

    }
  }
}

HTML

<button accordion class="accordion">Accordian #1</button>
    <div class="accordion-content">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas deleniti molestias necessitatibus quaerat quos incidunt! Quas officiis repellat dolore omnis nihil quo,
        ratione cupiditate! Sed, deleniti, recusandae! Animi, sapiente, nostrum?
      </p>     
    </div>

Demo https://stackblitz.com/edit/angular-directive-accordion?file=src/app/app.component.ts

Export Postgresql table data using pgAdmin

In the pgAdmin4, Right click on table select backup like this

enter image description here

After that into the backup dialog there is Dump options tab into that there is section queries you can select Use Insert Commands which include all insert queries as well in the backup.

enter image description here

Associative arrays in Shell scripts

I think that you need to step back and think about what a map, or associative array, really is. All it is is a way to store a value for a given key, and get that value back quickly and efficiently. You may also want to be able to iterate over the keys to retrieve every key value pair, or delete keys and their associated values.

Now, think about a data structure you use all the time in shell scripting, and even just in the shell without writing a script, that has these properties. Stumped? It's the filesystem.

Really, all you need to have an associative array in shell programming is a temp directory. mktemp -d is your associative array constructor:

prefix=$(basename -- "$0")
map=$(mktemp -dt ${prefix})
echo >${map}/key somevalue
value=$(cat ${map}/key)

If you don't feel like using echo and cat, you can always write some little wrappers; these ones are modelled off of Irfan's, though they just output the value rather than setting arbitrary variables like $value:

#!/bin/sh

prefix=$(basename -- "$0")
mapdir=$(mktemp -dt ${prefix})
trap 'rm -r ${mapdir}' EXIT

put() {
  [ "$#" != 3 ] && exit 1
  mapname=$1; key=$2; value=$3
  [ -d "${mapdir}/${mapname}" ] || mkdir "${mapdir}/${mapname}"
  echo $value >"${mapdir}/${mapname}/${key}"
}

get() {
  [ "$#" != 2 ] && exit 1
  mapname=$1; key=$2
  cat "${mapdir}/${mapname}/${key}"
}

put "newMap" "name" "Irfan Zulfiqar"
put "newMap" "designation" "SSE"
put "newMap" "company" "My Own Company"

value=$(get "newMap" "company")
echo $value

value=$(get "newMap" "name")
echo $value

edit: This approach is actually quite a bit faster than the linear search using sed suggested by the questioner, as well as more robust (it allows keys and values to contain -, =, space, qnd ":SP:"). The fact that it uses the filesystem does not make it slow; these files are actually never guaranteed to be written to the disk unless you call sync; for temporary files like this with a short lifetime, it's not unlikely that many of them will never be written to disk.

I did a few benchmarks of Irfan's code, Jerry's modification of Irfan's code, and my code, using the following driver program:

#!/bin/sh

mapimpl=$1
numkeys=$2
numvals=$3

. ./${mapimpl}.sh    #/ <- fix broken stack overflow syntax highlighting

for (( i = 0 ; $i < $numkeys ; i += 1 ))
do
    for (( j = 0 ; $j < $numvals ; j += 1 ))
    do
        put "newMap" "key$i" "value$j"
        get "newMap" "key$i"
    done
done

The results:

    $ time ./driver.sh irfan 10 5

    real    0m0.975s
    user    0m0.280s
    sys     0m0.691s

    $ time ./driver.sh brian 10 5

    real    0m0.226s
    user    0m0.057s
    sys     0m0.123s

    $ time ./driver.sh jerry 10 5

    real    0m0.706s
    user    0m0.228s
    sys     0m0.530s

    $ time ./driver.sh irfan 100 5

    real    0m10.633s
    user    0m4.366s
    sys     0m7.127s

    $ time ./driver.sh brian 100 5

    real    0m1.682s
    user    0m0.546s
    sys     0m1.082s

    $ time ./driver.sh jerry 100 5

    real    0m9.315s
    user    0m4.565s
    sys     0m5.446s

    $ time ./driver.sh irfan 10 500

    real    1m46.197s
    user    0m44.869s
    sys     1m12.282s

    $ time ./driver.sh brian 10 500

    real    0m16.003s
    user    0m5.135s
    sys     0m10.396s

    $ time ./driver.sh jerry 10 500

    real    1m24.414s
    user    0m39.696s
    sys     0m54.834s

    $ time ./driver.sh irfan 1000 5

    real    4m25.145s
    user    3m17.286s
    sys     1m21.490s

    $ time ./driver.sh brian 1000 5

    real    0m19.442s
    user    0m5.287s
    sys     0m10.751s

    $ time ./driver.sh jerry 1000 5

    real    5m29.136s
    user    4m48.926s
    sys     0m59.336s

Is it possible to use 'else' in a list comprehension?

The syntax a if b else c is a ternary operator in Python that evaluates to a if the condition b is true - otherwise, it evaluates to c. It can be used in comprehension statements:

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

So for your example,

table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))

How to repeat a char using printf?

you can make a function that do this job and use it

#include <stdio.h>

void repeat (char input , int count )
{
    for (int i=0; i != count; i++ )
    {
        printf("%c", input);
    }
}

int main()
{
    repeat ('#', 5);
    return 0;
}

This will output

#####

PHP server on local machine?

AppServ is a small program in Windows to run:

  • Apache
  • PHP
  • MySQL
  • phpMyAdmin

It will also give you a startup and stop button for Apache. Which I find very useful.

Rendering JSON in controller

For the instance of

render :json => @projects, :include => :tasks

You are stating that you want to render @projects as JSON, and include the association tasks on the Project model in the exported data.

For the instance of

render :json => @projects, :callback => 'updateRecordDisplay'

You are stating that you want to render @projects as JSON, and wrap that data in a javascript call that will render somewhat like:

updateRecordDisplay({'projects' => []})

This allows the data to be sent to the parent window and bypass cross-site forgery issues.

How to add an item to an ArrayList in Kotlin?

If you have a MUTABLE collection:

val list = mutableListOf(1, 2, 3)
list += 4

If you have an IMMUTABLE collection:

var list = listOf(1, 2, 3)
list += 4

note that I use val for the mutable list to emphasize that the object is always the same, but its content changes.

In case of the immutable list, you have to make it var. A new object is created by the += operator with the additional value.

How to scroll up or down the page to an anchor using jQuery?

Description

You can do this using jQuery.offset() and jQuery.animate().

Check out the jsFiddle Demonstration.

Sample

function scrollToAnchor(aid){
    var aTag = $("a[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

scrollToAnchor('id3');

More Information

Changing factor levels with dplyr mutate

With the forcats package from the tidyverse this is easy, too.

mutate(dat, x = fct_recode(x, "B" = "A"))

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:

RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’

And from there I ran a restore statement with MOVE using logical names.

RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'

When it was done restoring, I almost wept with joy.

Good luck!

Android - Start service on boot

Just to make searching easier, as mentioned in comments, this is not possible since 3.1 https://stackoverflow.com/a/19856367/6505257

Confirm Password with jQuery Validate

It works if id value and name value are different:

<input type="password" class="form-control"name="password" id="mainpassword">
password: {     required: true,     } , 
cpassword: {required: true, equalTo: '#mainpassword' },

Removing body margin in CSS

This should help you get rid of body margins and default top margin of <h1> tag

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

h1 {
        margin-top: 0px;
    }

HttpGet with HTTPS : SSLPeerUnverifiedException

Note: Do not do this in production code, use http instead, or the actual self signed public key as suggested above.

On HttpClient 4.xx:

import static org.junit.Assert.assertEquals;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;

public class HttpClientTrustingAllCertsTest {

    @Test
    public void shouldAcceptUnsafeCerts() throws Exception {
        DefaultHttpClient httpclient = httpClientTrustingAllSSLCerts();
        HttpGet httpGet = new HttpGet("https://host_with_self_signed_cert");
        HttpResponse response = httpclient.execute( httpGet );
        assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
    }

    private DefaultHttpClient httpClientTrustingAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());

        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        return httpclient;
    }

    private TrustManager[] getTrustingManager() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing
            }

        } };
        return trustAllCerts;
    }
}

Warning about SSL connection when connecting to MySQL database

The defaults for initiating a connection to a MySQL server were changed in the recent past, and (from a quick look through the most popular questions and answers on stack overflow) the new values are causing a lot of confusion. What is worse is that the standard advice seems to be to disable SSL altogether, which is a bit of a disaster in the making.

Now, if your connection is genuinely not exposed to the network (localhost only) or you are working in a non-production environment with no real data, then sure: there's no harm in disabling SSL by including the option useSSL=false.

For everyone else, the following set of options are required to get SSL working with certificate and host verification:

  • useSSL=true
  • sslMode=VERIFY_IDENTITY
  • trustCertificateKeyStoreUrl=file:path_to_keystore
  • trustCertificateKeyStorePassword=password

As an added bonus, seeing as you're already playing with the options, it is simple to disable the weak SSL protocols too:

  • enabledTLSProtocols=TLSv1.2

Example

So as a working example you'll need to follow the following broad steps:

First, make sure you have a valid certificate generated for the MySQL server host, and that the CA certificate is installed onto the client host (if you are using self-signed, then you'll likely need to do this manually, but for the popular public CAs it'll already be there).

Next, make sure that the java keystore contains all the CA certificates. On Debian/Ubuntu this is achieved by running:

update-ca-certificates -f
chmod 644 /etc/ssl/certs/java/cacerts

Then finally, update the connection string to include all the required options, which on Debian/Ubuntu would be something a bit like (adapt as required):

jdbc:mysql://{mysql_server}/confluence?useSSL=true&sslMode=VERIFY_IDENTITY&trustCertificateKeyStoreUrl=file%3A%2Fetc%2Fssl%2Fcerts%2Fjava%2Fcacerts&trustCertificateKeyStorePassword=changeit&enabledTLSProtocols=TLSv1.2&useUnicode=true&characterEncoding=utf8

Reference: https://beansandanicechianti.blogspot.com/2019/11/mysql-ssl-configuration.html

How to use a variable in the replacement side of the Perl substitution operator?

On the replacement side, you must use $1, not \1.

And you can only do what you want by making replace an evalable expression that gives the result you want and telling s/// to eval it with the /ee modifier like so:

$find="start (.*) end";
$replace='"foo $1 bar"';

$var = "start middle end";
$var =~ s/$find/$replace/ee;

print "var: $var\n";

To see why the "" and double /e are needed, see the effect of the double eval here:

$ perl
$foo = "middle";
$replace='"foo $foo bar"';
print eval('$replace'), "\n";
print eval(eval('$replace')), "\n";
__END__
"foo $foo bar"
foo middle bar

(Though as ikegami notes, a single /e or the first /e of a double e isn't really an eval(); rather, it tells the compiler that the substitution is code to compile, not a string. Nonetheless, eval(eval(...)) still demonstrates why you need to do what you need to do to get /ee to work as desired.)

ADB not recognising Nexus 4 under Windows 7

Just to confirm a previous comment. I needed to switch my connection to Camera (PTP) mode in addition to enabling Developer options and then selecting USB Debugging from the newly appeared Developer Options.

Java: method to get position of a match in a String?

public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
   {
    int iii1=0;
    int iii2=0;
    int iii3=0;
    while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
    // iii2 is the number of the occurences
    if(iii2>0) {
        positions_ = new int[iii2];
        while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
            positions_[iii3] = iii1-1;
            iii3 = iii3 + 1;
            System.out.println("position=" + positions_[iii3 - 1]);
        }
    }
    return iii2;
}

Show "Open File" Dialog

I agree John M has best answer to OP's question. Thought not explictly stated, the apparent purpose is to get a selected file name, whereas other answers return either counts or lists. I would add, however, that the msofiledialogfilepicker might be a better option in this case. ie:

Dim f As object
Set f = Application.FileDialog(msoFileDialogFilePicker)
dim varfile as variant 
f.show
with f
    .allowmultiselect = false
     for each varfile in .selecteditems
        msgbox varfile
     next varfile
end with

Note: the value of varfile will remain the same since multiselect is false (only one item is ever selected). I used its value outside the loop with equal success. It's probably better practice to do it as John M did, however. Also, the folder picker can be used to get a selected folder. I always prefer late binding, but I think the object is native to the default access library, so it may not be necessary here

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

In regards to @Anthonyeef great answer, here is a sample code in Java:

private boolean shouldShowFragmentInOnResume;

private void someMethodThatShowsTheFragment() {

    if (this.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
        showFragment();
    } else {
        shouldShowFragmentInOnResume = true;
    }
}

private void showFragment() {
    //Your code here
}

@Override
protected void onResume() {
    super.onResume();

    if (shouldShowFragmentInOnResume) {
        shouldShowFragmentInOnResume = false;
        showFragment();
    }
}

Hiding axis text in matplotlib plots

If you want to hide just the axis text keeping the grid lines:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

Doing set_visible(False) or set_ticks([]) will also hide the grid lines.

Can I embed a .png image into an html page?

Quick google search says you can embed it like this:

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" 
width="16" height="14" alt="embedded folder icon">

But you need a different implementation in Internet Explorer.

http://www.websiteoptimization.com/speed/tweak/inline-images/

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

This query was very useful for me. It shows all values that don't have any matches

select FK_column from FK_table
WHERE FK_column NOT IN
(SELECT PK_column from PK_table)

Simple and fast method to compare images for similarity

Does the screenshot contain only the icon? If so, the L2 distance of the two images might suffice. If the L2 distance doesn't work, the next step is to try something simple and well established, like: Lucas-Kanade. Which I'm sure is available in OpenCV.

__init__() got an unexpected keyword argument 'user'

You can't do

LivingRoom.objects.create(user=instance)

because you have an __init__ method that does NOT take user as argument.

You need something like

#signal function: if a user is created, add control livingroom to the user    
def create_control_livingroom(sender, instance, created, **kwargs):
    if created:
        my_room = LivingRoom()
        my_room.user = instance

Update

But, as bruno has already said it, Django's models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields.

So, following better principles, you should probably have something like

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, *args, temp=65, **kwargs):
        self.temp = temp
        return super().__init__(*args, **kwargs)

Note - If you weren't using temp as a keyword argument, e.g. LivingRoom(65), then you'll have to start doing that. LivingRoom(user=instance, temp=66) or if you want the default (65), simply LivingRoom(user=instance) would do.

Regular expression to get a string between two strings in Javascript

If the data is on multiple lines then you may have to use the following,

/My cow ([\s\S]*)milk/gm

My cow always gives 
milk

Regex 101 example

Call Python function from JavaScript code

Typically you would accomplish this using an ajax request that looks like

var xhr = new XMLHttpRequest();
xhr.open("GET", "pythoncode.py?text=" + text, true);
xhr.responseType = "JSON";
xhr.onload = function(e) {
  var arrOfStrings = JSON.parse(xhr.response);
}
xhr.send();

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

Add a default value to a column through a migration

change_column_default :employees, :foreign, false

MongoDB "root" user

While out of the box, MongoDb has no authentication, you can create the equivalent of a root/superuser by using the "any" roles to a specific user to the admin database.

Something like this:

use admin
db.addUser( { user: "<username>",
          pwd: "<password>",
          roles: [ "userAdminAnyDatabase",
                   "dbAdminAnyDatabase",
                   "readWriteAnyDatabase"

] } )

Update for 2.6+

While there is a new root user in 2.6, you may find that it doesn't meet your needs, as it still has a few limitations:

Provides access to the operations and all the resources of the readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase and clusterAdmin roles combined.

root does not include any access to collections that begin with the system. prefix.

Update for 3.0+

Use db.createUser as db.addUser was removed.

Update for 3.0.7+

root no longer has the limitations stated above.

The root has the validate privilege action on system. collections. Previously, root does not include any access to collections that begin with the system. prefix other than system.indexes and system.namespaces.

Android setOnClickListener method - How does it work?

its an implementation of anonymouse class object creation to give ease of writing less code and to save time

Get data from file input in JQuery

 <script src="~/fileupload/fileinput.min.js"></script>
 <link href="~/fileupload/fileinput.min.css" rel="stylesheet" />

Download above files named fileinput add the path i your index page.

<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"       
 `enter code here`accept=".pdf" multiple>
</div>

<script>
        $("#uploadFile1").fileinput({
            autoReplace: true,
            maxFileCount: 5
        });
</script>

Retrieving a random item from ArrayList

As I can see the code
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
is unreachable.

Text to speech(TTS)-Android

MainActivity.class

import java.util.Locale;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences.Editor;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

    String text;
    EditText et;
    TextToSpeech tts;

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

        et=(EditText)findViewById(R.id.editText1);
        tts=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int status) {
                // TODO Auto-generated method stub
                if(status == TextToSpeech.SUCCESS){
                    int result=tts.setLanguage(Locale.US);
                    if(result==TextToSpeech.LANG_MISSING_DATA ||
                            result==TextToSpeech.LANG_NOT_SUPPORTED){
                        Log.e("error", "This Language is not supported");
                    }
                    else{
                        ConvertTextToSpeech();
                    }
                }
                else
                    Log.e("error", "Initilization Failed!");
            }
        });


    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub

        if(tts != null){

            tts.stop();
            tts.shutdown();
        }
        super.onPause();
    }

    public void onClick(View v){

        ConvertTextToSpeech();

    }

    private void ConvertTextToSpeech() {
        // TODO Auto-generated method stub
        text = et.getText().toString();
        if(text==null||"".equals(text))
        {
            text = "Content not available";
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }else
            tts.speak(text+"is saved", TextToSpeech.QUEUE_FLUSH, null);
    }

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="177dp"
        android:onClick="onClick"
        android:text="Button" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="81dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

</RelativeLayout>

How to use a Java8 lambda to sort a stream in reverse order?

You can use a method reference:

import static java.util.Comparator.*;
import static java.util.stream.Collectors.*;

Arrays.asList(files).stream()
    .filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
    .sorted(comparing(File::lastModified).reversed())
    .skip(numOfNewestToLeave)
    .forEach(item -> item.delete());

In alternative of method reference you can use a lambda expression, so the argument of comparing become:

.sorted(comparing(file -> file.lastModified()).reversed());

What are the use cases for selecting CHAR over VARCHAR in SQL?

Many people have pointed out that if you know the exact length of the value using CHAR has some benefits. But while storing US states as CHAR(2) is great today, when you get the message from sales that 'We have just made our first sale to Australia', you are in a world of pain. I always send to overestimate how long I think fields will need to be rather than making an 'exact' guess to cover for future events. VARCHAR will give me more flexibility in this area.

Android device is not connected to USB for debugging (Android studio)

For example:

My file path:

C:\...\sdk\extras\google\usb_driver\android_winusb.inf

My data to paste:

;Tablet PC

%SingleAdbInterface%        = USB_Install, USB\VID_18D1&PID_0003&MI_01

%CompositeADBInterface%     = USB_Install, USB\VID_18D1&PID_0003&REV_0230&MI_01

How to read the Stock CPU Usage data

So far this has been the most helpful source of information regarding this I could find. Apparently the numbers do NOT reperesent load average in %: http://forum.xda-developers.com/showthread.php?t=1495763

jQuery: Uncheck other checkbox on one checked

Bind a change handler, then just uncheck all of the checkboxes, apart from the one checked:

$('input.example').on('change', function() {
    $('input.example').not(this).prop('checked', false);  
});

Here's a fiddle

Matplotlib-Animation "No MovieWriters Available"

For fellow googlers using Anaconda, install the ffmpeg package:

conda install -c conda-forge ffmpeg

This works on Windows too.

(Original answer used menpo package owner but as mentioned by @harsh their version is a little behind at time of writing)

Move an array element from one array position to another

Here is my one liner ES6 solution with an optional parameter on.

if (typeof Array.prototype.move === "undefined") {
  Array.prototype.move = function(from, to, on = 1) {
    this.splice(to, 0, ...this.splice(from, on))
  }
}

Adaptation of the first solution proposed by digiguru

The parameter on is the number of element starting from from you want to move.

How to get file URL using Storage facade in laravel 5?

Edit: Solution for L5.2+

There's a better and more straightforward solution.

Use Storage::url($filename) to get the full path/URL of a given file. Note that you need to set S3 as your storage filesystem in config/filesystems.php: 'default' => 's3'

Of course, you can also do Storage::disk('s3')->url($filename) in the same way.

As you can see in config/filesystems.php there's also a parameter 'cloud' => 's3' defined, that refers to the Cloud filesystem. In case you want to mantain the storage folder in the local server but retrieve/store some files in the cloud use Storage::cloud(), which also has the same filesystem methods, i.e. Storage::cloud()->url($filename).

The Laravel documentation doesn't mention this method, but if you want to know more about it you can check its source code here.

PHP display current server path

echo $_SERVER["DOCUMENT_ROOT"];

'DOCUMENT_ROOT' The document root directory under which the current script is executing, as defined in the server's configuration file.

http://php.net/manual/en/reserved.variables.server.php

Git commit in terminal opens VIM, but can't get back to terminal

This is in answer to your question...

I'd also like to know how to make it open up in Sublime Text 2 instead

For Windows:

git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"

Check that the path for sublime_text.exe is correct and adjust if needed.

For Mac/Linux:

git config --global core.editor "subl -n -w"

If you get an error message such as:

error: There was a problem with the editor 'subl -n -w'.

Create the alias for subl

sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl

Again check that the path matches for your machine.

For Sublime Text simply save cmd S and close the window cmd W to return to git.

Running vbscript from batch file

Batch files are processed row by row and terminate whenever you call an executable directly.
- To make the batch file wait for the process to terminate and continue, put call in front of it.
- To make the batch file continue without waiting, put start "" in front of it.

I recommend using this single line script to accomplish your goal:

@call cscript "%~dp0necdaily.vbs"

(because this is a single line, you can use @ instead of @echo off)

If you believe your script can only be called from the SysWOW64 versions of cmd.exe, you might try:

@%WINDIR%\SysWOW64\cmd.exe /c call cscript "%~dp0necdaily.vbs"

If you need the window to remain, you can replace /c with /k

Read String line by line

Solution using Java 8 features such as Stream API and Method references

new BufferedReader(new StringReader(myString))
        .lines().forEach(System.out::println);

or

public void someMethod(String myLongString) {

    new BufferedReader(new StringReader(myLongString))
            .lines().forEach(this::parseString);
}

private void parseString(String data) {
    //do something
}

How to display count of notifications in app launcher icon

It works in samsung touchwiz launcher

public static void setBadge(Context context, int count) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", context.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    context.sendBroadcast(intent);
}

public static String getLauncherClassName(Context context) {

    PackageManager pm = context.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

How can I pass arguments to anonymous functions in JavaScript?

<input type="button" value="Click me" id="myButton" />

<script type="text/javascript">
    var myButton = document.getElementById("myButton");

    myButton.myMessage = "it's working";

    myButton.onclick = function() { alert(this.myMessage); };


</script>

This works in my test suite which includes everything from IE6+. The anonymous function is aware of the object which it belongs to therefore you can pass data with the object that's calling it ( in this case myButton ).

Python loop that also accesses previous and next values

I don't know how this hasn't come up yet since it uses only built-in functions and is easily extendable to other offsets:

values = [1, 2, 3, 4]
offsets = [None] + values[:-1], values, values[1:] + [None]
for value in list(zip(*offsets)):
    print(value) # (previous, current, next)

(None, 1, 2)
(1, 2, 3)
(2, 3, 4)
(3, 4, None)

Android map v2 zoom to show all the markers

Use the method "getCenterCoordinate" to obtain the center coordinate and use in CameraPosition.

private void setUpMap() {
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setScrollGesturesEnabled(true);
    mMap.getUiSettings().setTiltGesturesEnabled(true);
    mMap.getUiSettings().setRotateGesturesEnabled(true);

    clientMarker = mMap.addMarker(new MarkerOptions()
            .position(new LatLng(Double.valueOf(-12.1024174), Double.valueOf(-77.0262274)))
            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_taxi))
    );
    clientMarker = mMap.addMarker(new MarkerOptions()
            .position(new LatLng(Double.valueOf(-12.1024637), Double.valueOf(-77.0242617)))
            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_location))
    );

    camPos = new CameraPosition.Builder()
            .target(getCenterCoordinate())
            .zoom(17)
            .build();
    camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
    mMap.animateCamera(camUpd3);
}


public LatLng getCenterCoordinate(){
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    builder.include(new LatLng(Double.valueOf(-12.1024174), Double.valueOf(-77.0262274)));
    builder.include(new LatLng(Double.valueOf(-12.1024637), Double.valueOf(-77.0242617)));
    LatLngBounds bounds = builder.build();
    return bounds.getCenter();
}

Define the selected option with the old input in Laravel / Blade

Also, you can use the ? operator to avoid having to use @if @else @endif syntax. Change:

@if (Input::old('title') == $key)
      <option value="{{ $key }}" selected>{{ $val }}</option>
@else
      <option value="{{ $key }}">{{ $val }}</option>
@endif

Simply to:

<option value="{{ $key }}" {{ (Input::old("title") == $key ? "selected":"") }}>{{ $val }}</option>

jQuery Form Validation before Ajax submit

> Required JS for jquery form validation
> ## jquery-1.7.1.min.js ##
> ## jquery.validate.min.js ##
> ## jquery.form.js ##

$("form#data").validate({
    rules: {
        first: {
                required: true,
            },
        middle: {
            required: true,
        },          
        image: {
            required: true,
        },
    },
    messages: {
        first: {
                required: "Please enter first",
            },
        middle: {
            required: "Please enter middle",
        },          
        image: {
            required: "Please Select logo",
        },
    },
    submitHandler: function(form) {
        var formData = new FormData($("#image")[0]);
        $(form).ajaxSubmit({
            url:"action.php",
            type:"post",
            success: function(data,status){
              alert(data);
            }
        });
    }
});

Truncate a SQLite table if it exists?

Just do delete. This is from the SQLite documentation:

The Truncate Optimization

"When the WHERE is omitted from a DELETE statement and the table being deleted has no triggers, SQLite uses an optimization to erase the entire table content without having to visit each row of the table individually. This "truncate" optimization makes the delete run much faster. Prior to SQLite version 3.6.5, the truncate optimization also meant that the sqlite3_changes() and sqlite3_total_changes() interfaces and the count_changes pragma will not actually return the number of deleted rows. That problem has been fixed as of version 3.6.5."

select records from postgres where timestamp is in certain range

Search till the seconds for the timestamp column in postgress

select * from "TableName" e
    where timestamp >= '2020-08-08T13:00:00' and timestamp < '2020-08-08T17:00:00';

Check whether variable is number or string in JavaScript

Errr? Just use regular expressions! :)

function isInteger(val) {
  return val.match(/^[0-9]$/)
}

function isFloat(val) {
  return val.match(/^[0-9]*/\.[0-9]+$/)
}

Adding an identity to an existing column

Right click on table name in Object Explorer. You will get some options. Click on 'Design'. A new tab will be opened for this table. You can add Identity constraint here in 'Column Properties'.

How to split a long array into smaller arrays, with JavaScript

function chunkArrayInGroups(arr, size) {
    var newArr=[];

    for (var i=0; i < arr.length; i+= size){
    newArr.push(arr.slice(i,i+size));
    }
    return newArr;

}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

If it is something to do with the data in your database, why not utilize database isolation locking to achieve?

How to center the text in PHPExcel merged cell

<?php
    /** Error reporting */
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    date_default_timezone_set('Europe/London');

    /** Include PHPExcel */
    require_once '../Classes/PHPExcel.php';

    $objPHPExcel = new PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValueByColumnAndRow(0, 1, "test");
    $sheet->mergeCells('A1:B1');
    $sheet->getActiveSheet()->getStyle('A1:B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save("test.xlsx");
?>

Using other keys for the waitKey() function of opencv

This works the best for me:

http://www.asciitable.com/

Sometimes it's the simple answers that are the best ;+)

case statement in where clause - SQL Server

simply do the select:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))

Remove Backslashes from Json Data in JavaScript

In React Native , This worked for me

name = "hi \n\ruser"
name.replace( /[\r\n]+/gm, ""); // hi user

Pure CSS collapse/expand div

You just need to iterate the anchors in the two links.

<a href="#hide2" class="hide" id="hide2">+</a>
<a href="#show2" class="show" id="show2">-</a>

See this jsfiddle http://jsfiddle.net/eJX8z/

I also added some margin to the FAQ call to improve the format.

Algorithm to detect overlapping periods

How about a custom interval-tree structure? You'll have to tweak it a little bit to define what it means for two intervals to "overlap" in your domain.

This question might help you find an off-the-shelf interval-tree implementation in C#.

Error installing mysql2: Failed to build gem native extension

This solved my problem once in Windows:

subst X: "C:\Program files\MySQL\MySQL Server 5.5" 
gem install mysql2 -v 0.x.x --platform=ruby -- --with-mysql-dir=X: --with-mysql-lib=X:\lib\opt 
subst X: /D

Get value from input (AngularJS)

If your markup is bound to a controller, directive or anything else with a $scope:

console.log($scope.movie);

How to open Visual Studio Code from the command line on OSX?

For Windows you can use Command:

start Code filename.extension

The above line works for me.

How to write a file or data to an S3 object using boto3

Here's a nice trick to read JSON from s3:

import json, boto3
s3 = boto3.resource("s3").Bucket("bucket")
json.load_s3 = lambda f: json.load(s3.Object(key=f).get()["Body"])
json.dump_s3 = lambda obj, f: s3.Object(key=f).put(Body=json.dumps(obj))

Now you can use json.load_s3 and json.dump_s3 with the same API as load and dump

data = {"test":0}
json.dump_s3(data, "key") # saves json to s3://bucket/key
data = json.load_s3("key") # read json from s3://bucket/key

Two div blocks on same line

Use a table inside a div.

<div>
   <table style='margin-left: auto; margin-right: auto'>
        <tr>
           <td>
              <div>Your content </div>
           </td>
           <td>
              <div>Your content </div>
           </td>
        </tr>
   </table>
</div>

How to pass a view's onClick event to its parent on Android?

If your TextView create click issues, than remove android:inputType="" from your xml file.

MySQL - Trigger for updating same table after insert

Instead you can use before insert and get max pkid for the particular table and then update the maximium pkid table record.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

How do I determine file encoding in OS X?

You can try loading the file into a firefox window then go to View - Character Encoding. There should be a check mark next to the file's encoding type.

VBA - If a cell in column A is not blank the column B equals

Use the function IF :

=IF ( logical_test, value_if_true, value_if_false )

How to diff a commit with its parent?

git diff 15dc8 15dce~1

~1 means 'parent', ~2 'grandparent, etc.

Finding all possible combinations of numbers to reach a given sum

Deduce 0 in the first place. Zero is an identiy for addition so it is useless by the monoid laws in this particular case. Also deduce negative numbers as well if you want to climb up to a positive number. Otherwise you would also need subtraction operation.

So... the fastest algorithm you can get on this particular job is as follows given in JS.

_x000D_
_x000D_
function items2T([n,...ns],t){_x000D_
    var c = ~~(t/n);_x000D_
    return ns.length ? Array(c+1).fill()_x000D_
                                 .reduce((r,_,i) => r.concat(items2T(ns, t-n*i).map(s => Array(i).fill(n).concat(s))),[])_x000D_
                     : t % n ? []_x000D_
                             : [Array(c).fill(n)];_x000D_
};_x000D_
_x000D_
var data = [3, 9, 8, 4, 5, 7, 10],_x000D_
    result;_x000D_
_x000D_
console.time("combos");_x000D_
result = items2T(data, 15);_x000D_
console.timeEnd("combos");_x000D_
console.log(JSON.stringify(result));
_x000D_
_x000D_
_x000D_

This is a very fast algorithm but if you sort the data array descending it will be even faster. Using .sort() is insignificant since the algorithm will end up with much less recursive invocations.

remove legend title in ggplot

Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name argument of the scale_ function to NULL, i.e.

scale_fill_discrete(name = NULL)

(kudos to @pascal for a comment on another thread)

Regular expression to match standard 10 digit phone number

^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$

Matches the following

123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890

If you do not want a match on non-US numbers use

^(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$

Update :
As noticed by user Simon Weaver below, if you are also interested in matching on unformatted numbers just make the separator character class optional as [\s.-]?

^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$

How to script FTP upload and download?

This script generates the command file then pipes the command file to the ftp program, creating a log along the way. Finally print the original bat file, the command files and the log of this session.

@echo on
@echo off > %0.ftp
::== GETmy!dir.bat
>> %0.ftp echo a00002t
>> %0.ftp echo iasdad$2
>> %0.ftp echo help
>> %0.ftp echo prompt
>> %0.ftp echo ascii
>> %0.ftp echo !dir REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo get REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo get CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir WORKLOAD.CP1c.ROLLEDUP.TXT
>> %0.ftp echo get WORKLOAD.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir WORKLOAD.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo *************************************************   
>> %0.ftp echo !dir CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo **************************************************   
>> %0.ftp echo !dir WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo quit
ftp -d -v -s:%0.ftp 150.45.12.18 > %0.log
type %0.bat 
type %0.ftp 
type %0.log 

How to install a specific version of a ruby gem?

Use the -v flag:

$ gem install fog -v 1.8

Where in memory are my variables stored in C?

  • Variables/automatic variables ---> stack section
  • Dynamically allocated variables ---> heap section
  • Initialised global variables -> data section
  • Uninitialised global variables -> data section (bss)
  • Static variables -> data section
  • String constants -> text section/code section
  • Functions -> text section/code section
  • Text code -> text section/code section
  • Registers -> CPU registers
  • Command line inputs -> environmental/command line section
  • Environmental variables -> environmental/command line section

enum Values to NSString (iOS)

I will introduce is the way I use, and it looks better than previous answer.(I thinks)

I would like to illustrate with UIImageOrientation for easy understanding.

typedef enum {
    UIImageOrientationUp = 0,            // default orientation, set to 0 so that it always starts from 0
    UIImageOrientationDown,          // 180 deg rotation
    UIImageOrientationLeft,          // 90 deg CCW
    UIImageOrientationRight,         // 90 deg CW
    UIImageOrientationUpMirrored,    // as above but image mirrored along other axis. horizontal flip
    UIImageOrientationDownMirrored,  // horizontal flip
    UIImageOrientationLeftMirrored,  // vertical flip
    UIImageOrientationRightMirrored, // vertical flip
} UIImageOrientation;

create a method like:

NSString *stringWithUIImageOrientation(UIImageOrientation input) {
    NSArray *arr = @[
    @"UIImageOrientationUp",            // default orientation
    @"UIImageOrientationDown",          // 180 deg rotation
    @"UIImageOrientationLeft",          // 90 deg CCW
    @"UIImageOrientationRight",         // 90 deg CW
    @"UIImageOrientationUpMirrored",    // as above but image mirrored along other axis. horizontal flip
    @"UIImageOrientationDownMirrored",  // horizontal flip
    @"UIImageOrientationLeftMirrored",  // vertical flip
    @"UIImageOrientationRightMirrored", // vertical flip
    ];
    return (NSString *)[arr objectAtIndex:input];
}

All you have to do is :

  1. name your function.

  2. copy contents of enum and paste that between NSArray *arr = @[ and ]; return (NSString *)[arr objectAtIndex:input];

  3. put some @ , " , and comma

  4. PROFIT!!!!

How to change the background colour's opacity in CSS

background: rgba(0,0,0,.5);

you can use rgba for opacity, will only work in ie9+ and better browsers

How to get current time with jQuery

_x000D_
_x000D_
.clock {_x000D_
width: 260px;_x000D_
margin: 0 auto;_x000D_
padding: 30px;_x000D_
color: #FFF;background:#333;_x000D_
}_x000D_
.clock ul {_x000D_
width: 250px;_x000D_
margin: 0 auto;_x000D_
padding: 0;_x000D_
list-style: none;_x000D_
text-align: center_x000D_
}_x000D_
_x000D_
.clock ul li {_x000D_
display: inline;_x000D_
font-size: 3em;_x000D_
text-align: center;_x000D_
font-family: "Arial", Helvetica, sans-serif;_x000D_
text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff, 0 4px 7px #55c6ff_x000D_
}_x000D_
#Date { _x000D_
font-family: 'Arial', Helvetica, sans-serif;_x000D_
font-size: 26px;_x000D_
text-align: center;_x000D_
text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff;_x000D_
padding-bottom: 40px;_x000D_
}_x000D_
_x000D_
#point {_x000D_
position: relative;_x000D_
-moz-animation: mymove 1s ease infinite;_x000D_
-webkit-animation: mymove 1s ease infinite;_x000D_
padding-left: 10px;_x000D_
padding-right: 10px_x000D_
}_x000D_
_x000D_
/* Animasi Detik Kedap - Kedip */_x000D_
@-webkit-keyframes mymove _x000D_
{_x000D_
0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}_x000D_
50% {opacity:0; text-shadow:none; }_x000D_
100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } _x000D_
}_x000D_
_x000D_
@-moz-keyframes mymove _x000D_
{_x000D_
0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}_x000D_
50% {opacity:0; text-shadow:none; }_x000D_
100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
// Making 2 variable month and day_x000D_
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; _x000D_
var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]_x000D_
_x000D_
// make single object_x000D_
var newDate = new Date();_x000D_
// make current time_x000D_
newDate.setDate(newDate.getDate());_x000D_
// setting date and time_x000D_
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());_x000D_
_x000D_
setInterval( function() {_x000D_
// Create a newDate() object and extract the seconds of the current time on the visitor's_x000D_
var seconds = new Date().getSeconds();_x000D_
// Add a leading zero to seconds value_x000D_
$("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);_x000D_
},1000);_x000D_
_x000D_
setInterval( function() {_x000D_
// Create a newDate() object and extract the minutes of the current time on the visitor's_x000D_
var minutes = new Date().getMinutes();_x000D_
// Add a leading zero to the minutes value_x000D_
$("#min").html(( minutes < 10 ? "0" : "" ) + minutes);_x000D_
},1000);_x000D_
_x000D_
setInterval( function() {_x000D_
// Create a newDate() object and extract the hours of the current time on the visitor's_x000D_
var hours = new Date().getHours();_x000D_
// Add a leading zero to the hours value_x000D_
$("#hours").html(( hours < 10 ? "0" : "" ) + hours);_x000D_
}, 1000); _x000D_
});_x000D_
</script>_x000D_
<div class="clock">_x000D_
<div id="Date"></div>_x000D_
<ul>_x000D_
<li id="hours"></li>_x000D_
<li id="point">:</li>_x000D_
<li id="min"></li>_x000D_
<li id="point">:</li>_x000D_
<li id="sec"></li>_x000D_
</ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaScript property access: dot notation vs. brackets?

Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.

How do I import a .sql file in mysql database using PHP?

If you need a User Interface and if you want to use PDO

Here's a simple solution

<form method="post" enctype="multipart/form-data">
    <input type="text" name="db" placeholder="Databasename" />
    <input type="file" name="file">
    <input type="submit" name="submit" value="submit">
</form>

<?php

if(isset($_POST['submit'])){
    $query = file_get_contents($_FILES["file"]["name"]);
    $dbname = $_POST['db'];
    $con = new PDO("mysql:host=localhost;dbname=$dbname","root","");
    $stmt = $con->prepare($query);
    if($stmt->execute()){
        echo "Successfully imported to the $dbname.";
    }
}
?>

Definitely working on my end. Worth a try.

Slack URL to open a channel from browser

Referencing a channel within a conversation

To create a clickable reference to a channel in a Slack conversation, just type # followed by the channel name. For example: #general.

# mention of a channel

To grab a link to a channel through the Slack UI

To share the channel URL externally, you can grab its link by control-clicking (Mac) or right-clicking (Windows) on the channel name:

grabbing a channel's URL

The link would look like this:

https://yourteam.slack.com/messages/C69S1L3SS

Note that this link doesn't change even if you change the name of the channel. So, it is better to use this link rather than the one based on channel's name.

To compose a URL for a channel based on channel name

https://yourteam.slack.com/channels/<channel_name>

Opening the above URL from a browser would launch the Slack client (if available) or open the slack channel on the browser itself.

To compose a URL for a direct message (DM) channel to a user

https://yourteam.slack.com/channels/<username>

Java: Array with loop

If all you want to do is calculate the sum of 1,2,3... n then you could use :

 int sum = (n * (n + 1)) / 2;

Changing CSS for last <li>

I've done this with pure CSS (probably because I come from the future - 3 years later than everyone else :P )

Supposing we have a list:

<ul id="nav">
  <li><span>Category 1</span></li>
  <li><span>Category 2</span></li>
  <li><span>Category 3</span></li>
</ul>

Then we can easily make the text of the last item red with:

ul#nav li:last-child span {
   color: Red;
}

How can I replace newlines using PowerShell?

A CRLF is two characters, of course, the CR and the LF. However, `n consists of both. For example:

PS C:\> $x = "Hello
>> World"

PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>

I think you're running into problems with the `r. I was able to remove the `r from your example, use only `n, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.

Insert the same fixed value into multiple rows

You're looking for UPDATE not insert.

UPDATE mytable
SET    table_column = 'test';

UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).

Hash table runtime complexity (insert, search and delete)

Hash tables are O(1) average and amortized case complexity, however it suffers from O(n) worst case time complexity. [And I think this is where your confusion is]

Hash tables suffer from O(n) worst time complexity due to two reasons:

  1. If too many elements were hashed into the same key: looking inside this key may take O(n) time.
  2. Once a hash table has passed its load balance - it has to rehash [create a new bigger table, and re-insert each element to the table].

However, it is said to be O(1) average and amortized case because:

  1. It is very rare that many items will be hashed to the same key [if you chose a good hash function and you don't have too big load balance.
  2. The rehash operation, which is O(n), can at most happen after n/2 ops, which are all assumed O(1): Thus when you sum the average time per op, you get : (n*O(1) + O(n)) / n) = O(1)

Note because of the rehashing issue - a realtime applications and applications that need low latency - should not use a hash table as their data structure.

EDIT: Annother issue with hash tables: cache
Another issue where you might see a performance loss in large hash tables is due to cache performance. Hash Tables suffer from bad cache performance, and thus for large collection - the access time might take longer, since you need to reload the relevant part of the table from the memory back into the cache.

JVM property -Dfile.encoding=UTF8 or UTF-8?

Both UTF8 and UTF-8 work for me.

What version of Python is on my Mac?

Use the which command. It will show you the path

which python

How to leave a message for a github.com user

Here is another way:

  • Browse someone's commit history (Click commits which is next to branch to see the whole commit history)

  • Click the commit that with the person's username because there might be so many of them

  • Then you should see the web address has a hash concatenated to the URL. Add .patch to this commit URL

  • You will probably see the person's email address there

Example: https://github.com/[username]/[reponame]/commit/[hash].patch

Source: Chris Herron @ Sourcecon

How to declare an array of objects in C#

The issue here is that you've initialized your array, but not its elements; they are all null. So if you try to reference houses[0], it will be null.

Here's a great little helper method you could write for yourself:

T[] InitializeArray<T>(int length) where T : new()
{
    T[] array = new T[length];
    for (int i = 0; i < length; ++i)
    {
        array[i] = new T();
    }

    return array;
}

Then you could initialize your houses array as:

GameObject[] houses = InitializeArray<GameObject>(200);

CMake complains "The CXX compiler identification is unknown"

I just had this problem setting up my new laptop. The issue for me was that my toolchain (CodeSourcery) is 32bit and I had not installed the 32bit libs.

sudo apt-get install ia32-libs

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

Use dynamic (variable) string as regex pattern in JavaScript

To create the regex from a string, you have to use JavaScript's RegExp object.

If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:

var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.


In the general case, escape the string before using as regex:

Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:

function escapeRegExp(stringToGoIntoTheRegex) {
    return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.



Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.

Good tool for testing socket connections?

Try Wireshark or WebScarab second is better for interpolating data into the exchange (not sure Wireshark even can). Anyway, one of them should be able to help you out.

Can't get value of input type="file"?

It's old question but just in case someone bump on this tread...

var input = document.getElementById("your_input");
var file = input.value.split("\\");
var fileName = file[file.length-1];

No need for regex, jQuery....

Has Windows 7 Fixed the 255 Character File Path Limit?

Workarounds are not solutions, therefore the answer is "No".

Still looking for workarounds, here are possible solutions: http://support.code42.com/CrashPlan/Latest/Troubleshooting/Windows_File_Paths_Longer_Than_255_Characters

How to use the gecko executable with Selenium

You need to specify the system property with the path the .exe when starting the Selenium server node. See also the accepted anwser to Selenium grid with Chrome driver (WebDriverException: The path to the driver executable must be set by the webdriver.chrome.driver system property)

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

Toggle visibility property of div

Using jQuery:

$('#play-pause').click(function(){
  if ( $('#video-over').css('visibility') == 'hidden' )
    $('#video-over').css('visibility','visible');
  else
    $('#video-over').css('visibility','hidden');
});

How to input a regex in string.replace?

I would go like this (regex explained in comments):

import re

# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")

# <\/{0,}\[\d+>
# 
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
#    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
#    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»

subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
and there are many other lines in the txt files
with<[3> such tags </[3>"""

result = pattern.sub("", subject)

print(result)

If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.

How to count down in for loop?

If you google. "Count down for loop python" you get these, which are pretty accurate.

how to loop down in python list (countdown)
Loop backwards using indices in Python?

I recommend doing minor searches before posting. Also "Learn Python The Hard Way" is a good place to start.

Benefits of EBS vs. instance-store (and vice-versa)

I've had the exact same experience as Eric at my last position. Now in my new job, I'm going through the same process I performed at my last job... rebuilding all their AMIs for EBS backed instances - and possibly as 32bit machines (cheaper - but can't use same AMI on 32 and 64 machines).

EBS backed instances launch quickly enough that you can begin to make use of the Amazon AutoScaling API which lets you use CloudWatch metrics to trigger the launch of additional instances and register them to the ELB (Elastic Load Balancer), and also to shut them down when no longer required.

This kind of dynamic autoscaling is what AWS is all about - where the real savings in IT infrastructure can come into play. It's pretty much impossible to do autoscaling right with the old s3 "InstanceStore"-backed instances.

Print PDF directly from JavaScript

I used this function to download pdf stream from server.

function printPdf(url) {
        var iframe = document.createElement('iframe');
        // iframe.id = 'pdfIframe'
        iframe.className='pdfIframe'
        document.body.appendChild(iframe);
        iframe.style.display = 'none';
        iframe.onload = function () {
            setTimeout(function () {
                iframe.focus();
                iframe.contentWindow.print();
                URL.revokeObjectURL(url)
                // document.body.removeChild(iframe)
            }, 1);
        };
        iframe.src = url;
        // URL.revokeObjectURL(url)
    }

Convert an NSURL to an NSString

I just fought with this very thing and this update didn't work.

This eventually did in Swift:

let myUrlStr : String = myUrl!.relativePath!

How to reload a div without reloading the entire page?

write a button tag and on click function

var x = document.getElementById('codeRefer').innerHTML;
  document.getElementById('codeRefer').innerHTML = x;

write this all in onclick function

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

I resolved this issue by correcting an error with my Global.asax file arrangement. I had copied across the files from another project and failed to embed the Global.asax.cs within the Global.asax file (both files previously existed at the same level).

Global.asax arrangement

How to download videos from youtube on java?

I know i am answering late. But this code may useful for some one. So i am attaching it here.

Use the following java code to download the videos from YouTube.

package com.mycompany.ytd;

import java.io.File;
import java.net.URL;
import com.github.axet.vget.VGet;

/**
 *
 * @author Manindar
 */
public class YTD {

    public static void main(String[] args) {
        try {
            String url = "https://www.youtube.com/watch?v=s10ARdfQUOY";
            String path = "D:\\Manindar\\YTD\\";
            VGet v = new VGet(new URL(url), new File(path));
            v.download();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Add the below Dependency in your POM.XML file

        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>vget</artifactId>
            <version>1.1.33</version>
        </dependency>

Hope this will be useful.

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

I faced the same problem but the issue was very silly, By mistake I have given wrong relationship I have given relationship between 2 Ids.

How to replace � in a string

No above answer resolve my issue. When i download xml it apppends <xml to my xml. I simply

xml = parser.getXmlFromUrl(url);

xml = xml.substring(3);// it remove first three character from string,

now it is running accurately.

HTTPS setup in Amazon EC2

You need to register a domain(on GoDaddy for example) and put a load balancer in front of your ec2 instance - as DigaoParceiro said in his answer.

The issue is that domains generated by amazon on your ec2 instances are ephemeral. Today the domain is belonging to you, tomorrow it may not.

For that reason, let's encrypt throws an error when you try to register a certificate on amazon generated domain that states:

The ACME server refuses to issue a certificate for this domain name, because it is forbidden by policy

More details about this here: https://community.letsencrypt.org/t/policy-forbids-issuing-for-name-on-amazon-ec2-domain/12692/4

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

cell format round and display 2 decimal places

Input: 0 0.1 1000

=FIXED(E5,2)

Output: 0.00 0.10 1,000.00

=TEXT(E5,"0.00")

Output: 0.00 0.10 1000.00

Note: As you can see FIXED add a coma after a thousand, where TEXT does not.

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

In Swift this problem can be solved by adding the following code in your

viewDidLoad

method.

tableView.registerClass(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "your_reuse_identifier")

Javascript ES6 export const vs export let

In ES6, imports are live read-only views on exported-values. As a result, when you do import a from "somemodule";, you cannot assign to a no matter how you declare a in the module.

However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):

//------ lib.js ------
export let counter = 3;
export function incCounter() {
    counter++;
}

//------ main1.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

// The imported value can’t be changed
counter++; // TypeError

As you can see, the difference really lies in lib.js, not main1.js.


To summarize:

  • You cannot assign to import-ed variables, no matter how you declare the corresponding variables in the module.
  • The traditional let-vs-const semantics applies to the declared variable in the module.
    • If the variable is declared const, it cannot be reassigned or rebound in anywhere.
    • If the variable is declared let, it can only be reassigned in the module (but not the user). If it is changed, the import-ed variable changes accordingly.

Reference: http://exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values

How to call multiple JavaScript functions in onclick event?

A link with 1 function defined

<a href="#" onclick="someFunc()">Click me To fire some functions</a>

Firing multiple functions from someFunc()

function someFunc() {
    showAlert();
    validate();
    anotherFunction();
    YetAnotherFunction();
}

how to get the value of css style using jquery

Yes, you're right. With the css() method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/

But if you want to get its position you can check offset() and position() methods to get it's position.

LISTAGG function: "result of string concatenation is too long"

A new feature added in 12cR2 is the ON OVERFLOW clause of LISTAGG. The query including this clause would look like:

SELECT pid, LISTAGG(Desc, ' ' ON OVERFLOW TRUNCATE ) WITHIN GROUP (ORDER BY seq) AS desc
FROM B GROUP BY pid;

The above will restrict the output to 4000 characters but will not throw the ORA-01489 error.

These are some of the additional options of ON OVERFLOW clause:

  • ON OVERFLOW TRUNCATE 'Contd..' : This will display 'Contd..' at the end of string (Default is ... )
  • ON OVERFLOW TRUNCATE '' : This will display the 4000 characters without any terminating string.
  • ON OVERFLOW TRUNCATE WITH COUNT : This will display the total number of characters at the end after the terminating characters. Eg:- '...(5512)'
  • ON OVERFLOW ERROR : If you expect the LISTAGG to fail with the ORA-01489 error ( Which is default anyway ).

LISTAGG Enhancements in 12c R2

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

On mac os, please follow below steps:

Stop MySQL

$ sudo /usr/local/mysql/support-files/mysql.server stop Start it in safe mode:

$ sudo mysqld_safe --skip-grant-tables (above line is the whole command)

This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:

$ mysql -u root

mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; Start MySQL

sudo /usr/local/mysql/support-files/mysql.server start your new password is 'password'.

JSON encode MySQL results

The code below works fine here!

<?php

  $con=mysqli_connect("localhost",$username,$password,databaseName);

  // Check connection
  if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $query = "the query here";

  $result = mysqli_query($con,$query);

  $rows = array();
  while($r = mysqli_fetch_array($result)) {
    $rows[] = $r;
  }
  echo json_encode($rows);

  mysqli_close($con);
?>

Difference between single and double quotes in Bash

If you're referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.

For example, this

#!/bin/sh
MYVAR=sometext
echo "double quotes gives you $MYVAR"
echo 'single quotes gives you $MYVAR'

will give this:

double quotes gives you sometext
single quotes gives you $MYVAR

LINQ: Distinct values

// First Get DataTable as dt
// DataRowComparer Compare columns numbers in each row & data in each row

IEnumerable<DataRow> Distinct = dt.AsEnumerable().Distinct(DataRowComparer.Default);

foreach (DataRow row in Distinct)
{
    Console.WriteLine("{0,-15} {1,-15}",
        row.Field<int>(0),
        row.Field<string>(1)); 
}

How to remove a row from JTable?

The correct way to apply a filter to a JTable is through the RowFilter interface added to a TableRowSorter. Using this interface, the view of a model can be changed without changing the underlying model. This strategy preserves the Model-View-Controller paradigm, whereas removing the rows you wish hidden from the model itself breaks the paradigm by confusing your separation of concerns.

How merge two objects array in angularjs?

This works for me :

$scope.array1 = $scope.array1.concat(array2)

In your case it would be :

$scope.actions.data = $scope.actions.data.concat(data)

Ternary operation in CoffeeScript

CoffeeScript has no ternary operator. That's what the docs say.

You can still use a syntax like

a = true then 5 else 10

It's way much clearer.

How to force a html5 form validation without submitting it via jQuery

To check whether a certain field is valid, use:

$('#myField')[0].checkValidity(); // returns true/false

To check if the form is valid, use:

$('#myForm')[0].checkValidity(); // returns true/false

If you want to display the native error messages that some browsers have (such as Chrome), unfortunately the only way to do that is by submitting the form, like this:

var $myForm = $('#myForm');

if(! $myForm[0].checkValidity()) {
  // If the form is invalid, submit it. The form won't actually submit;
  // this will just cause the browser to display the native HTML5 error messages.
  $myForm.find(':submit').click();
}

Hope this helps. Keep in mind that HTML5 validation is not supported in all browsers.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

Best way to integrate Python and JavaScript?

You could also use XPCOM, say in XUL based apps like Firefox, Thunderbird or Komodo.

How to prevent rm from reporting that a file was not found?

I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.

jQuery click event not working in mobile browsers

I know this is a resolved old topic, but I just answered a similar question, and though my answer could help someone else as it covers other solution options:

Click events work a little differently on touch enabled devices. There is no mouse, so technically there is no click. According to this article - http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html - due to memory limitations, click events are only emulated and dispatched from anchor and input elements. Any other element could use touch events, or have click events manually initialized by adding a handler to the raw html element, for example, to force click events on list items:

$('li').each(function(){
    this.onclick = function() {}
});

Now click will be triggered by li, therefore can be listened by jQuery.


On your case, you could just change the listener to the anchor element as very well put by @mason81, or use a touch event on the li:

$('.menu').on('touchstart', '.publications', function(){
    $('#filter_wrapper').show();
});

Here is a fiddle with a few experiments - http://jsbin.com/ukalah/9/edit

Change Volley timeout duration

req.setRetryPolicy(new DefaultRetryPolicy(
    MY_SOCKET_TIMEOUT_MS, 
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

You can set MY_SOCKET_TIMEOUT_MS as 100. Whatever you want to set this to is in milliseconds. DEFAULT_MAX_RETRIES can be 0 default is 1.

How to resize images proportionally / keeping the aspect ratio?

This issue can be solved by CSS.

.image{
 max-width:*px;
}

Moment.js - How to convert date string into date?

If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:

var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method

var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

How to change the default docker registry from docker.io to my private registry?

if you are using the fedora distro, you can change the file

/etc/containers/registries.conf

Adding domain docker.io

Force the origin to start at 0

xlim and ylim don't cut it here. You need to use expand_limits, scale_x_continuous, and scale_y_continuous. Try:

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for

enter image description here

p + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))

enter image description here

You may need to adjust things a little to make sure points are not getting cut off (see, for example, the point at x = 5 and y = 5.

Byte[] to InputStream or OutputStream

we can convert byte[] array into input stream by using ByteArrayInputStream

String str = "Welcome to awesome Java World";
    byte[] content = str.getBytes();
    int size = content.length;
    InputStream is = null;
    byte[] b = new byte[size];
    is = new ByteArrayInputStream(content);

For full example please check here http://www.onlinecodegeek.com/2015/09/how-to-convert-byte-into-inputstream.html

PHP String to Float

Use this function to cast a float value from any kind of text style:

function parseFloat($value) {
    return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,3}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}

This solution is not dependant on any locale settings. Thus for user input users can type float values in any way they like. This is really helpful e.g. when you have a project wich is in english only but people all over the world are using it and might not have in mind that the project wants a dot instead of a comma for float values. You could throw javascript in the mix and fetch the browsers default settings but still many people set these values to english but still typing 1,25 instead of 1.25 (especially but not limited to the translation industry, research and IT)

PHP 5.4 Call-time pass-by-reference - Easy fix available?

PHP and references are somewhat unintuitive. If used appropriately references in the right places can provide large performance improvements or avoid very ugly workarounds and unusual code.

The following will produce an error:

 function f(&$v){$v = true;}
 f(&$v);

 function f($v){$v = true;}
 f(&$v);

None of these have to fail as they could follow the rules below but have no doubt been removed or disabled to prevent a lot of legacy confusion.

If they did work, both involve a redundant conversion to reference and the second also involves a redundant conversion back to a scoped contained variable.

The second one used to be possible allowing a reference to be passed to code that wasn't intended to work with references. This is extremely ugly for maintainability.

This will do nothing:

 function f($v){$v = true;}
 $r = &$v;
 f($r);

More specifically, it turns the reference back into a normal variable as you have not asked for a reference.

This will work:

 function f(&$v){$v = true;}
 f($v);

This sees that you are passing a non-reference but want a reference so turns it into a reference.

What this means is that you can't pass a reference to a function where a reference is not explicitly asked for making it one of the few areas where PHP is strict on passing types or in this case more of a meta type.

If you need more dynamic behaviour this will work:

 function f(&$v){$v = true;}
 $v = array(false,false,false);
 $r = &$v[1];
 f($r);

Here it sees that you want a reference and already have a reference so leaves it alone. It may also chain the reference but I doubt this.

Use bash to find first folder name that contains a string

You can use the -quit option of find:

find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit

input type="submit" Vs button tag are they interchangeable?

If you are talking about <input type=button>, it won't automatically submit the form

if you are talking about the <button> tag, that's newer and doesn't automatically submit in all browsers.

Bottom line, if you want the form to submit on click in all browsers, use <input type="submit">

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

How to change option menu icon in the action bar?

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
            android:id="@+id/logout"
            android:icon="@drawable/logout"
            android:title="Log Out"
            app:showAsAction="always"
        />
</menu>

This did the trick for me!

How to add "on delete cascade" constraints?

Usage:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

Function:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.

angularjs to output plain text instead of html

You can use ng-bind-html, don't forget to inject $sanitize service into your module Hope it helps

Set the value of an input field

This part you use in html

<input id="latitude" type="text" name="latitude"></p>

This is javaScript:

<script>
document.getElementById("latitude").value=25;
</script>

Internet Explorer cache location

If you want to find the folder in a platform independent way, you should query the registry key:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache

Adjust table column width to content size

maybe problem with margin?

width:auto;
padding: 0px;
margin: 0px

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

In CentOS 6 and Solr 4.4.0

I had to comp some lib files to get this error addressed

cp ~/solr-4.4.0/example/lib/ext/* /usr/share/tomcat6/lib/

C# how to convert File.ReadLines into string array?

File.ReadLines() returns an object of type System.Collections.Generic.IEnumerable<String>
File.ReadAllLines() returns an array of strings.

If you want to use an array of strings you need to call the correct function.

You could use Jim solution, just use ReadAllLines() or you could change your return type.

This would also work:

System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");

You can use any generic collection which implements IEnumerable. IList for an example.

How do you make sure email you send programmatically is not automatically marked as spam?

The intend of most of the programmatically generated emails is generally transactional, triggered or alert n nature- which means these are important emails which should never land into spam.

Having said that there are multiple parameters which are been considered before flagging an email as spam. While Quality of email list is the most important parameter to be considered, but I am skipping that here from the discussion because here we are talking about important emails which are sent to either ourself or to known email addresses.

Apart from list quality, the other 3 important parameters are;

  1. Sender Reputation
  2. Compliance with Email Standards and Authentication (SPF, DKIM, DMARC, rDNS)
  3. Email content

Sender Reputation = Reputation of Sending IP address + Reputation of Return Path/Envelope domain + Reputation of From Domain.

There is no straight answer to what is your Sender Reputation. This is because there are multiple authorities like SenderScore, Reputation Authority and so on who maintains the reputation score for your domain. Apart from that ISPs like Gmail, Yahoo, Outlook also maintains the reputation of each domain at their end.

But, you can use free tools like GradeMyEmail to get a 360-degree view of your reputation and potential problems with your email settings or any other compliance-related issue too.

Sometimes, if you're using a new domain for sending an email, then those are also found to land in spam. You should be checking whether your domain is listed on any of the global blocklists or not. Again GradeMyEmail and MultiRBL are useful tools to identify the list of blocklists.

Once you're pretty sure with the sender reputation score, you should check whether your email sending domain complies with all email authentications and standards.

  1. SPF
  2. DKIM
  3. DMARC
  4. Reverse DNS

For this, you can again use GradeMyEmail or MXToolbox to know the potential problems with your authentication.

Your SPF, DKIM and DMARC should always PASS to ensure, your emails are complying with the standard email authentications. Here's an example of how these authentications should look like in Gmail: Email Authentication

Similarly, you can use tools like Mail-Tester which scans the complete email content and tells the potential keywords which can trigger spam filters.

How to copy an object in Objective-C

Apple documentation says

A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.

to add to the existing answer

@interface YourClass : NSObject <NSCopying> 
{
   SomeOtherObject *obj;
}

// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
  YourClass *another = [super copyWithZone:zone];
  another.obj = [obj copyWithZone: zone];

  return another;
}

Setting mime type for excel document

Waking up an old thread here I see, but I felt the urge to add the "new" .xlsx format.

According to http://filext.com/file-extension/XLSX the extension for .xlsx is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. It might be a good idea to include it when checking for mime types!

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

Regular expression for URL validation (in JavaScript)

Try this it works for me:

 /^(http[s]?:\/\/){0,1}(w{3,3}\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/;

In Angular, how to redirect with $location.path as $http.post success callback

I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.

    $http({
        url:'/login/user',
        method : 'POST',
        headers: {
            'Content-Type': 'application/json'
          },
        data: userData
    }).success(function(loginDetails){
        $scope.updLoginDetails = loginDetails;
        if($scope.updLoginDetails.successful == true)
            {
                loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
                loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
                window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
                $window.location='/login/homepage';
            }
        else
        alert('No access available.');

    }).error(function(err,status){
        alert('No access available.');      
    });

And it worked for me.

What is the --save option for npm install?

according to NPM Doc

enter image description here

So it seems that by running npm install package_name, the package dependency should be automatically added to package.json right?

Show just the current branch in Git

You may be interested in the output of

git symbolic-ref HEAD

In particular, depending on your needs and layout you may wish to do

basename $(git symbolic-ref HEAD)

or

git symbolic-ref HEAD | cut -d/ -f3-

and then again there is the .git/HEAD file which may also be of interest for you.

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

For..In loops in JavaScript - key value pairs

yes, you can have associative arrays also in javascript:

var obj = 
{
    name:'some name',
    otherProperty:'prop value',
    date: new Date()
};
for(i in obj)
{
    var propVal = obj[i]; // i is the key, and obj[i] is the value ...
}

Uncaught TypeError: Cannot read property 'appendChild' of null

Had the same problem when Load external without cache using Javascript

Load external <script> without cache using Javascript

Had a good solution for cache problem here:

https://www.c-sharpcorner.com/article/how-to-force-the-browser-to-reload-cached-js-css-files-to-reflect-latest-chan/

But this happend: Uncaught TypeError: Cannot read property 'appendChild' of null.

Here is good explanation: https://stackoverflow.com/a/58824439/14491024

As it said your script tag is in the head, the JavaScript is loaded before your HTML.

Error

In Visual Studio by C# this problem is solved like this by adding Guid:

Guid

Here is how it looks in the View page source:

OK

std::string to float or double

std::string num = "0.6";
double temp = ::atof(num.c_str());

Does it for me, it is a valid C++ syntax to convert a string to a double.

You can do it with the stringstream or boost::lexical_cast but those come with a performance penalty.


Ahaha you have a Qt project ...

QString winOpacity("0.6");
double temp = winOpacity.toDouble();

Extra note:
If the input data is a const char*, QByteArray::toDouble will be faster.

How to pass multiple parameters in json format to a web service using jquery?

I think the best way is:

data: "{'Ids':['2','2']}"

To read this values Ids[0], Ids[1].

Merge/flatten an array of arrays

To flatten a two-dimensional array in one line:

[[1, 2], [3, 4, 5]].reduce(Function.prototype.apply.bind(Array.prototype.concat))
// => [ 1, 2, 3, 4, 5 ]

Key value pairs using JSON

JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.

Since Javascripts objects consists of key/value pairs its very easy to use and access JSON that way.

So if we have an object:

var myObj = {
    foo:   'bar',
    base:  'ball',
    deep:  {
       java:  'script'
    }
};

We can convert that into a string by calling window.JSON.stringify(myObj); with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}".

The other way around, we would call window.JSON.parse("a json string like the above");.

JSON.parse() returns a javascript object/array on success.

alert(myObj.deep.java);  // 'script'

window.JSON is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.

android: stretch image in imageview to fit screen

if you use android:scaleType="fitXY" then you must specify

android:layout_width="75dp" and android:layout_height="75dp"

if use wrap_content it will not stretch to what you need

<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="@+id/listItemNoteImage"
android:src="@drawable/MyImage"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="12dp"
android:scaleType="fitXY"/>

React img tag issue with url and class

Remember that your img is not really a DOM element but a javascript expression.

  1. This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions

  2. In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components

    /** @jsx React.DOM */
    
    var Hello = React.createClass({
        render: function() {
            return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
        }
    });
    
    React.renderComponent(<Hello name="World" />, document.body);
    

Creating NSData from NSString in Swift

Swift 4.2

let data = yourString.data(using: .utf8, allowLossyConversion: true)

How to truncate float values?

Most answers are way too complicated in my opinion, how about this?

digits = 2  # Specify how many digits you want

fnum = '122.485221'
truncated_float = float(fnum[:fnum.find('.') + digits + 1])

>>> 122.48

Simply scanning for the index of '.' and truncate as desired (no rounding). Convert string to float as final step.

Or in your case if you get a float as input and want a string as output:

fnum = str(122.485221)  # convert float to string first
truncated_float = fnum[:fnum.find('.') + digits + 1]  # string output

How to add target="_blank" to JavaScript window.location?

Just use in your if (key=="smk")

if (key=="smk") { window.open('http://www.smkproduction.eu5.org','_blank'); }

Disable and later enable all table indexes in Oracle

combining 3 answers together: (because a select statement does not execute the DDL)

set pagesize 0

alter session set skip_unusable_indexes = true;
spool c:\temp\disable_indexes.sql
select 'alter index ' || u.index_name || ' unusable;' from user_indexes u;
spool off
@c:\temp\disable_indexes.sql

Do import...

select 'alter index ' || u.index_name || 
' rebuild online;' from user_indexes u;

Note this assumes that the import is going to happen in the same (sqlplus) session.
If you are calling "imp" it will run in a separate session so you would need to use "ALTER SYSTEM" instead of "ALTER SESSION" (and remember to put the parameter back the way you found it.

Best radio-button implementation for IOS

Try DLRadioButton, works for both Swift and ObjC. You can also use images to indicate selection status or customize your own style.

Check it out at GitHub.

radio button for iOS

**Update: added the option for putting selection indicator on the right side.

**Update: added square button, IBDesignable, improved performance.

**Update: added multiple selection support.

How can I get Git to follow symlinks?

Use hard links instead. This differs from a soft (symbolic) link. All programs, including git will treat the file as a regular file. Note that the contents can be modified by changing either the source or the destination.

On macOS (before 10.13 High Sierra)

If you already have git and Xcode installed, install hardlink. It's a microscopic tool to create hard links.

To create the hard link, simply:

hln source destination

macOS High Sierra update

Does Apple File System support directory hard links?

Directory hard links are not supported by Apple File System. All directory hard links are converted to symbolic links or aliases when you convert from HFS+ to APFS volume formats on macOS.

From APFS FAQ on developer.apple.com

Follow https://github.com/selkhateeb/hardlink/issues/31 for future alternatives.

On Linux and other Unix flavors

The ln command can make hard links:

ln source destination

On Windows (Vista, 7, 8, …)

Use mklink to create a junction on Windows:

mklink /j "source" "destination"

Redirecting a page using Javascript, like PHP's Header->Location

You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)

You can use window.location to change your current page.

$('.entry a:first').click(function() {
    window.location = "http://google.ca";
});

Why do people write #!/usr/bin/env python on the first line of a Python script?

If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH. The alternative would be to hardcode something like #!/usr/bin/python; that's ok, but less flexible.

In Unix, an executable file that's meant to be interpreted can indicate what interpreter to use by having a #! at the start of the first line, followed by the interpreter (and any flags it may need).

If you're talking about other platforms, of course, this rule does not apply (but that "shebang line" does no harm, and will help if you ever copy that script to a platform with a Unix base, such as Linux, Mac, etc).

How to set up gradle and android studio to do release build?

  1. open the Build Variants pane, typically found along the lower left side of the window:

Build Variants

  1. set debug to release
  2. shift+f10 run!!

then, Android Studio will execute assembleRelease task and install xx-release.apk to your device.

PHP call Class method / function

Create object for the class and call, if you want to call it from other pages.

$obj = new Functions();

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

Or inside the same class instances [ methods ], try this.

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

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

Create CA certificate

openssl genrsa -out privateKey.pem 4096
openssl req -new -x509 -nodes -days 3600 -key privateKey.pem -out caKey.pem

How to programmatically send SMS on the iPhone?

You can present MFMessageComposeViewController, which can send SMS, but with user prompt(he taps send button). No way to do that without user permission. On iOS 11, you can make extension, that can be like filter for incoming messages , telling iOS either its spam or not. Nothing more with SMS cannot be done

How to pass data to view in Laravel?

It's probably worth mentioning that as of Laravel 5, passing data to the view is now done like this:

return view("blog", ["posts"=>$posts]);

Or:

return view("blog", compact("posts"));

Documentation is available here.

Python Pandas : pivot table with aggfunc = count unique distinct

Since at least version 0.16 of pandas, it does not take the parameter "rows"

As of 0.23, the solution would be:

df2.pivot_table(values='X', index='Y', columns='Z', aggfunc=pd.Series.nunique)

which returns:

Z    Z1   Z2   Z3
Y                
Y1  1.0  1.0  NaN
Y2  NaN  NaN  1.0

How to create query parameters in Javascript?

Just like to revisit this almost 10 year old question. In this era of off-the-shelf programming, your best bet is to set your project up using a dependency manager (npm). There is an entire cottage industry of libraries out there that encode query strings and take care of all the edge cases. This is one of the more popular ones -

https://www.npmjs.com/package/query-string

Example of SOAP request authenticated with WS-UsernameToken

Check this one (Password should be password):

<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-6138db82-5a4c-4bf7-915f-af7a10d9ae96">
  <wsse:Username>user</wsse:Username>
  <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">CBb7a2itQDgxVkqYnFtggUxtuqk=</wsse:Password>
  <wsse:Nonce>5ABcqPZWb6ImI2E6tob8MQ==</wsse:Nonce>
  <wsu:Created>2010-06-08T07:26:50Z</wsu:Created>
</wsse:UsernameToken>

How to detect orientation change in layout in Android?

Use the onConfigurationChanged method of Activity. See the following code:

@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

NOTE: with Android 3.2 (API level 13) or higher, the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher, you must declare android:configChanges="orientation|screenSize" for API level 13 or higher.

Hope this will help you... :)

How to get the last N records in mongodb?

Sorting, skipping and so on can be pretty slow depending on the size of your collection.

A better performance would be achieved if you have your collection indexed by some criteria; and then you could use min() cursor:

First, index your collection with db.collectionName.setIndex( yourIndex ) You can use ascending or descending order, which is cool, because you want always the "N last items"... so if you index by descending order it is the same as getting the "first N items".

Then you find the first item of your collection and use its index field values as the min criteria in a search like:

db.collectionName.find().min(minCriteria).hint(yourIndex).limit(N)

Here's the reference for min() cursor: https://docs.mongodb.com/manual/reference/method/cursor.min/

How to change the text color of first select option

Here is a way so that when you select an option, it turns black. When you change it back to the placeholder, it turns back into the placeholder color (in this case red).

http://jsfiddle.net/wFP44/166/

It requires the options to have values.

_x000D_
_x000D_
$('select').on('change', function() {_x000D_
  if ($(this).val()) {_x000D_
return $(this).css('color', 'black');_x000D_
  } else {_x000D_
return $(this).css('color', 'red');_x000D_
  }_x000D_
});
_x000D_
select{_x000D_
  color: red;_x000D_
}_x000D_
select option { color: black; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value="">Pick one...</option>_x000D_
<option value="test1">Test 1</option>_x000D_
<option value="test2">Test 2</option>_x000D_
<option value="test3">Test 3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Getting 400 bad request error in Jquery Ajax POST

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

How to declare global variables in Android?

Like there was discussed above OS could kill the APPLICATION without any notification (there is no onDestroy event) so there is no way to save these global variables.

SharedPreferences could be a solution EXCEPT you have COMPLEX STRUCTURED variables (in my case I had integer array to store the IDs that the user has already handled). The problem with the SharedPreferences is that it is hard to store and retrieve these structures each time the values needed.

In my case I had a background SERVICE so I could move this variables to there and because the service has onDestroy event, I could save those values easily.

Return JSON for ResponseEntity<String>

public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
    JSONObject resp = new JSONObject();
    resp.put("status", 0);
    resp.put("id", id);

    return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}

How to replace all spaces in a string

VERY EASY:

just use this to replace all white spaces with -:

myString.replace(/ /g,"-")