Programs & Examples On #Designmode

Adding click event handler to iframe

You can use closures to pass parameters:

iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);

However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):

document.getElementById("myFrame").contentDocument.addEventListener(...);

Javascript validation: Block special characters

It would help you... assume you have a form with "formname" form and a text box with "txt" name. then you can use following code to allow only aphanumeric values

var checkString = document.formname.txt.value;
if (checkString != "") {
    if ( /[^A-Za-z\d]/.test(checkString)) {
        alert("Please enter only letter and numeric characters");
        document.formname.txt.focus();
        return (false);
    }
}

How can I change the size of a Bootstrap checkbox?

It is possible to implement custom bootstrap checkbox for the most popular browsers nowadays.

You can check my Bootstrap-Checkbox project in GitHub, which contains simple .less file. There is a good article in MDN describing some techniques, where the two major are:

  1. Label redirects a click event.

    Label can redirect a click event to its target if it has the for attribute like in <label for="target_id">Text</label> <input id="target_id" type="checkbox" />, or if it contains input as in Bootstrap case: <label><input type="checkbox" />Text</label>.

    It means that it is possible to place a label in one corner of the browser, click on it, and then the label will redirect click event to the checkbox located in other corner producing check/uncheck action for the checkbox.

    We can hide original checkbox visually, but make it is still working and taking click event from the label. In the label itself we can emulate checkbox with a tag or pseudo-element :before :after.

  2. General non supported tag for old browsers

    Some old browsers does not support several CSS features like selecting siblings p+p or specific search input[type=checkbox]. According to the MDN article browsers that support these features also support :root CSS selector, while others not. The :root selector just selects the root element of a document, which is html in a HTML page. Thus it is possible to use :root for a fallback to old browsers and original checkboxes.

    Final code snippet:

_x000D_
_x000D_
:root {_x000D_
  /* larger checkbox */_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox] {_x000D_
  /* hide original check box */_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
  /* find the nearest span with checkbox-placeholder class and draw custom checkbox */_x000D_
  /* draw checkmark before the span placeholder when original hidden input is checked */_x000D_
  /* disabled checkbox style */_x000D_
  /* disabled and checked checkbox style */_x000D_
  /* when the checkbox is focused with tab key show dots arround */_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox] + span.checkbox-placeholder {_x000D_
  width: 14px;_x000D_
  height: 14px;_x000D_
  border: 1px solid;_x000D_
  border-radius: 3px;_x000D_
  /*checkbox border color*/_x000D_
  border-color: #737373;_x000D_
  display: inline-block;_x000D_
  cursor: pointer;_x000D_
  margin: 0 7px 0 -20px;_x000D_
  vertical-align: middle;_x000D_
  text-align: center;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked + span.checkbox-placeholder {_x000D_
  background: #0ccce4;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked + span.checkbox-placeholder:before {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  vertical-align: text-top;_x000D_
  width: 5px;_x000D_
  height: 9px;_x000D_
  /*checkmark arrow color*/_x000D_
  border: solid white;_x000D_
  border-width: 0 2px 2px 0;_x000D_
  /*can be done with post css autoprefixer*/_x000D_
  -webkit-transform: rotate(45deg);_x000D_
  -moz-transform: rotate(45deg);_x000D_
  -ms-transform: rotate(45deg);_x000D_
  -o-transform: rotate(45deg);_x000D_
  transform: rotate(45deg);_x000D_
  content: "";_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:disabled + span.checkbox-placeholder {_x000D_
  background: #ececec;_x000D_
  border-color: #c3c2c2;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked:disabled + span.checkbox-placeholder {_x000D_
  background: #d6d6d6;_x000D_
  border-color: #bdbdbd;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:focus:not(:hover) + span.checkbox-placeholder {_x000D_
  outline: 1px dotted black;_x000D_
}_x000D_
:root label.checkbox-bootstrap.checkbox-lg input[type=checkbox] + span.checkbox-placeholder {_x000D_
  width: 26px;_x000D_
  height: 26px;_x000D_
  border: 2px solid;_x000D_
  border-radius: 5px;_x000D_
  /*checkbox border color*/_x000D_
  border-color: #737373;_x000D_
}_x000D_
:root label.checkbox-bootstrap.checkbox-lg input[type=checkbox]:checked + span.checkbox-placeholder:before {_x000D_
  width: 9px;_x000D_
  height: 15px;_x000D_
  /*checkmark arrow color*/_x000D_
  border: solid white;_x000D_
  border-width: 0 3px 3px 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<p>_x000D_
 Original checkboxes:_x000D_
</p>_x000D_
<div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox">             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox_x000D_
      </label>_x000D_
 </div>_x000D_
 <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox" disabled>             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox disabled_x000D_
      </label>_x000D_
 </div>_x000D_
 <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox" checked>             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox checked_x000D_
      </label>_x000D_
 </div>_x000D_
  <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox" checked disabled>             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox checked and disabled_x000D_
      </label>_x000D_
 </div>_x000D_
 <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap checkbox-lg">                           _x000D_
          <input type="checkbox">             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Large checkbox unchecked_x000D_
      </label>_x000D_
 </div>_x000D_
  <br/>_x000D_
<p>_x000D_
 Inline checkboxes:_x000D_
</p>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
  <input type="checkbox">_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Inline _x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
  <input type="checkbox" disabled>_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Inline disabled_x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
  <input type="checkbox" checked disabled>_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Inline checked and disabled_x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap checkbox-lg">_x000D_
  <input type="checkbox" checked>_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Large inline checked_x000D_
</label>
_x000D_
_x000D_
_x000D_

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

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

Can I use complex HTML with Twitter Bootstrap's Tooltip?

Just as normal, using data-original-title:

Html:

<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>

Javascript:

$("[rel=tooltip]").tooltip({html:true});

The html parameter specifies how the tooltip text should be turned into DOM elements. By default Html code is escaped in tooltips to prevent XSS attacks. Say you display a username on your site and you show a small bio in a tooltip. If the html code isn't escaped and the user can edit the bio themselves they could inject malicious code.

cannot import name patterns

Pattern module in not available from django 1.8. So you need to remove pattern from your import and do something similar to the following:

from django.conf.urls import include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = [                 
    # here we are not using pattern module like in previous django versions
    url(r'^admin/', include(admin.site.urls)),
]

How to check Grants Permissions at Run-Time?

Nice !!

I just found my need we can check if the permission is granted by :

checkSelfPermission(Manifest.permission.READ_CONTACTS)

Request permissions if necessary

if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant

        return;
    }

Handle the permissions request response

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! do the
                // calendar task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'switch' lines to check for other
        // permissions this app might request
    }
}

How to remove the first Item from a list?

>>> x = [0, 1, 2, 3, 4]
>>> x.pop(0)
0

More on this here.

?: operator (the 'Elvis operator') in PHP

See the docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

How to use both onclick and target="_blank"

you can use

        <p><a href="/link/to/url" target="_blank"><button id="btn_id">Present Name </button></a></p>

How to find NSDocumentDirectory in Swift?

Apparently, the compiler thinks NSSearchPathDirectory:0 is an array, and of course it expects the type NSSearchPathDirectory instead. Certainly not a helpful error message.

But as to the reasons:

First, you are confusing the argument names and types. Take a look at the function definition:

func NSSearchPathForDirectoriesInDomains(
    directory: NSSearchPathDirectory,
    domainMask: NSSearchPathDomainMask,
    expandTilde: Bool) -> AnyObject[]!
  • directory and domainMask are the names, you are using the types, but you should leave them out for functions anyway. They are used primarily in methods.
  • Also, Swift is strongly typed, so you shouldn't just use 0. Use the enum's value instead.
  • And finally, it returns an array, not just a single path.

So that leaves us with (updated for Swift 2.0):

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

and for Swift 3:

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

Creating a directory in /sdcard fails

I had same issue after I updated my Android phone to 6.0 (API level 23). The following solution works on me. Hopefully it helps you as well.

Please check your android version. If it is >= 6.0 (API level 23), you need to not only include

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

in your AndroidManifest.xml, but also request permission before calling mkdir(). Code snopshot.

public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
public int mkFolder(String folderName){ // make a folder under Environment.DIRECTORY_DCIM
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)){
        Log.d("myAppName", "Error: external storage is unavailable");
        return 0;
    }
    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        Log.d("myAppName", "Error: external storage is read only.");
        return 0;
    }
    Log.d("myAppName", "External storage is not read only or unavailable");

    if (ContextCompat.checkSelfPermission(this, // request permission when it is not granted. 
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        Log.d("myAppName", "permission:WRITE_EXTERNAL_STORAGE: NOT granted!");
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
    File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),folderName);
    int result = 0;
    if (folder.exists()) {
        Log.d("myAppName","folder exist:"+folder.toString());
        result = 2; // folder exist
    }else{
        try {
            if (folder.mkdir()) {
                Log.d("myAppName", "folder created:" + folder.toString());
                result = 1; // folder created
            } else {
                Log.d("myAppName", "creat folder fails:" + folder.toString());
                result = 0; // creat folder fails
            }
        }catch (Exception ecp){
            ecp.printStackTrace();
        }
    }
    return result;
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

More information please read "Requesting Permissions at Run Time"

xml.LoadData - Data at the root level is invalid. Line 1, position 1

if we are using XDocument.Parse(@""). Use @ it resolves the issue.

How to always show the vertical scrollbar in a browser?

Here is a method. This will not only provide scrollbar container, but will also show the scrollbar even if content isnt enough (as per your requirement). Would also work on Iphone, and android devices as well..

<style>
    .scrollholder {
        position: relative;
        width: 310px; height: 350px;
        overflow: auto;
        z-index: 1;
    }
</style>

<script>
    function isTouchDevice() {
        try {
            document.createEvent("TouchEvent");
            return true;
        } catch (e) {
            return false;
        }
    }

    function touchScroll(id) {
        if (isTouchDevice()) { //if touch events exist...
            var el = document.getElementById(id);
            var scrollStartPos = 0;

            document.getElementById(id).addEventListener("touchstart", function (event) {
                scrollStartPos = this.scrollTop + event.touches[0].pageY;
                event.preventDefault();
            }, false);

            document.getElementById(id).addEventListener("touchmove", function (event) {
                this.scrollTop = scrollStartPos - event.touches[0].pageY;
                event.preventDefault();
            }, false);
        }
    }
</script>

<body onload="touchScroll('scrollMe')">

    <!-- title -->
    <!-- <div class="title" onselectstart="return false">Alarms</div> -->
    <div class="scrollholder" id="scrollMe">

</div>
</body>

Scroll to the top of the page using JavaScript?

function scrolltop() {

    var offset = 220;
    var duration = 500;

    jQuery(window).scroll(function() {
        if (jQuery(this).scrollTop() > offset) {
            jQuery('#back-to-top').fadeIn(duration);
        } else {
            jQuery('#back-to-top').fadeOut(duration);
        }
    });

    jQuery('#back-to-top').click(function(event) {
        event.preventDefault();
        jQuery('html, body').animate({scrollTop: 0}, duration);
        return false;
    });
}

Controlling execution order of unit tests in Visual Studio

I'll not address the order of tests, sorry. Others already did it. Also, if you know about "ordered tests" - well, this is MS VS's response to the problem. I know that those ordered-tests are no fun. But they thought it will be "it" and there's really nothing more in MSTest about that.

I write about one of your assumptions:

as there is no way to tear down the static class.

Unless your static class represents some process-wide external state external to your code (like ie. the state of an unmanaged native DLL library thats P/Invoked by the rest of your code), your assumption that there is no way is not true.

If your static class refers to this, then sorry, you are perfectly right, the rest of this anwer is irrelevant. Still, as you didn't say that, I assume your code is "managed".

Think and check the AppDomain thingy. Rarely it is needed, but this is exactly the case when you'd probably like to use them.

You can create a new AppDomain, and instantiate the test there, and run the test method there. Static data used by managed code will isolated there and upon completion, you will be able to unload the AppDomain and all the data, statics included, will evaporate. Then, next test would initialize another appdomain, and so on.

This will work unless you have external state that you must track. AppDomains only isolate the managed memory. Any native DLL will still be load per-process and their state will be shared by all AppDomains.

Also, creating/tearing down the appdomains will, well, slow down the tests. Also, you may have problems with assembly resolution in the child appdomain, but they are solvable with reasonable amount of reusable code.

Also, you may have small problems with passing test data to - and back from - the child AppDomain. Objects passed will either have to be serializable in some way, or be MarshalByRef or etc. Talking cross-domain is almost like IPC.

However, take care here, it will be 100% managed talking. If you take some extra care and add a little work to the AppDomain setup, you will be able to even pass delegates and run them in the target domain. Then, instead of making some hairy cross-domain setup, you can wrap your tests with to something like:

void testmethod()
{
    TestAppDomainHelper.Run( () =>
    {
        // your test code
    });
}

or even

[IsolatedAppDomain]
void testmethod()
{
    // your test code
}

if your test framework supports creating such wrappers/extensions. After some initial research and work, using them is almost trivial.

Invalid shorthand property initializer

In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas "," after each property. but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

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

Most likely, you ran out of memory, so the Kernel killed your process.

Have you heard about OOM Killer?

Here's a log from a script that I developed for processing a huge set of data from CSV files:

Mar 12 18:20:38 server.com kernel: [63802.396693] Out of memory: Kill process 12216 (python3) score 915 or sacrifice child
Mar 12 18:20:38 server.com kernel: [63802.402542] Killed process 12216 (python3) total-vm:9695784kB, anon-rss:7623168kB, file-rss:4kB, shmem-rss:0kB
Mar 12 18:20:38 server.com kernel: [63803.002121] oom_reaper: reaped process 12216 (python3), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB

It was taken from /var/log/syslog.

Basically:

PID 12216 elected as a victim (due to its use of +9Gb of total-vm), so oom_killer reaped it.

Here's a article about OOM behavior.

CSS height 100% percent not working

I believe you need to make sure that all the container div tags above the 100% height div also has 100% height set on them including the body tag and html.

How to convert current date into string in java?

// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";

public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}

Taken from here

UTF-8 byte[] to String

You can use the String(byte[] bytes) constructor for that. See this link for details. EDIT You also have to consider your plateform's default charset as per the java doc:

Constructs a new String by decoding the specified array of bytes using the platform's default charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array. The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

Swift_TransportException Connection could not be established with host smtp.gmail.com

In my case, I was using Laravel 5 and I had forgotten to change the mail globals in the .env file that is located in your directory root folder (these variables override your mail configuration)

   MAIL_DRIVER=smtp
   MAIL_HOST=smtp.gmail.com
   MAIL_PORT=465
   [email protected]
   MAIL_PASSWORD=yourpassword

by default, the mailhost is:

   MAIL_HOST=mailtraper.io

I was getting the same error but that worked for me.

How can I add NSAppTransportSecurity to my info.plist file?

One bad news for developers using NSAppTransportSecurity.

UPDATE:
[Apple will require HTTPS connections for iOS apps by the end of 2016]

https://techcrunch.com/2016/06/14/apple-will-require-https-connections-for-ios-apps-by-the-end-of-2016/

android download pdf from url then open it with a pdf reader

Download source code from here (Open Pdf from url in Android Programmatically)

MainActivity.java

package com.deepshikha.openpdf;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

Thanks!

Get sum of MySQL column in PHP

$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);

$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
    $qty += $num['ColumnName'];
}
echo $qty;

jQuery - find child with a specific class

I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:

$(".bgHeaderH2").text();

Insert string at specified position

str_replace($sub_str, $insert_str.$sub_str, $org_str);

How to make HTML code inactive with comments

Just create a multi-line comment around it. When you want it back, just erase the comment tags.

For example, <!-- Stuff to comment out or make inactive -->

How to manage startActivityForResult on Android?

I will post the new "way" with androidx in a short answer (because in some case you does not need custom registry or contract). If you want more informations see : https://developer.android.com/training/basics/intents/result

Important : there is actually a bug with the backward compatibility of androidx so you have to add fragment_version in your gradle file. Otherwise you will get an exception "New result API error : Can only use lower 16 bits for requestCode".

dependencies {

    def activity_version = "1.2.0-beta01"
    // Java language implementation
    implementation "androidx.activity:activity:$activity_version"
    // Kotlin
    implementation "androidx.activity:activity-ktx:$activity_version"

    def fragment_version = "1.3.0-beta02"
    // Java language implementation
    implementation "androidx.fragment:fragment:$fragment_version"
    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}

Now you just have to add this member variable of your activity. This use a predefined registry and generic contract.

public class MyActivity extends AppCompatActivity{

   ...

    /**
     * Activity callback API.
     */
    // https://developer.android.com/training/basics/intents/result
    private ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),

            new ActivityResultCallback<ActivityResult>() {

                @Override
                public void onActivityResult(ActivityResult result) {
                    switch (result.getResultCode()) {
                        case Activity.RESULT_OK:
                            Intent intent = result.getData();
                            // Handle the Intent
                            Toast.makeText(MyActivity.this, "Activity returned ok", Toast.LENGTH_SHORT).show();
                            break;
                        case Activity.RESULT_CANCELED:
                            Toast.makeText(MyActivity.this, "Activity canceled", Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            });

Before new API you had :

btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyActivity .this, EditActivity.class);
                startActivityForResult(intent, Constants.INTENT_EDIT_REQUEST_CODE);
            }
        });

You may notice that the request code is now generated (and holded) by the google framework. Your code become.

 btn.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MyActivity .this, EditActivity.class);
                    mStartForResult.launch(intent);
                }
            });

Hope my answer will help some people !

Passing parameters to a Bash function

Another way to pass named parameters to Bash... is passing by reference. This is supported as of Bash 4.0

#!/bin/bash
function myBackupFunction(){ # directory options destination filename
local directory="$1" options="$2" destination="$3" filename="$4";
  echo "tar cz ${!options} ${!directory} | ssh root@backupserver \"cat > /mnt/${!destination}/${!filename}.tgz\"";
}

declare -A backup=([directory]=".." [options]="..." [destination]="backups" [filename]="backup" );

myBackupFunction backup[directory] backup[options] backup[destination] backup[filename];

An alternative syntax for Bash 4.3 is using a nameref.

Although the nameref is a lot more convenient in that it seamlessly dereferences, some older supported distros still ship an older version, so I won't recommend it quite yet.

Clear listview content?

Simply write

listView.setAdapter(null);

Set order of columns in pandas dataframe

You could also do something like df = df[['x', 'y', 'a', 'b']]

import pandas as pd
frame = pd.DataFrame({'one thing':[1,2,3,4],'second thing':[0.1,0.2,1,2],'other thing':['a','e','i','o']})
frame = frame[['second thing', 'other thing', 'one thing']]
print frame
   second thing other thing  one thing
0           0.1           a          1
1           0.2           e          2
2           1.0           i          3
3           2.0           o          4

Also, you can get the list of columns with:

cols = list(df.columns.values)

The output will produce something like this:

['x', 'y', 'a', 'b']

Which is then easy to rearrange manually.

how to use DEXtoJar

  1. Download Dex2jar and Extract it.
  2. Go to Download path ./d2j-dex2jar.sh /path-to-your/someApk.apk if .sh is not compilable, update the permission: chmod a+x d2j-dex2jar.sh.
  3. It will generate .jar file.
  4. Now use the jar with JD-GUI to decompile it

How to split a string, but also keep the delimiters?

I will post my working versions also(first is really similar to Markus).

public static String[] splitIncludeDelimeter(String regex, String text){
    List<String> list = new LinkedList<>();
    Matcher matcher = Pattern.compile(regex).matcher(text);

    int now, old = 0;
    while(matcher.find()){
        now = matcher.end();
        list.add(text.substring(old, now));
        old = now;
    }

    if(list.size() == 0)
        return new String[]{text};

    //adding rest of a text as last element
    String finalElement = text.substring(old);
    list.add(finalElement);

    return list.toArray(new String[list.size()]);
}

And here is second solution and its round 50% faster than first one:

public static String[] splitIncludeDelimeter2(String regex, String text){
    List<String> list = new LinkedList<>();
    Matcher matcher = Pattern.compile(regex).matcher(text);

    StringBuffer stringBuffer = new StringBuffer();
    while(matcher.find()){
        matcher.appendReplacement(stringBuffer, matcher.group());
        list.add(stringBuffer.toString());
        stringBuffer.setLength(0); //clear buffer
    }

    matcher.appendTail(stringBuffer); ///dodajemy reszte  ciagu
    list.add(stringBuffer.toString());

    return list.toArray(new String[list.size()]);
}

Comment shortcut Android Studio

Are you sure you are using / and not \ ? On Mac I have found by default:

  • Cmd + /

Comments using // notation

  • Cmd + Opt + /

Comments using /* */ notation

Secure random token in Node.js

Simple function that gets you a token that is URL safe and has base64 encoding! It's a combination of 2 answers from above.

const randomToken = () => {
    crypto.randomBytes(64).toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
}

Parse JSON from HttpURLConnection object

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

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

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

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

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

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

There is a sample of AuthMsg class:

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

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

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

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

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

Regards

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

Remove a specific string from an array of string

It is not possible in on step or you need to keep the reference to the array. If you can change the reference this can help:

      String[] n = new String[]{"google","microsoft","apple"};
      final List<String> list =  new ArrayList<String>();
      Collections.addAll(list, n); 
      list.remove("apple");
      n = list.toArray(new String[list.size()]);

I not recommend the following but if you worry about performance:

      String[] n = new String[]{"google","microsoft","apple"};
      final String[] n2 = new String[2]; 
      System.arraycopy(n, 0, n2, 0, n2.length);
      for (int i = 0, j = 0; i < n.length; i++)
      {
        if (!n[i].equals("apple"))
        {
          n2[j] = n[i];
          j++;
        }      
      }

I not recommend it because the code is a lot more difficult to read and maintain.

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

What is the difference between a deep copy and a shallow copy?

Breadth vs Depth; think in terms of a tree of references with your object as the root node.

Shallow:

Before Copy Shallow Copying Shallow Done

The variables A and B refer to different areas of memory, when B is assigned to A the two variables refer to the same area of memory. Later modifications to the contents of either are instantly reflected in the contents of other, as they share contents.

Deep:

Before Copy Deep Copying Deep Done

The variables A and B refer to different areas of memory, when B is assigned to A the values in the memory area which A points to are copied into the memory area to which B points. Later modifications to the contents of either remain unique to A or B; the contents are not shared.

How can I force component to re-render with hooks in React?

Generally, you can use any state handling approach you want to trigger an update.

With TypeScript

codesandbox example

useState

const forceUpdate: () => void = React.useState()[1].bind(null, {})  // see NOTE below

useReducer

const forceUpdate = React.useReducer(() => ({}), {})[1] as () => void

as custom hook

Just wrap whatever approach you prefer like this

function useForceUpdate(): () => void {
  return React.useReducer(() => ({}), {})[1] as () => void // <- paste here
}

How this works?

"To trigger an update" means to tell React engine that some value has changed and that it should rerender your component.

[, setState] from useState() requires a parameter. We get rid of it by binding a fresh object {}.
() => ({}) in useReducer is a dummy reducer that returns a fresh object each time an action is dispatched.
{} (fresh object) is required so that it triggers an update by changing a reference in the state.

PS: useState just wraps useReducer internally. source

NOTE: Using .bind with useState causes a change in function reference between renders. It is possible to wrap it inside useCallback as already explained here, but then it wouldn't be a sexy one-liner™. The Reducer version already keeps reference equality between renders. This is important if you want to pass the forceUpdate function in props.

plain JS

const forceUpdate = React.useState()[1].bind(null, {})  // see NOTE above
const forceUpdate = React.useReducer(() => ({}))[1]

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.

The fix was to simply to add the missing brackets: numpy.concatenate( ( A,B ) ), which are required because the arrays to be concatenated constitute to a single argument

Oracle Insert via Select from multiple tables where one table may not have a row

insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
   ts.tax_status_id, 
   ( select r.recipient_id
     from recipient r
     where r.recipient_code = ?
   )
from tax_status ts
where ts.tax_status_code = ?

Browse for a directory in C#

You could just use the FolderBrowserDialog class from the System.Windows.Forms namespace.

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I had the same problem today. To fix I downgraded firefox version 51 to 47 and it's working.

Note: I'm using a Linux Ubuntu Mate, in a Virtual Box, with host being another Ubuntu Mate. All OS are 64 bits and firefox also.

High-precision clock in Python

You can also use time.clock() It counts the time used by the process on Unix and time since the first call to it on Windows. It's more precise than time.time().

It's the usually used function to measure performance.

Just call

import time
t_ = time.clock()
#Your code here
print 'Time in function', time.clock() - t_

EDITED: Ups, I miss the question as you want to know exactly the time, not the time spent...

Bootstrap change carousel height

like Answers above, if you do bootstrap 4 just add few line of css to .carousel , carousel-inner ,carousel-item and img as follows

.carousel .carousel-inner{
height:500px
}
.carousel-inner .carousel-item img{
min-height:200px;
//prevent it from stretch in screen size < than 768px
object-fit:cover
}

@media(max-width:768px){
.carousel .carousel-inner{
//prevent it from adding a white space between carousel and container elements
height:auto
 }
}

How can I check the current status of the GPS receiver?

Setting time interval to check for fix is not a good choice.. i noticed that onLocationChanged is not called if you are not moving.. what is understandable since location is not changing :)

Better way would be for example:

  • check interval to last location received (in gpsStatusChanged)
  • if that interval is more than 15s set variable: long_interval = true
  • remove the location listener and add it again, usually then you get updated position if location really is available, if not - you probably lost location
  • in onLocationChanged you just set long_interval to false..

How is the java memory pool divided?

Java Heap Memory is part of memory allocated to JVM by Operating System.

Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.

enter image description here

You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:

Young , Tenured and Perm generation

PermGen has been replaced with Metaspace since Java 8 release.

Regarding your queries:

  1. Eden Space, Survivor Space, Tenured Space are part of heap memory
  2. Metaspace and Code Cache are part of non-heap memory.

Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.

Pandas groupby month and year

There are different ways to do that.

  • I created the data frame to showcase the different techniques to filter your data.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],

'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })

  • I separated months/year/day and seperated month-year as you explained.
def getMonth(s):
  return s.split("-")[1]

def getDay(s):
  return s.split("-")[0]

def getYear(s):
  return s.split("-")[2]

def getYearMonth(s):
  return s.split("-")[1]+"-"+s.split("-")[2]
  • I created new columns: year, month, day and 'yearMonth'. In your case, you need one of both. You can group using two columns 'year','month' or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x))
df['month']= df['Date'].apply(lambda x: getMonth(x))
df['day']= df['Date'].apply(lambda x: getDay(x))
df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
3  20-Jan-14   25   15   14   Jan  20    Jan-14
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • You can go through the different groups in groupby(..) items.

In this case, we are grouping by two columns:

for key,g in df.groupby(['year','month']):
    print key,g

Output:

('13', 'Jun')         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
('13', 'Aug')         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
('14', 'Jan')         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
('14', 'Feb')         Date  abc  xyz year month day YearMonth

In this case, we are grouping by one column:

for key,g in df.groupby(['YearMonth']):
    print key,g

Output:

Jun-13         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
Aug-13         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
Jan-14         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
Feb-14         Date  abc  xyz year month day YearMonth
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • In case you wanna access to specific item, you can use get_group

print df.groupby(['YearMonth']).get_group('Jun-13')

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
  • Similar to get_group. This hack would help to filter values and get the grouped values.

This also would give the same result.

print df[df['YearMonth']=='Jun-13'] 

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13

You can select list of abc or xyz values during Jun-13

print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values

Output:

[100 -20]  #abc values
[200  50]  #xyz values

You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.

for x in set(df.YearMonth): 
    print df[df['YearMonth']==x].abc.values
    print df[df['YearMonth']==x].xyz.values

I recommend also to check this answer as well.

How do I fix the indentation of an entire file in Vi?

You can create a mapping to do this for you.

This one will auto indent the whole file and still keep your cursor in the position you are:

nmap <leader>ai mzgg=G`z

How to determine if one array contains all elements of another array

If there are are no duplicate elements or you don't care about them, then you can use the Set class:

a1 = Set.new [5, 1, 6, 14, 2, 8]
a2 = Set.new [2, 6, 15]
a1.subset?(a2)
=> false

Behind the scenes this uses

all? { |o| set.include?(o) }

Help needed with Median If in Excel

Expanding on Brian Camire's Answer:

Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) with CTRL+SHIFT+ENTER will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:

=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))

Don't forget to press CTRL+SHIFT+ENTER to treat the formula as an "array formula".

curl Failed to connect to localhost port 80

Since you have a ::1 localhost line in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.

Since the web server is not listening on IPv6, the connection fails.

You could try to use the --ipv4 option to curl, which should force an IPv4 connection when both are available.

Merge two HTML table cells

use colspan for do this

 <td colspan="3">PUR mix up column</td>

How do search engines deal with AngularJS applications?

This has drastically changed.

http://searchengineland.com/bing-offers-recommendations-for-seo-friendly-ajax-suggests-html5-pushstate-152946

If you use: $locationProvider.html5Mode(true); you are set.

No more rendering pages.

Automatic HTTPS connection/redirect with node.js/express

if your node application install on IIS you can do like this in web.config

<configuration>
    <system.webServer>

        <!-- indicates that the hello.js file is a node.js application 
    to be handled by the iisnode module -->

        <handlers>
            <add name="iisnode" path="src/index.js" verb="*" modules="iisnode" />
        </handlers>

        <!-- use URL rewriting to redirect the entire branch of the URL namespace
    to hello.js node.js application; for example, the following URLs will 
    all be handled by hello.js:
    
        http://localhost/node/express/myapp/foo
        http://localhost/node/express/myapp/bar
        -->
        <rewrite>
            <rules>
                <rule name="HTTPS force" enabled="true" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
                </rule>
                <rule name="sendToNode">
                    <match url="/*" />
                    <action type="Rewrite" url="src/index.js" />
                </rule>
            </rules>
        </rewrite>

        <security>
            <requestFiltering>
                <hiddenSegments>
                    <add segment="node_modules" />
                </hiddenSegments>
            </requestFiltering>
        </security>

    </system.webServer>
</configuration>

How do I compare version numbers in Python?

I was looking for a solution which wouldn't add any new dependencies. Check out the following (Python 3) solution:

class VersionManager:

    @staticmethod
    def compare_version_tuples(
            major_a, minor_a, bugfix_a,
            major_b, minor_b, bugfix_b,
    ):

        """
        Compare two versions a and b, each consisting of 3 integers
        (compare these as tuples)

        version_a: major_a, minor_a, bugfix_a
        version_b: major_b, minor_b, bugfix_b

        :param major_a: first part of a
        :param minor_a: second part of a
        :param bugfix_a: third part of a

        :param major_b: first part of b
        :param minor_b: second part of b
        :param bugfix_b: third part of b

        :return:    1 if a  > b
                    0 if a == b
                   -1 if a  < b
        """
        tuple_a = major_a, minor_a, bugfix_a
        tuple_b = major_b, minor_b, bugfix_b
        if tuple_a > tuple_b:
            return 1
        if tuple_b > tuple_a:
            return -1
        return 0

    @staticmethod
    def compare_version_integers(
            major_a, minor_a, bugfix_a,
            major_b, minor_b, bugfix_b,
    ):
        """
        Compare two versions a and b, each consisting of 3 integers
        (compare these as integers)

        version_a: major_a, minor_a, bugfix_a
        version_b: major_b, minor_b, bugfix_b

        :param major_a: first part of a
        :param minor_a: second part of a
        :param bugfix_a: third part of a

        :param major_b: first part of b
        :param minor_b: second part of b
        :param bugfix_b: third part of b

        :return:    1 if a  > b
                    0 if a == b
                   -1 if a  < b
        """
        # --
        if major_a > major_b:
            return 1
        if major_b > major_a:
            return -1
        # --
        if minor_a > minor_b:
            return 1
        if minor_b > minor_a:
            return -1
        # --
        if bugfix_a > bugfix_b:
            return 1
        if bugfix_b > bugfix_a:
            return -1
        # --
        return 0

    @staticmethod
    def test_compare_versions():
        functions = [
            (VersionManager.compare_version_tuples, "VersionManager.compare_version_tuples"),
            (VersionManager.compare_version_integers, "VersionManager.compare_version_integers"),
        ]
        data = [
            # expected result, version a, version b
            (1, 1, 0, 0, 0, 0, 1),
            (1, 1, 5, 5, 0, 5, 5),
            (1, 1, 0, 5, 0, 0, 5),
            (1, 0, 2, 0, 0, 1, 1),
            (1, 2, 0, 0, 1, 1, 0),
            (0, 0, 0, 0, 0, 0, 0),
            (0, -1, -1, -1, -1, -1, -1),  # works even with negative version numbers :)
            (0, 2, 2, 2, 2, 2, 2),
            (-1, 5, 5, 0, 6, 5, 0),
            (-1, 5, 5, 0, 5, 9, 0),
            (-1, 5, 5, 5, 5, 5, 6),
            (-1, 2, 5, 7, 2, 5, 8),
        ]
        count = len(data)
        index = 1
        for expected_result, major_a, minor_a, bugfix_a, major_b, minor_b, bugfix_b in data:
            for function_callback, function_name in functions:
                actual_result = function_callback(
                    major_a=major_a, minor_a=minor_a, bugfix_a=bugfix_a,
                    major_b=major_b, minor_b=minor_b, bugfix_b=bugfix_b,
                )
                outcome = expected_result == actual_result
                message = "{}/{}: {}: {}: a={}.{}.{} b={}.{}.{} expected={} actual={}".format(
                    index, count,
                    "ok" if outcome is True else "fail",
                    function_name,
                    major_a, minor_a, bugfix_a,
                    major_b, minor_b, bugfix_b,
                    expected_result, actual_result
                )
                print(message)
                assert outcome is True
                index += 1
        # test passed!


if __name__ == '__main__':
    VersionManager.test_compare_versions()

EDIT: added variant with tuple comparison. Of course the variant with tuple comparison is nicer, but I was looking for the variant with integer comparison

What's the difference between JPA and Hibernate?

As you state JPA is just a specification, meaning there is no implementation. You can annotate your classes as much as you would like with JPA annotations, however without an implementation nothing will happen. Think of JPA as the guidelines that must be followed or an interface, while Hibernate's JPA implementation is code that meets the API as defined by the JPA specification and provides the under the hood functionality.

When you use Hibernate with JPA you are actually using the Hibernate JPA implementation. The benefit of this is that you can swap out Hibernate's implementation of JPA for another implementation of the JPA specification. When you use straight Hibernate you are locking into the implementation because other ORMs may use different methods/configurations and annotations, therefore you cannot just switch over to another ORM.

For a more detailed description read my blog entry.

std::cin input with spaces?

It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".

Use std::getline:

int main()
{
   std::string name, title;

   std::cout << "Enter your name: ";
   std::getline(std::cin, name);

   std::cout << "Enter your favourite movie: ";
   std::getline(std::cin, title);

   std::cout << name << "'s favourite movie is " << title;
}

Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.

Update

Your edited question bears little resemblance to the original.

You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.

Aligning label and textbox on same line (left and right)

You can do it with a table, like this:

<table width="100%">
  <tr>
    <td style="width: 50%">Left Text</td>
    <td style="width: 50%; text-align: right;">Right Text</td>
  </tr>
</table>

Or, you can do it with CSS like this:

<div style="float: left;">
    Left text
</div>
<div style="float: right;">
    Right text
</div>

How do you convert WSDLs to Java classes using Eclipse?

You need to do next in command line:

wsimport -keep -s (name of folder where you want to store generated code) urlToWsdl

for example:

wsimport -keep -s C://NewFolder https://www.blablabla.com

Unique constraint on multiple columns

This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.

  1. Under the table, right click Indexes->Click/hover New Index->Click Non-Clustered Index...

enter image description here

  1. A default Index name will be given but you may want to change it. Check the Unique checkbox and click Add... button

enter image description here

  1. Check the columns you want included

enter image description here

Click OK in each window and you're done.

UITableViewCell, show delete button on swipe

In iOS 8 and Swift 2.0 please try this,

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
   // let the controller to know that able to edit tableView's row 
   return true
}

override func tableView(tableView: UITableView, commitEdittingStyle editingStyle UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)  {
   // if you want to apply with iOS 8 or earlier version you must add this function too. (just left in blank code)
}

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?  {
   // add the action button you want to show when swiping on tableView's cell , in this case add the delete button.
   let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action , indexPath) -> Void in

   // Your delete code here.....
   .........
   .........
   })

   // You can set its properties like normal button
   deleteAction.backgroundColor = UIColor.redColor()

   return [deleteAction]
}

Time part of a DateTime Field in SQL

Note that from MS SQL 2012 onwards you can use FORMAT(value,'format')

e.g. WHERE FORMAT(YourDatetime,'HH:mm') = '17:00'

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

I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resources class and a strongly typed resource:

ProjectNamespace.Properties.Resources.file

Use the IDE's resource manager to add resources.

Select and trigger click event of a radio button in jquery

$("#radio1").attr('checked', true).trigger('click');

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

Removing the xml declaration solved it

<?xml version='1.0' encoding='utf-8'?>

Retrieving data from a POST method in ASP.NET

You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.

Changing user agent on urllib2.urlopen

Another solution in urllib2 and Python 2.7:

req = urllib2.Request('http://www.example.com/')
req.add_unredirected_header('User-Agent', 'Custom User-Agent')
urllib2.urlopen(req)

How to use a DataAdapter with stored procedure and parameter

public class SQLCon
{
  public static string cs = 
   ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
protected void Page_Load(object sender, EventArgs e)
{
    SqlDataAdapter MyDataAdapter;
    SQLCon cs = new SQLCon();
    DataSet RsUser = new DataSet();
    RsUser = new DataSet();
    using (SqlConnection MyConnection = new SqlConnection(SQLCon.cs))
       {
        MyConnection.Open();
        MyDataAdapter = new SqlDataAdapter("GetAPPID", MyConnection);
        //'Set the command type as StoredProcedure.
        MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
        RsUser = new DataSet();
        MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@organizationID", 
        SqlDbType.Int));
        MyDataAdapter.SelectCommand.Parameters["@organizationID"].Value = TxtID.Text;
        MyDataAdapter.Fill(RsUser, "GetAPPID");
       }

      if (RsUser.Tables[0].Rows.Count > 0) //data was found
      {
        Session["AppID"] = RsUser.Tables[0].Rows[0]["AppID"].ToString();
       }
     else
       {

       }    
}    

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Yes, it's possible, the syntax is curl [protocol://]<host>[:port], for example:

curl example.com:1234

If you're using Bash, you can also use pseudo-device /dev files to open a TCP connection, e.g.:

exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.

See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).

How to close <img> tag properly?

This one is valid HTML5 and it is absolutely fine without closing it. It is a so-called void element:

<img src='stackoverflow.png'>

The following are valid XHTML tags. They have to be closed. The later one is also fine in HTML 5:

<img src='stackoverflow.png'></img>
<img src='stackoverflow.png' />

How to read values from the querystring with ASP.NET Core?

in .net core if you want to access querystring in our view use it like

@Context.Request.Query["yourKey"]

if we are in location where @Context is not avilable we can inject it like

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@if (HttpContextAccessor.HttpContext.Request.Query.Keys.Contains("yourKey"))
{
      <text>do something </text>
}

also for cookies

HttpContextAccessor.HttpContext.Request.Cookies["DeniedActions"]

Why Maven uses JDK 1.6 but my java -version is 1.7

add the following to your ~/.mavenrc:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/{jdk-version}/Contents/Home

Second Solution:

echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

On Ubuntu 14.04 LTS

/usr/share# mv /opt/tomcat/apache-tomcat-7.0.56/ tomcat7

fixed the issue for me. There was a symbolic link there to /opt. Inside that opt directory there where ../../java links that would not point to /usr/share/java since the files physically were in /opt

error_reporting(E_ALL) does not produce error

That error is a parse error. The parser is throwing it while going through the code, trying to understand it. No code is being executed yet in the parsing stage. Because of that it hasn't yet executed the error_reporting line, therefore the error reporting settings aren't changed yet.

You cannot change error reporting settings (or really, do anything) in a file with syntax errors.

Border color on default input style

If I understand your question correctly this should solve it:

http://jsfiddle.net/wvk2mnsf/

HTML - create a simple input field.

<input type="text" id="giraffe" />

CSS - clear out the native outline so you can set your own and it doesn't look weird with a bluey red outline.

input:focus {
    outline: none;
}
.error-input-border {
    border: 1px solid #FF0000;
}

JS - on typing in the field set red border class declared in the CSS

document.getElementById('giraffe').oninput = function() { this.classList.add('error-input-border'); }

This has a lot of information on the latest standards too: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation

How do I get the AM/PM value from a DateTime?

If you want to add time to LongDateString Date, you can format it this way:

    DateTime date = DateTime.Now;
    string formattedDate = date.ToLongDateString(); 
    string formattedTime = date.ToShortTimeString();
    Label1.Text = "New Formatted Date: " + formattedDate + " " + formattedTime;

Output:

New Formatted Date: Monday, January 1, 1900 8:53 PM 

INNER JOIN in UPDATE sql for DB2

Here's a good example of something I just got working:

update cac c
set ga_meth_id = (
    select cim.ga_meth_id 
    from cci ci, ccim cim 
    where ci.cus_id_key_n = cim.cus_id_key_n
    and ci.cus_set_c = cim.cus_set_c
    and ci.cus_set_c = c.cus_set_c
    and ci.cps_key_n = c.cps_key_n
)
where exists (
    select 1  
    from cci ci2, ccim cim2 
    where ci2.cus_id_key_n = cim2.cus_id_key_n
    and ci2.cus_set_c = cim2.cus_set_c
    and ci2.cus_set_c = c.cus_set_c
    and ci2.cps_key_n = c.cps_key_n
)

MySQL COUNT DISTINCT

Overall

SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site

  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.

change image opacity using javascript

I'm not sure if you can do this in every browser but you can set the css property of the specified img.
Try to work with jQuery which allows you to make css changes much faster and efficiently.
in jQuery you will have the options of using .animate(),.fadeTo(),.fadeIn(),.hide("slow"),.show("slow") for example.
I mean this CSS snippet should do the work for you:

img
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}

Also check out this website where everything further is explained:
http://www.w3schools.com/css/css_image_transparency.asp

How can I disable mod_security in .htaccess file?

With some web hosts including NameCheap, it's not possible to disable ModSecurity using .htaccess. The only option is to contact tech support and ask them to alter the configuration for you.

How to find files modified in last x minutes (find -mmin does not work as expected)

this command may be help you sir

find -type f -mtime -60

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

disable viewport zooming iOS 10+ safari?

The workaround that works in Mobile Safari at this time of writing, is to have the the third argument in addEventListener be { passive: false }, so the full workaround looks like this:

document.addEventListener('touchmove', function (event) {
  if (event.scale !== 1) { event.preventDefault(); }
}, { passive: false });

You may want to check if options are supported to remain backwards compatible.

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

I recently needed a user-friendly approach and I came up with this, based on valuable insights from contributors here and elsewhere. Simply put this line at the top of your .bat script. Feedback welcome.

@pushd %~dp0 & fltmc | find "." && (powershell start '%~f0' ' %*' -verb runas 2>nul && exit /b)

Intrepretation:

  • @pushd %~dp0 ensures a consistant working directory relative to this batch file; supports UNC paths
  • fltmc a native windows command that outputs an error if run unelevated
  • | find "." makes the error prettier, and causes nothing to output when elevated
  • && ( if we successfully got an error because we're not elevated, do this...
  • powershell start invoke PowerShell and call the Start-Process cmdlet (start is an alias)
  • '%~f0' pass in the full path and name of this .bat file. Single quotes allow spaces in the path/file name
  • ' %*' pass in any and all arguments to this .bat file. Funky quoting and escape sequences probably won't work, but simple quoted strings should. The leading space is needed to prevent breaking things if no arguments are present
  • -verb runas don't just start this process...RunAs Administrator!
  • 2>nul discard PowerShell's unsightly error output if the UAC prompt is canceled/ignored.
  • && if we successfully invoked ourself with PowerShell, then...
    • NOTE: in the event we don't obtain elevation (user cancels UAC), then && allows the .bat to continue running without elevation, such that any commands that require it will fail but others will work just fine. If you want the script to simply exit instead of running unelevated, make this a single ampersand: &
  • exit /b) exits the initial .bat processing, because we don't need it anymore; we have a new elevated process currently running out .bat. Adding /b allows cmd.exe to remain open if the .bat was started from the command line...it has no effect if the .bat was double-clicked

Converting string into datetime

Remember this and you didn't need to get confused in datetime conversion again.

String to datetime object = strptime

datetime object to other formats = strftime

Jun 1 2005 1:33PM

is equals to

%b %d %Y %I:%M%p

%b Month as locale’s abbreviated name(Jun)

%d Day of the month as a zero-padded decimal number(1)

%Y Year with century as a decimal number(2015)

%I Hour (12-hour clock) as a zero-padded decimal number(01)

%M Minute as a zero-padded decimal number(33)

%p Locale’s equivalent of either AM or PM(PM)

so you need strptime i-e converting string to

>>> dates = []
>>> dates.append('Jun 1 2005  1:33PM')
>>> dates.append('Aug 28 1999 12:00AM')
>>> from datetime import datetime
>>> for d in dates:
...     date = datetime.strptime(d, '%b %d %Y %I:%M%p')
...     print type(date)
...     print date
... 

Output

<type 'datetime.datetime'>
2005-06-01 13:33:00
<type 'datetime.datetime'>
1999-08-28 00:00:00

What if you have different format of dates you can use panda or dateutil.parse

>>> import dateutil
>>> dates = []
>>> dates.append('12 1 2017')
>>> dates.append('1 1 2017')
>>> dates.append('1 12 2017')
>>> dates.append('June 1 2017 1:30:00AM')
>>> [parser.parse(x) for x in dates]

OutPut

[datetime.datetime(2017, 12, 1, 0, 0), datetime.datetime(2017, 1, 1, 0, 0), datetime.datetime(2017, 1, 12, 0, 0), datetime.datetime(2017, 6, 1, 1, 30)]

How do I create an iCal-type .ics file that can be downloaded by other users?

There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.

http://apps.marudot.com/ical/

What should I set JAVA_HOME environment variable on macOS X 10.6?

It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:

$ echo $SHELL
/bin/bash

If your default terminal is /bin/bash (Bash), then you should use @hygull method

If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:

export JAVA_HOME="$(/usr/libexec/java_home)"

Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.

This method tested working in macOS Mojave Version 10.14.6.

How can I show dots ("...") in a span with hidden overflow?

I think you are looking for text-overflow: ellipsis in combination with white-space: nowrap

See some more details here

C# Wait until condition is true

Ended up writing this today and seems to be ok. Your usage could be:

await TaskEx.WaitUntil(isExcelInteractive);

code (including the inverse operation)

public static class TaskEx
{
    /// <summary>
    /// Blocks while condition is true or timeout occurs.
    /// </summary>
    /// <param name="condition">The condition that will perpetuate the block.</param>
    /// <param name="frequency">The frequency at which the condition will be check, in milliseconds.</param>
    /// <param name="timeout">Timeout in milliseconds.</param>
    /// <exception cref="TimeoutException"></exception>
    /// <returns></returns>
    public static async Task WaitWhile(Func<bool> condition, int frequency = 25, int timeout = -1)
    {
        var waitTask = Task.Run(async () =>
        {
            while (condition()) await Task.Delay(frequency);
        });

        if(waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout)))
            throw new TimeoutException();
    }

    /// <summary>
    /// Blocks until condition is true or timeout occurs.
    /// </summary>
    /// <param name="condition">The break condition.</param>
    /// <param name="frequency">The frequency at which the condition will be checked.</param>
    /// <param name="timeout">The timeout in milliseconds.</param>
    /// <returns></returns>
    public static async Task WaitUntil(Func<bool> condition, int frequency = 25, int timeout = -1)
    {
        var waitTask = Task.Run(async () =>
        {
            while (!condition()) await Task.Delay(frequency);
        });

        if (waitTask != await Task.WhenAny(waitTask, 
                Task.Delay(timeout))) 
            throw new TimeoutException();
    }
}

Example usage: https://dotnetfiddle.net/Vy8GbV

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

Browser (webapi):

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

Cannot use a leading ../ to exit above the top directory

I know these answers are enough, but I'll show the place that's throwing an error.

If you have the structure like the below:

  • ./Src/Master.cs - (Master Form Page)
  • ./Invoice/SubFolder/InvoiceEdit.aspx - (Sub Form Page)

If you enter the sub form page, you'll get an error when you use similar like that you've used in master page: Page.ResolveClientUrl("~/Style/img/logo_small.png").

Now ResolveClientUrl is situated in the master page and trying to serve the root folder. But since you are in the subfolder, the function returns something like ../../Style/img/logo_small.png. This is the wrong way.

Because when you're up two levels, you are not in the right place; you need to go up only one level, so something like ../.

Can you test google analytics on a localhost address?

Answer for 2019

The best practice is to setup two separate properties for your development/staging, and your production servers. You do not want to pollute your Analytics data with test, and setting up filters is not pleasant if you are forced to do that.

That being said, Google Analytics now has real time tracking, and if you want to track Campaigns or Transactions, the lag is around 1 minute until the data is shown on the page, as long as you select the current day.

For example, you create Site and Site Test, and each one ha UA-XXXX-Y code.

In your application logic, where you serve the analytics JavaScript, check your environment and for production use your Site UA-XXXX-Y, and for staging/development use the Site Test one.

You can have this setup until you learn the ins and outs of GA, and then remove it, or keep it if you need to make constant changes (which you will test on development/staging first).

Source: personal experience, various articles.

Correct Way to Load Assembly, Find Class and Call Run() Method

Use an AppDomain

It is safer and more flexible to load the assembly into its own AppDomain first.

So instead of the answer given previously:

var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

I would suggest the following (adapted from this answer to a related question):

var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

Now you can unload the assembly and have different security settings.

If you want even more flexibility and power for dynamic loading and unloading of assemblies, you should look at the Managed Add-ins Framework (i.e. the System.AddIn namespace). For more information, see this article on Add-ins and Extensibility on MSDN.

Why can't I display a pound (£) symbol in HTML?

Or for other code equivalents try:

&#163;
&pound;

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

display: inline-block extra margin

A year later, stumbled across this question for a inline LI problem, but have found a great solution that may apply here.

http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

vertical-align:bottom on all my LI elements fixed my "extra margin" problem in all browsers.

C# : Converting Base Class to Child Class

You can use the as operator to perform certain types of conversions between compatible reference types or nullable types.

SkyfilterClient c = client as SkyfilterClient;
if (c != null)
{
    //do something with it
}



NetworkClient c = new SkyfilterClient() as NetworkClient; // c is not null
SkyfilterClient c2 = new NetworkClient() as SkyfilterClient; // c2 is null

TypeError: unsupported operand type(s) for /: 'str' and 'str'

By turning them into integers instead:

percent = (int(pyc) / int(tpy)) * 100;

In python 3, the input() function returns a string. Always. This is a change from Python 2; the raw_input() function was renamed to input().

Convert UNIX epoch to Date object

Go via POSIXct and you want to set a TZ there -- here you see my (Chicago) default:

R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05" 
R> 

Edit: A few years later, we can now use the anytime package:

R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R> 

Note how all this works without any format or origin arguments.

Calling virtual functions inside constructors

The reason is that C++ objects are constructed like onions, from the inside out. Base classes are constructed before derived classes. So, before a B can be made, an A must be made. When A's constructor is called, it's not a B yet, so the virtual function table still has the entry for A's copy of fn().

What are all possible pos tags of NLTK?

To save some folks some time, here is a list I extracted from a small corpus. I do not know if it is complete, but it should have most (if not all) of the help definitions from upenn_tagset...

CC: conjunction, coordinating

& 'n and both but either et for less minus neither nor or plus so
therefore times v. versus vs. whether yet

CD: numeral, cardinal

mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-
seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025
fifteen 271,124 dozen quintillion DM2,000 ...

DT: determiner

all an another any both del each either every half la many much nary
neither no some such that the them these this those

EX: existential there

there

IN: preposition or conjunction, subordinating

astride among uppon whether out inside pro despite on by throughout
below within for towards near behind atop around if like until below
next into if beside ...

JJ: adjective or numeral, ordinal

third ill-mannered pre-war regrettable oiled calamitous first separable
ectoplasmic battery-powered participatory fourth still-to-be-named
multilingual multi-disciplinary ...

JJR: adjective, comparative

bleaker braver breezier briefer brighter brisker broader bumper busier
calmer cheaper choosier cleaner clearer closer colder commoner costlier
cozier creamier crunchier cuter ...

JJS: adjective, superlative

calmest cheapest choicest classiest cleanest clearest closest commonest
corniest costliest crassest creepiest crudest cutest darkest deadliest
dearest deepest densest dinkiest ...

LS: list item marker

A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005
SP-44007 Second Third Three Two * a b c d first five four one six three
two

MD: modal auxiliary

can cannot could couldn't dare may might must need ought shall should
shouldn't will would

NN: noun, common, singular or mass

common-carrier cabbage knuckle-duster Casino afghan shed thermostat
investment slide humour falloff slick wind hyena override subhumanity
machinist ...

NNP: noun, proper, singular

Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos
Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA
Shannon A.K.C. Meltex Liverpool ...

NNS: noun, common, plural

undergraduates scotches bric-a-brac products bodyguards facets coasts
divestitures storehouses designs clubs fragrances averages
subjectivists apprehensions muses factory-jobs ...

PDT: pre-determiner

all both half many quite such sure this

POS: genitive marker

' 's

PRP: pronoun, personal

hers herself him himself hisself it itself me myself one oneself ours
ourselves ownself self she thee theirs them themselves they thou thy us

PRP$: pronoun, possessive

her his mine my our ours their thy your

RB: adverb

occasionally unabatingly maddeningly adventurously professedly
stirringly prominently technologically magisterially predominately
swiftly fiscally pitilessly ...

RBR: adverb, comparative

further gloomier grander graver greater grimmer harder harsher
healthier heavier higher however larger later leaner lengthier less-
perfectly lesser lonelier longer louder lower more ...

RBS: adverb, superlative

best biggest bluntest earliest farthest first furthest hardest
heartiest highest largest least less most nearest second tightest worst

RP: particle

aboard about across along apart around aside at away back before behind
by crop down ever fast for forth from go high i.e. in into just later
low more off on open out over per pie raising start teeth that through
under unto up up-pp upon whole with you

TO: "to" as preposition or infinitive marker

to

UH: interjection

Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen
huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly
man baby diddle hush sonuvabitch ...

VB: verb, base form

ask assemble assess assign assume atone attention avoid bake balkanize
bank begin behold believe bend benefit bevel beware bless boil bomb
boost brace break bring broil brush build ...

VBD: verb, past tense

dipped pleaded swiped regummed soaked tidied convened halted registered
cushioned exacted snubbed strode aimed adopted belied figgered
speculated wore appreciated contemplated ...

VBG: verb, present participle or gerund

telegraphing stirring focusing angering judging stalling lactating
hankerin' alleging veering capping approaching traveling besieging
encrypting interrupting erasing wincing ...

VBN: verb, past participle

multihulled dilapidated aerosolized chaired languished panelized used
experimented flourished imitated reunifed factored condensed sheared
unsettled primed dubbed desired ...

VBP: verb, present tense, not 3rd person singular

predominate wrap resort sue twist spill cure lengthen brush terminate
appear tend stray glisten obtain comprise detest tease attract
emphasize mold postpone sever return wag ...

VBZ: verb, present tense, 3rd person singular

bases reconstructs marks mixes displeases seals carps weaves snatches
slumps stretches authorizes smolders pictures emerges stockpiles
seduces fizzes uses bolsters slaps speaks pleads ...

WDT: WH-determiner

that what whatever which whichever

WP: WH-pronoun

that what whatever whatsoever which who whom whosoever

WRB: Wh-adverb

how however whence whenever where whereby whereever wherein whereof why

Effect of NOLOCK hint in SELECT statements

In addition to what is said above, you should be very aware that nolock actually imposes the risk of you not getting rows that has been committed before your select.

See http://blogs.msdn.com/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

I fixed this error by upgrading the app from .Net Framework 4.5 to 4.6.2.

TLS-1.2 was correctly installed on the server, and older versions like TLS-1.1 were disabled. However, .Net 4.5 does not support TLS-1.2.

Show animated GIF

I wanted to put the .gif file in a GUI but displayed with other elements. And the .gif file would be taken from the java project and not from an URL.

1 - Top of the interface would be a list of elements where we can choose one

2 - Center would be the animated GIF

3 - Bottom would display the element chosen from the list

Here is my code (I need 2 java files, the first (Interf.java) calls the second (Display.java)):

1 - Interf.java

public class Interface_for {

    public static void main(String[] args) {

        Display Fr = new Display();

    }
}

2 - Display.java

INFOS: Be shure to create a new source folder (NEW > source folder) in your java project and put the .gif inside for it to be seen as a file.

I get the gif file with the code below, so I can it export it in a jar project(it's then animated).

URL url = getClass().getClassLoader().getResource("fire.gif");

  public class Display extends JFrame {
  private JPanel container = new JPanel();
  private JComboBox combo = new JComboBox();
  private JLabel label = new JLabel("A list");
  private JLabel label_2 = new JLabel ("Selection");

  public Display(){
    this.setTitle("Animation");
    this.setSize(400, 350);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    container.setLayout(new BorderLayout());
    combo.setPreferredSize(new Dimension(190, 20));
    //We create te list of elements for the top of the GUI
    String[] tab = {"Option 1","Option 2","Option 3","Option 4","Option 5"};
    combo = new JComboBox(tab);

    //Listener for the selected option
    combo.addActionListener(new ItemAction());

    //We add elements from the top of the interface
    JPanel top = new JPanel();
    top.add(label);
    top.add(combo);
    container.add(top, BorderLayout.NORTH);

    //We add elements from the center of the interface
    URL url = getClass().getClassLoader().getResource("fire.gif");
    Icon icon = new ImageIcon(url);
    JLabel center = new JLabel(icon);
    container.add(center, BorderLayout.CENTER);

    //We add elements from the bottom of the interface
    JPanel down = new JPanel();
    down.add(label_2);
    container.add(down,BorderLayout.SOUTH);

    this.setContentPane(container);
    this.setVisible(true);
    this.setResizable(false);
  }
  class ItemAction implements ActionListener{
      public void actionPerformed(ActionEvent e){
          label_2.setText("Chosen option: "+combo.getSelectedItem().toString());
      }
  }
}

Allowed characters in filename

You should start with the Wikipedia Filename page. It has a decent-sized table (Comparison of filename limitations), listing the reserved characters for quite a lot of file systems.

It also has a plethora of other information about each file system, including reserved file names such as CON under MS-DOS. I mention that only because I was bitten by that once when I shortened an include file from const.h to con.h and spent half an hour figuring out why the compiler hung.

Turns out DOS ignored extensions for devices so that con.h was exactly the same as con, the input console (meaning, of course, the compiler was waiting for me to type in the header file before it would continue).

How to diff a commit with its parent?

If you know how far back, you can try something like:

# Current branch vs. parent
git diff HEAD^ HEAD

# Current branch, diff between commits 2 and 3 times back
git diff HEAD~3 HEAD~2

Prior commits work something like this:

# Parent of HEAD
git show HEAD^1

# Grandparent
git show HEAD^2

There are a lot of ways you can specify commits:

# Great grandparent
git show HEAD~3

See this page for details.

Foreign Key to multiple tables

You have a few options, all varying in "correctness" and ease of use. As always, the right design depends on your needs.

  • You could simply create two columns in Ticket, OwnedByUserId and OwnedByGroupId, and have nullable Foreign Keys to each table.

  • You could create M:M reference tables enabling both ticket:user and ticket:group relationships. Perhaps in future you will want to allow a single ticket to be owned by multiple users or groups? This design does not enforce that a ticket must be owned by a single entity only.

  • You could create a default group for every user and have tickets simply owned by either a true Group or a User's default Group.

  • Or (my choice) model an entity that acts as a base for both Users and Groups, and have tickets owned by that entity.

Heres a rough example using your posted schema:

create table dbo.PartyType
(   
    PartyTypeId tinyint primary key,
    PartyTypeName varchar(10)
)

insert into dbo.PartyType
    values(1, 'User'), (2, 'Group');


create table dbo.Party
(
    PartyId int identity(1,1) primary key,
    PartyTypeId tinyint references dbo.PartyType(PartyTypeId),
    unique (PartyId, PartyTypeId)
)

CREATE TABLE dbo.[Group]
(
    ID int primary key,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(2 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyId, PartyTypeID)
)  

CREATE TABLE dbo.[User]
(
    ID int primary key,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(1 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyID, PartyTypeID)
)

CREATE TABLE dbo.Ticket
(
    ID int primary key,
    [Owner] int NOT NULL references dbo.Party(PartyId),
    [Subject] varchar(50) NULL
)

Failed to locate the winutils binary in the hadoop binary path

Set up HADOOP_HOME variable in windows to resolve the problem.

You can find answer in org/apache/hadoop/hadoop-common/2.2.0/hadoop-common-2.2.0-sources.jar!/org/apache/hadoop/util/Shell.java :

IOException from

  public static final String getQualifiedBinPath(String executable) 
  throws IOException {
    // construct hadoop bin path to the specified executable
    String fullExeName = HADOOP_HOME_DIR + File.separator + "bin" 
      + File.separator + executable;
    File exeFile = new File(fullExeName);
    if (!exeFile.exists()) {
      throw new IOException("Could not locate executable " + fullExeName
        + " in the Hadoop binaries.");
    }
    return exeFile.getCanonicalPath();
  }

HADOOP_HOME_DIR from

// first check the Dflag hadoop.home.dir with JVM scope
String home = System.getProperty("hadoop.home.dir");
// fall back to the system/user-global env variable
if (home == null) {
  home = System.getenv("HADOOP_HOME");
}

How to get process ID of background process?

You need to save the PID of the background process at the time you start it:

foo &
FOO_PID=$!
# do other stuff
kill $FOO_PID

You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.

Bootstrap - dropdown menu not working?

Double importing jquery can cause Error

<script src="static/public/js/jquery/jquery.min.js"></script>

OR

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="" crossorigin="anonymous"></script>

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

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

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

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

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

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

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

export class testWidget {

    private model: Model = new Model();

    constructor() {}
}

Verifying that a string contains only letters in C#

For those of you who would rather not go with Regex and are on the .NET 2.0 Framework (AKA no LINQ):

Only Letters:

public static bool IsAllLetters(string s)
{
    foreach (char c in s)
    {
        if (!Char.IsLetter(c))
            return false;
    }
    return true;
}

Only Numbers:

    public static bool IsAllDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsDigit(c))
                return false;
        }
        return true;
    }

Only Numbers Or Letters:

    public static bool IsAllLettersOrDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c))
                return false;
        }
        return true;
    }

Only Numbers Or Letters Or Underscores:

    public static bool IsAllLettersOrDigitsOrUnderscores(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c) && c != '_')
                return false;
        }
        return true;
    }

JUnit Testing Exceptions

An adventage of use ExpectedException Rule (version 4.7) is that you can test exception message and not only the expected exception.

And using Matchers, you can test the part of message you are interested:

exception.expectMessage(containsString("income: -1000.0"));

Is null check needed before calling instanceof?

No, a null check is not needed before using instanceof.

The expression x instanceof SomeClass is false if x is null.

From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":

"At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false."

So if the operand is null, the result is false.

How to implement the factory method pattern in C++ correctly

Loki has both a Factory Method and an Abstract Factory. Both are documented (extensively) in Modern C++ Design, by Andei Alexandrescu. The factory method is probably closer to what you seem to be after, though it's still a bit different (at least if memory serves, it requires you to register a type before the factory can create objects of that type).

Getting the current date in SQL Server?

SELECT CAST(GETDATE() AS DATE)

Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.

SELECT CAST(GETDATE() AS BINARY(8))

The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

What is ".NET Core"?

From Microsoft's Website:

.NET Core refers to several technologies including .NET Core, ASP.NET Core and Entity Framework Core.

These technologies are different than native .NET in that they run using CoreCLR runtime (used in the Universal Windows Platform).

As you mentioned in your question, .NET Core is not only open-source, but portable as well [runs on MacOS, Windows, and Linux]

The internals of .NET Core are also optimised to not use different modules from its core library unless it is required by the application.

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

Printing image with PrintDocument. how to adjust the image to fit paper size

Agree with TonyM and BBoy - this is the correct answer for original 4*6 printing of label. (args.PageBounds). This worked for me for printing Endicia API service shipping Labels.

private void SubmitResponseToPrinter(ILabelRequestResponse response)
    {
        PrintDocument pd = new PrintDocument();
        pd.PrintPage += (sender, args) =>
        {
            Image i = Image.FromFile(response.Labels[0].FullPathFileName.Trim());
            args.Graphics.DrawImage(i, args.PageBounds);
        };
        pd.Print();
    }

converting CSV/XLS to JSON?

Take a try on the tiny free tool:

http://keyangxiang.com/csvtojson/

It utilises node.js csvtojson module

Powershell Execute remote exe with command line arguments on remote computer

$sb = ScriptBlock::Create("$command")
Invoke-Command -ScriptBlock $sb

This should work and avoid misleading the beginners.

jQuery's .click - pass parameters to user function

You need to use an anonymous function like this:

$('.leadtoscore').click(function() {
  add_event('shot')
});

You can call it like you have in the example, just a function name without parameters, like this:

$('.leadtoscore').click(add_event);

But the add_event method won't get 'shot' as it's parameter, but rather whatever click passes to it's callback, which is the event object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind() and pass data, like this:

$('.leadtoscore').bind('click', { param: 'shot' }, add_event);

And access it in add_event, like this:

function add_event(event) {
  //event.data.param == "shot", use as needed
}

Disable Tensorflow debugging information

You can disable all debugging logs using os.environ :

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 
import tensorflow as tf

Tested on tf 0.12 and 1.0

In details,

0 = all messages are logged (default behavior)
1 = INFO messages are not printed
2 = INFO and WARNING messages are not printed
3 = INFO, WARNING, and ERROR messages are not printed

PHP Error: Cannot use object of type stdClass as array (array and object issues)

$blog is an object not an array

try using $blog->id instead of $blog['id']

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Where can I find decent visio templates/diagrams for software architecture?

There should be templates already included in Visio 2007 for software architecture but you might want to check out Visio 2007 templates.

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

SwiftUI

in SwiftUI, there is a View called Divider that is perfectly matched for this. You can add it below any view by embedding them into a simple VStack:

VStack {
    Text("This could be any View")
    Divider()
}

When to use RSpec let()?

Dissenting voice here: after 5 years of rspec I don't like let very much.

1. Lazy evaluation often makes test setup confusing

It becomes difficult to reason about setup when some things that have been declared in setup are not actually affecting state, while others are.

Eventually, out of frustration someone just changes let to let! (same thing without lazy evaluation) in order to get their spec working. If this works out for them, a new habit is born: when a new spec is added to an older suite and it doesn't work, the first thing the writer tries is to add bangs to random let calls.

Pretty soon all the performance benefits are gone.

2. Special syntax is unusual to non-rspec users

I would rather teach Ruby to my team than the tricks of rspec. Instance variables or method calls are useful everywhere in this project and others, let syntax will only be useful in rspec.

3. The "benefits" allow us to easily ignore good design changes

let() is good for expensive dependencies that we don't want to create over and over. It also pairs well with subject, allowing you to dry up repeated calls to multi-argument methods

Expensive dependencies repeated in many times, and methods with big signatures are both points where we could make the code better:

  • maybe I can introduce a new abstraction that isolates a dependency from the rest of my code (which would mean fewer tests need it)
  • maybe the code under test is doing too much
  • maybe I need to inject smarter objects instead of a long list of primitives
  • maybe I have a violation of tell-don't-ask
  • maybe the expensive code can be made faster (rarer - beware of premature optimisation here)

In all these cases, I can address the symptom of difficult tests with a soothing balm of rspec magic, or I can try address the cause. I feel like I spent way too much of the last few years on the former and now I want some better code.

To answer the original question: I would prefer not to, but I do still use let. I mostly use it to fit in with the style of the rest of the team (it seems like most Rails programmers in the world are now deep into their rspec magic so that is very often). Sometimes I use it when I'm adding a test to some code that I don't have control of, or don't have time to refactor to a better abstraction: i.e. when the only option is the painkiller.

Excel VBA - select a dynamic cell range

If you want to select a variable range containing all headers cells:

Dim sht as WorkSheet
Set sht = This Workbook.Sheets("Data")

'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUST

sht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select

...as long as there's no other content on that row.

EDIT: updated to stress that when using Range(Cells(...), Cells(...)) it's good practice to qualify both Range and Cells with a worksheet reference.

CSS scale height to match width - possibly with a formfactor

Solution with Jquery

$(window).resize(function () {
    var width = $("#map").width();
    $("#map").height(width * 1.72);
});

How to increase the max connections in postgres?

change max_connections variable in postgresql.conf file located in /var/lib/pgsql/data or /usr/local/pgsql/data/

How do I read a large csv file with pandas?

You can try sframe, that have the same syntax as pandas but allows you to manipulate files that are bigger than your RAM.

Is SMTP based on TCP or UDP?

In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.

As defined in RFC 821, RFC 2821, and RFC 5321:

SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.

In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.

In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.


The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.

Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.

Pressed <button> selector

Maybe :active over :focus with :hover will help! Try

button {
background:lime;
}

button:hover {
background:green;
}

button:focus {
background:gray;
}

button:active {
background:red;
}

Then:

<button onkeydown="alerted_of_key_pressed()" id="button" title="Test button" href="#button">Demo</button>

Then:

<!--JAVASCRIPT-->
<script>
function alerted_of_key_pressed() { alert("You pressed a key when hovering over this button.") }
</script>
 Sorry about that last one. :) I was just showing you a cool function! 
Wait... did I just emphasize a code block? This is cool!!!

Converting Integer to String with comma for thousands

This is a way that also able you to replace default separator with any characters:

val myNumber = NumberFormat.getNumberInstance(Locale.US)
   .format(123456789)
   .replace(",", "?")

Ant if else condition?

The quirky syntax using conditions on the target (described by Mads) is the only supported way to perform conditional execution in core ANT.

ANT is not a programming language and when things get complicated I choose to embed a script within my build as follows:

<target name="prepare-copy" description="copy file based on condition">
    <groovy>
        if (properties["some.condition"] == "true") {
            ant.copy(file:"${properties["some.dir"]}/true", todir:".")
        }
    </groovy>
</target>

ANT supports several languages (See script task), my preference is Groovy because of it's terse syntax and because it plays so well with the build.

Apologies, David I am not a fan of ant-contrib.

How can I generate a 6 digit unique number?

If you want it to start at 000001 and go to 999999:

$num_str = sprintf("%06d", mt_rand(1, 999999));

Mind you, it's stored as a string.

install apt-get on linux Red Hat server

If you insist on using yum, try yum install apt. As read on this site: Link

Oracle query to fetch column names

  1. SELECT * FROM <SCHEMA_NAME.TABLE_NAME> WHERE ROWNUM = 0; --> Note that, this is Query Result, a ResultSet. This is exportable to other formats. And, you can export the Query Result to Text format. Export looks like below when I did SELECT * FROM SATURN.SPRIDEN WHERE ROWNUM = 0; :

    "SPRTELE_PIDM" "SPRTELE_SEQNO" "SPRTELE_TELE_CODE" "SPRTELE_ACTIVITY_DATE" "SPRTELE_PHONE_AREA" "SPRTELE_PHONE_NUMBER" "SPRTELE_PHONE_EXT" "SPRTELE_STATUS_IND" "SPRTELE_ATYP_CODE" "SPRTELE_ADDR_SEQNO" "SPRTELE_PRIMARY_IND" "SPRTELE_UNLIST_IND" "SPRTELE_COMMENT" "SPRTELE_INTL_ACCESS" "SPRTELE_DATA_ORIGIN" "SPRTELE_USER_ID" "SPRTELE_CTRY_CODE_PHONE" "SPRTELE_SURROGATE_ID" "SPRTELE_VERSION" "SPRTELE_VPDI_CODE"

  2. DESCRIBE <TABLE_NAME> --> Note: This is script output.

How do I check if an index exists on a table field in MySQL?

show index from table_name where Column_name='column_name';

Best Timer for using in a Windows service

I agree with previous comment that might be best to consider a different approach. My suggest would be write a console application and use the windows scheduler:

This will:

  • Reduce plumbing code that replicates scheduler behaviour
  • Provide greater flexibility in terms of scheduling behaviour (e.g. only run on weekends) with all scheduling logic abstracted from application code
  • Utilise the command line arguments for parameters without having to setup configuration values in config files etc
  • Far easier to debug/test during development
  • Allow a support user to execute by invoking the console application directly (e.g. useful during support situations)

Get viewport/window height in ReactJS

class AppComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {height: props.height};
  }

  componentWillMount(){
    this.setState({height: window.innerHeight + 'px'});
  }

  render() {
    // render your component...
  }
}

Set the props

AppComponent.propTypes = {
 height:React.PropTypes.string
};

AppComponent.defaultProps = {
 height:'500px'
};

viewport height is now available as {this.state.height} in rendering template

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

How to include !important in jquery

If you need to have jquery use !important for more than one item, this is how you would do it.

e.g. set an img tags max-width and max-height to 500px each

$('img').css('cssText', "max-width: 500px !important;' + "max-height: 500px !important;');

How to use Git Revert

The question is quite old but revert is still confusing people (like me)

As a beginner, after some trial and error (more errors than trials) I've got an important point:

  • git revert requires the id of the commit you want to remove keeping it into your history

  • git reset requires the commit you want to keep, and will consequentially remove anything after that from history.

That is, if you use revert with the first commit id, you'll find yourself into an empty directory and an additional commit in history, while with reset your directory will be.. reverted back to the initial commit and your history will get as if the last commit(s) never happened.

To be even more clear, with a log like this:

# git log --oneline

cb76ee4 wrong
01b56c6 test
2e407ce first commit

Using git revert cb76ee4 will by default bring your files back to 01b56c6 and will add a further commit to your history:

8d4406b Revert "wrong"
cb76ee4 wrong
01b56c6 test
2e407ce first commit

git reset 01b56c6 will instead bring your files back to 01b56c6 and will clean up any other commit after that from your history :

01b56c6 test
2e407ce first commit

I know these are "the basis" but it was quite confusing for me, by running revert on first id ('first commit') I was expecting to find my initial files, it taken a while to understand, that if you need your files back as 'first commit' you need to use the next id.

Why is using onClick() in HTML a bad practice?

It's a new paradigm called "Unobtrusive JavaScript". The current "web standard" says to separate functionality and presentation.

It's not really a "bad practice", it's just that most new standards want you to use event listeners instead of in-lining JavaScript.

Also, this may just be a personal thing, but I think it's much easier to read when you use event listeners, especially if you have more than 1 JavaScript statement you want to run.

find if an integer exists in a list of integers

bool vExist = false;
int vSelectValue = 1;

List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);

IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
    vExist = true;
}

Name attribute in @Entity and @Table

@Entity(name = "someThing") => this name will be used to name the Entity
@Table(name = "someThing")  => this name will be used to name a table in DB

So, in the first case your table and entity will have the same name, that will allow you to access your table with the same name as the entity while writing HQL or JPQL.

And in second case while writing queries you have to use the name given in @Entity and the name given in @Table will be used to name the table in the DB.

So in HQL your someThing will refer to otherThing in the DB.

Angular/RxJs When should I unsubscribe from `Subscription`

For handling subscription I use a "Unsubscriber" class.

Here is the Unsubscriber Class.

export class Unsubscriber implements OnDestroy {
  private subscriptions: Subscription[] = [];

  addSubscription(subscription: Subscription | Subscription[]) {
    if (Array.isArray(subscription)) {
      this.subscriptions.push(...subscription);
    } else {
      this.subscriptions.push(subscription);
    }
  }

  unsubscribe() {
    this.subscriptions
      .filter(subscription => subscription)
      .forEach(subscription => {
        subscription.unsubscribe();
      });
  }

  ngOnDestroy() {
    this.unsubscribe();
  }
}

And You can use this class in any component / Service / Effect etc.

Example:

class SampleComponent extends Unsubscriber {
    constructor () {
        super();
    }

    this.addSubscription(subscription);
}

Django DoesNotExist

I have found the solution to this issue using ObjectDoesNotExist on this way

from django.core.exceptions import ObjectDoesNotExist
......

try:
  # try something
except ObjectDoesNotExist:
  # do something

After this, my code works as I need

Thanks any way, your post help me to solve my issue

Show spinner GIF during an $http request in AngularJS?

Here are the current past AngularJS incantations:

angular.module('SharedServices', [])
    .config(function ($httpProvider) {
        $httpProvider.responseInterceptors.push('myHttpInterceptor');
        var spinnerFunction = function (data, headersGetter) {
            // todo start the spinner here
            //alert('start spinner');
            $('#mydiv').show();
            return data;
        };
        $httpProvider.defaults.transformRequest.push(spinnerFunction);
    })
// register the interceptor as a service, intercepts ALL angular ajax http calls
    .factory('myHttpInterceptor', function ($q, $window) {
        return function (promise) {
            return promise.then(function (response) {
                // do something on success
                // todo hide the spinner
                //alert('stop spinner');
                $('#mydiv').hide();
                return response;

            }, function (response) {
                // do something on error
                // todo hide the spinner
                //alert('stop spinner');
                $('#mydiv').hide();
                return $q.reject(response);
            });
        };
    });

//regular angular initialization continued below....
angular.module('myApp', [ 'myApp.directives', 'SharedServices']).
//.......

Here is the rest of it (HTML / CSS)....using

$('#mydiv').show(); 
$('#mydiv').hide(); 

to toggle it. NOTE: the above is used in the angular module at beginning of post

#mydiv {  
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    z-index:1000;
    background-color:grey;
    opacity: .8;
 }

.ajax-loader {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -32px; /* -1 * image width / 2 */
    margin-top: -32px;  /* -1 * image height / 2 */
    display: block;     
}

<div id="mydiv">
    <img src="lib/jQuery/images/ajax-loader.gif" class="ajax-loader"/>
</div>

Relationship between hashCode and equals method in Java

The contract is that if obj1.equals(obj2) then obj1.hashCode() == obj2.hashCode() , it is mainly for performance reasons, as maps are mainly using hashCode method to compare entries keys.

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );

How can I export Excel files using JavaScript?

I recommend you to generate an open format XML Excel file, is much more flexible than CSV.
Read Generating an Excel file in ASP.NET for more info

write multiple lines in a file in python

I notice that this is a study drill from the book "Learn Python The Hard Way". Though you've asked this question 3 years ago, I'm posting this for new users to say that don't ask in stackoverflow directly. At least read the documentation before asking.

And as far as the question is concerned, using writelines is the easiest way.

Use it like this:

target.writelines([line1, line2, line3])

And as alkid said, you messed with the brackets, just follow what he said.

How can I remove the search bar and footer added by the jQuery DataTables plugin?

If you only want to hide the search form for example because you have column input filters or may be because you already have a CMS search form able to return results from the table then all you have to do is inspect the form and get its id - (at the time of writing this, it looks as such[tableid]-table_filter.dataTables_filter). Then simply do [tableid]-table_filter.dataTables_filter{display:none;} retaining all other features of datatables.

How to convert Nonetype to int or string?

A common "Pythonic" way to handle this kind of situation is known as EAFP for "It's easier to ask forgiveness than permission". Which usually means writing code that assumes everything is fine, but then wrapping it with a try...except block to handle things—just in case—it's not.

Here's that coding style applied to your problem:

try:
    my_value = int(my_value)
except TypeError:
    my_value = 0  # or whatever you want to do

answer = my_value / divisor

Or perhaps the even simpler and slightly faster:

try:
    answer = int(my_value) / divisor
except TypeError:
    answer = 0

The inverse and more traditional approach is known as LBYL which stands for "Look before you leap" is what @Soviut and some of the others have suggested. For additional coverage of this topic see my answer and associated comments to the question Determine whether a key is present in a dictionary elsewhere on this site.

One potential problem with EAFP is that it can hide the fact that something is wrong with some other part of your code or third-party module you're using, especially when the exceptions frequently occur (and therefore aren't really "exceptional" cases at all).

How to handle notification when app in background in Firebase

Working as of July 2019

Android compileSdkVersion 28, buildToolsVersion 28.0.3 and firebase-messaging:19.0.1

After many many hours of researching through all of the other StackOverflow questions and answers, and trying innumerable outdated solutions, this solution managed to show notifications in these 3 scenarios:

- App is in foreground:
the notification is received by the onMessageReceived method at my MyFirebaseMessagingService class

- App has been killed (it is not running in background): the notification is sent to the notification tray automatically by FCM. When the user touches the notification the app is launched by calling the activity that has android.intent.category.LAUNCHER in the manifest. You can get the data part of the notification by using getIntent().getExtras() at the onCreate() method.

- App is in background: the notification is sent to the notification tray automatically by FCM. When the user touches the notification the app is brought to the foreground by launching the activity that has android.intent.category.LAUNCHER in the manifest. As my app has launchMode="singleTop" in that activity, the onCreate() method is not called because one activity of the same class is already created, instead the onNewIntent() method of that class is called and you get the data part of the notification there by using intent.getExtras().

Steps: 1- If you define your app's main activity like this:

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:screenOrientation="portrait"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name=".MainActivity" />
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

2- add these lines at the onCreate() method of your MainActivity.class

Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null) {
    for (String key : extras.keySet()) {
        Object value = extras.get(key);
        Log.d(Application.APPTAG, "Extras received at onCreate:  Key: " + key + " Value: " + value);
    }
    String title = extras.getString("title");
    String message = extras.getString("body");
    if (message!=null && message.length()>0) {
        getIntent().removeExtra("body");
        showNotificationInADialog(title, message);
    }
}

and these methods to the same MainActivity.class:

@Override
public void onNewIntent(Intent intent){
    //called when a new intent for this class is created.
    // The main case is when the app was in background, a notification arrives to the tray, and the user touches the notification

    super.onNewIntent(intent);

    Log.d(Application.APPTAG, "onNewIntent - starting");
    Bundle extras = intent.getExtras();
    if (extras != null) {
        for (String key : extras.keySet()) {
            Object value = extras.get(key);
            Log.d(Application.APPTAG, "Extras received at onNewIntent:  Key: " + key + " Value: " + value);
        }
        String title = extras.getString("title");
        String message = extras.getString("body");
        if (message!=null && message.length()>0) {
            getIntent().removeExtra("body");
            showNotificationInADialog(title, message);
        }
    }
}


private void showNotificationInADialog(String title, String message) {

    // show a dialog with the provided title and message
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

3- create the class MyFirebase like this:

package com.yourcompany.app;

import android.content.Intent;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {


    public MyFirebaseMessagingService() {
        super();
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(Application.APPTAG, "myFirebaseMessagingService - onMessageReceived - message: " + remoteMessage);

        Intent dialogIntent = new Intent(this, NotificationActivity.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        dialogIntent.putExtra("msg", remoteMessage);
        startActivity(dialogIntent);

    }

}

4- create a new class NotificationActivity.class like this:

package com.yourcompany.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ContextThemeWrapper;

import com.google.firebase.messaging.RemoteMessage;

public class NotificationActivity extends AppCompatActivity {

private Activity context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    Bundle extras = getIntent().getExtras();

    Log.d(Application.APPTAG, "NotificationActivity - onCreate - extras: " + extras);

    if (extras == null) {
        context.finish();
        return;
    }

    RemoteMessage msg = (RemoteMessage) extras.get("msg");

    if (msg == null) {
        context.finish();
        return;
    }

    RemoteMessage.Notification notification = msg.getNotification();

    if (notification == null) {
        context.finish();
        return;
    }

    String dialogMessage;
    try {
        dialogMessage = notification.getBody();
    } catch (Exception e){
        context.finish();
        return;
    }
    String dialogTitle = notification.getTitle();
    if (dialogTitle == null || dialogTitle.length() == 0) {
        dialogTitle = "";
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.myDialog));
    builder.setTitle(dialogTitle);
    builder.setMessage(dialogMessage);
    builder.setPositiveButton(getResources().getString(R.string.accept), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();

}

}

5- Add these lines to your app Manifest, inside your tags

    <service
        android:name=".MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id"/>

    <activity android:name=".NotificationActivity"
        android:theme="@style/myDialog"> </activity>

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/notification_icon"/>

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/color_accent" />

6- add these lines in your Application.java onCreate() method, or in MainActivity.class onCreate() method:

      // notifications channel creation
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      // Create channel to show notifications.
      String channelId = getResources().getString("default_channel_id");
      String channelName = getResources().getString("General announcements");
      NotificationManager notificationManager = getSystemService(NotificationManager.class);
      notificationManager.createNotificationChannel(new NotificationChannel(channelId,
              channelName, NotificationManager.IMPORTANCE_LOW));
  }

Done.

Now for this to work well in the 3 mentioned scenarios, you have to send the notification from the Firebase web console in the following way:

In the Notification section: Notification Title = Title to display in the notification dialog (optional) Notification text = Message to show to the user (required) Then in the Target section: App = your Android app and in Additional Options section: Android Notification Channel = default_channel_id Custom Data key: title value: (same text here than in the Title field of the Notification section) key: body value: (same text here than in the Message field of the Notification section) key:click_action value: .MainActivity Sound=Disabled
Expires=4 weeks

You can debug it in the Emulator with API 28 with Google Play.

Happy coding!

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

This trick works for me:

    grd.DataSource = DT;

    // Set your desired AutoSize Mode:
    grd.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    grd.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    grd.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

    // Now that DataGridView has calculated it's Widths; we can now store each column Width values.
    for (int i = 0; i <= grd.Columns.Count - 1; i++)
    {
        // Store Auto Sized Widths:
        int colw = grd.Columns[i].Width;

        // Remove AutoSizing:
        grd.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;

        // Set Width to calculated AutoSize value:
        grd.Columns[i].Width = colw;
    }

In the Code above: You set the Columns AutoSize Property to whathever AutoSizeMode you need. Then (Column by Column) you store each column Width value (from AutoSize value); Disable the AutoSize Property and finally, set the Column Width to the Width value you previously stored.

Show Image View from file path?

onLoadImage Full load

private void onLoadImage(final String imagePath) {
    ImageSize targetSize = new ImageSize(imageView.getWidth(), imageView.getHeight()); // result Bitmap will be fit to this size

    //ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleto
    com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
    imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));

    imageLoader.loadImage(imagePath, targetSize, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(final String imageUri, View view) {
            super.onLoadingStarted(imageUri, view);

            progress2.setVisibility(View.VISIBLE);

            new Handler().post(new Runnable() {
                public void run() {
                    progress2.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);

                    // Picasso.with(getContext()).load(imagePath).into(imageView);
                    // Picasso.with(getContext()).load(imagePath) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imageView);

                    Glide.with(getContext())
                            .load(imagePath)
                            .asBitmap()
                            .into(imageView);
                }
          });
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            // else { 
              Log.e("onLoadImage", "onLoadingComplete");
            //   progress2.setVisibility(View.INVISIBLE);
            // }
            // setLoagingCompileImage();
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            super.onLoadingFailed(imageUri, view, failReason);
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            Log.e("onLoadingFailed", imageUri);
            Log.e("onLoadingFailed", failReason.toString());
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            super.onLoadingCancelled(imageUri, view);
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            Log.e("onLoadImage", "onLoadingCancelled");
        }
    });
}

How To Auto-Format / Indent XML/HTML in Notepad++

I'm using Notepad 7.6 with "Plugin Admin" and I could not find XML Tools.
I had to install it manually like @some-java-guy did in his answer except that my plugins folder was located here: C:\Users\<my username>\AppData\Local\Notepad++\plugins
In that directory I created a new directory (named XmlTools) and copied XMLTools.dll there. (And I copied all dependencies to the Notepad++ directory in Program files.)

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.

Singleton: How should it be used

The real downfall of Singletons is that they break inheritance. You can't derive a new class to give you extended functionality unless you have access to the code where the Singleton is referenced. So, beyond the fact the the Singleton will make your code tightly coupled (fixable by a Strategy Pattern ... aka Dependency Injection) it will also prevent you from closing off sections of the code from revision (shared libraries).

So even the examples of loggers or thread pools are invalid and should be replaced by Strategies.

Is it possible to serialize and deserialize a class in C++?

The Boost::serialization library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, here.

The only native way to do it is to use streams. That's essentially all the Boost::serialization library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format.

For built-in types, or your own types with operator<< and operator>> properly defined, that's fairly simple; see the C++ FAQ for more information.

Foreign keys in mongo?

We can define the so-called foreign key in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,

student
{ 
  _id: ObjectId(...),
  name: 'Jane',
  courses: ['bio101', 'bio102']   // <= ids of the courses
}

course
{
  _id: 'bio101',
  name: 'Biology 101',
  description: 'Introduction to biology'
}

The courses field contains _ids of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane, we need to perform another operation to retrieve the course document via _id.

If the course bio101 is removed, we need to perform another operation to update the courses field in the student document.

More: MongoDB Schema Design

The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:

Embedded document

  1. Suitable for one-to-few.
  2. Advantage: no need to perform additional queries to another document.
  3. Disadvantage: cannot manage the entity of embedded documents individually.

Example:

student
{
  name: 'Kate Monster',
  addresses : [
     { street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
     { street: '123 Avenue Q', city: 'New York', cc: 'USA' }
  ]
}

Child referencing

Like the student/course example above.

Parent referencing

Suitable for one-to-squillions, such as log messages.

host
{
    _id : ObjectID('AAAB'),
    name : 'goofy.example.com',
    ipaddr : '127.66.66.66'
}

logmsg
{
    time : ISODate("2014-03-28T09:42:41.382Z"),
    message : 'cpu is on fire!',
    host: ObjectID('AAAB')       // Reference to the Host document
}

Virtually, a host is the parent of a logmsg. Referencing to the host id saves much space given that the log messages are squillions.

References:

  1. 6 Rules of Thumb for MongoDB Schema Design: Part 1
  2. 6 Rules of Thumb for MongoDB Schema Design: Part 2
  3. 6 Rules of Thumb for MongoDB Schema Design: Part 3
  4. Model One-to-Many Relationships with Document References

How to implement a binary tree?

A very quick 'n dirty way of implementing a binary tree using lists. Not the most efficient, nor does it handle nil values all too well. But it's very transparent (at least to me):

def _add(node, v):
    new = [v, [], []]
    if node:
        left, right = node[1:]
        if not left:
            left.extend(new)
        elif not right:
            right.extend(new)
        else:
            _add(left, v)
    else:
        node.extend(new)

def binary_tree(s):
    root = []
    for e in s:
        _add(root, e)
    return root

def traverse(n, order):
    if n:
        v = n[0]
        if order == 'pre':
            yield v
        for left in traverse(n[1], order):
            yield left
        if order == 'in':
            yield v
        for right in traverse(n[2], order):
            yield right
        if order == 'post':
            yield v

Constructing a tree from an iterable:

 >>> tree = binary_tree('A B C D E'.split())
 >>> print tree
 ['A', ['B', ['D', [], []], ['E', [], []]], ['C', [], []]]

Traversing a tree:

 >>> list(traverse(tree, 'pre')), list(traverse(tree, 'in')), list(traverse(tree, 'post'))
 (['A', 'B', 'D', 'E', 'C'],
  ['D', 'B', 'E', 'A', 'C'],
  ['D', 'E', 'B', 'C', 'A'])

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

How to replace DOM element in place using Javascript?

This question is very old, but I found myself studying for a Microsoft Certification, and in the study book it was suggested to use:

oldElement.replaceNode(newElement)

I looked it up and it seems to only be supported in IE. Doh..

I thought I'd just add it here as a funny side note ;)

How to read a config file using python

In order to use my example,Your file "abc.txt" needs to look like:

[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"

Then in your software you can use the config parser:

import ConfigParser

and then in you code:

 configParser = ConfigParser.RawConfigParser()   
 configFilePath = r'c:\abc.txt'
 configParser.read(configFilePath)

Use case:

self.path = configParser.get('your-config', 'path1')

*Edit (@human.js)

in python 3, ConfigParser is renamed to configparser (as described here)

How to check if a registry value exists using C#?

Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.

For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.

foreach (var strServer in listServer)
{
    try
    {
        RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
        if (regCurrentUser == null)
            throw new ApplicationException("Not found registry SubKey ...");
        if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
            throw new ApplicationException("Not found value in SubKey ...");
    }
    catch (ApplicationException appEx)
    {
        Console.WriteLine(appEx);
        try
        {
            RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
            RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
            newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
        }
        catch(Exception ex)
        {
            Console.WriteLine($"{ex} Pipec kakoito ...");
        }
    }
}

sql delete statement where date is greater than 30 days

Although the DATEADD is probably the most transparrent way of doing this, it is worth noting that simply getdate()-30 will also suffice.

Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:

SELECT * 
FROM Results 
WHERE convert(varchar(8), [Date], 112) >= convert(varchar(8), getdate(), 112)

Is System.nanoTime() completely useless?

I have seen a negative elapsed time reported from using System.nanoTime(). To be clear, the code in question is:

    long startNanos = System.nanoTime();

    Object returnValue = joinPoint.proceed();

    long elapsedNanos = System.nanoTime() - startNanos;

and variable 'elapsedNanos' had a negative value. (I'm positive that the intermediate call took less than 293 years as well, which is the overflow point for nanos stored in longs :)

This occurred using an IBM v1.5 JRE 64bit on IBM P690 (multi-core) hardware running AIX. I've only seen this error occur once, so it seems extremely rare. I do not know the cause - is it a hardware-specific issue, a JVM defect - I don't know. I also don't know the implications for the accuracy of nanoTime() in general.

To answer the original question, I don't think nanoTime is useless - it provides sub-millisecond timing, but there is an actual (not just theoretical) risk of it being inaccurate which you need to take into account.

Iterating through populated rows

For the benefit of anyone searching for similar, see worksheet .UsedRange,
e.g. ? ActiveSheet.UsedRange.Rows.Count
and loops such as
For Each loopRow in Sheets(1).UsedRange.Rows: Print loopRow.Row: Next

Finding the last index of an array

Use Array.GetUpperBound(0). Array.Length contains the number of items in the array, so reading Length -1 only works on the assumption that the array is zero based.

Convert txt to csv python script

I suposse this is the output you need:

title,intro,tagline

2.9,Gardena,CA

It can be done with this changes to your code:

import csv
import itertools

with open('log.txt', 'r') as in_file:
    lines = in_file.read().splitlines()
    stripped = [line.replace(","," ").split() for line in lines]
    grouped = itertools.izip(*[stripped]*1)
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro', 'tagline'))
        for group in grouped:
            writer.writerows(group)

django order_by query set, ascending and descending

If for some reason you have null values you can use the F function like this:

from django.db.models import F

Reserved.objects.all().filter(client=client_id).order_by(F('check_in').desc(nulls_last=True))

So it will put last the null values. Documentation by Django: https://docs.djangoproject.com/en/stable/ref/models/expressions/#using-f-to-sort-null-values

Import/Index a JSON file into Elasticsearch

if you are using VirtualBox and UBUNTU in it or you are simply using UBUNTU then it can be useful

wget https://github.com/andrewvc/ee-datasets/archive/master.zip
sudo apt-get install unzip (only if unzip module is not installed)
unzip master.zip
cd ee-datasets
java -jar elastic-loader.jar http://localhost:9200 datasets/movie_db.eloader

Reducing MongoDB database file size

If you need to run a full repair, use the repairpath option. Point it to a disk with more available space.

For example, on my Mac I've used:

mongod --config /usr/local/etc/mongod.conf --repair --repairpath /Volumes/X/mongo_repair

Update: Per MongoDB Core Server Ticket 4266, you may need to add --nojournal to avoid an error:

mongod --config /usr/local/etc/mongod.conf --repair --repairpath /Volumes/X/mongo_repair --nojournal

OPTION (RECOMPILE) is Always Faster; Why?

The very first actions before tunning queries is to defrag/rebuild the indexes and statistics, otherway you're wasting your time.

You must check the execution plan to see if it's stable (is the same when you change the parameters), if not, you might have to create a cover index (in this case for each table) (knowing th system you can create one that is usefull for other queries too).

as an example : create index idx01_datafeed_trans On datafeed_trans ( feedid, feedDate) INCLUDE( acctNo, tradeDate)

if the plan is stable or you can stabilize it you can execute the sentence with sp_executesql('sql sentence') to save and use a fixed execution plan.

if the plan is unstable you have to use an ad-hoc statement or EXEC('sql sentence') to evaluate and create an execution plan each time. (or a stored procedure "with recompile").

Hope it helps.

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

Where can I find a list of escape characters required for my JSON ajax return type?

From the spec:

All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus [backslash] (U+005C), and the control characters U+0000 to U+001F

Just because e.g. Bell (U+0007) doesn't have a single-character escape code does not mean that you don't need to escape it. Use the Unicode escape sequence \u0007.

Remap values in pandas column with a dict

Adding to this question if you ever have more than one columns to remap in a data dataframe:

def remap(data,dict_labels):
    """
    This function take in a dictionnary of labels : dict_labels 
    and replace the values (previously labelencode) into the string.

    ex: dict_labels = {{'col1':{1:'A',2:'B'}}

    """
    for field,values in dict_labels.items():
        print("I am remapping %s"%field)
        data.replace({field:values},inplace=True)
    print("DONE")

    return data

Hope it can be useful to someone.

Cheers

Android: Flush DNS

You have a few options:

  • Release an update for your app that uses a different hostname that isn't in anyone's cache.
  • Same thing, but using the IP address of your server
  • Have your users go into settings -> applications -> Network Location -> Clear data.

You may want to check that last step because i don't know for a fact that this is the appropriate service. I can't really test that right now. Good luck!

Remove .php extension with .htaccess

If your url in PHP like http://yourdomain.com/demo.php than comes like http://yourdomain.com/demo

This is all you need:

create file .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]

How to call gesture tap on UIView programmatically in swift

I worked out on Xcode 6.4 on swift. See below.

var view1: UIView!

func assignTapToView1() {          
  let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
  //  tap.delegate = self
  view1.addGestureRecognizer(tap)
  self.view .addSubview(view1)

...
}

func handleTap() {
 print("tap working")
 view1.removeFromSuperview()
 // view1.alpha = 0.1
}

iOS for VirtualBox

You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.

Fatal error: Call to undefined function mcrypt_encrypt()

Under Ubuntu I had the problem and solved it with

$ sudo apt-get install php5-mcrypt
$ sudo service apache2 reload

"This operation requires IIS integrated pipeline mode."

I resolved this problem by following steps:

  1. Right click on root folder of project.
  2. Goto properties
  3. Click web in left menu
  4. change current port http://localhost:####/
  5. click create virtual directory
  6. Save the changes (ctrl+s)
  7. Run

may be it help you to.

Convert NSDate to NSString

Hope to add more value by providing the normal formatter including the year, month and day with the time. You can use this formatter for more than just a year

[dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"]; 

How to increase the vertical split window size in Vim

In case you need HORIZONTAL SPLIT resize as well:
The command is the same for all splits, just the parameter changes:

- + instead of < >

Examples:
Decrease horizontal size by 10 columns

:10winc -

Increase horizontal size by 30 columns

:30winc +

or within normal mode:

Horizontal splits

10 CTRL+w -

30 CTRL+w +

Vertical splits

10 CTRL+w < (decrease)

30 CTRL+w > (increase)

How to: "Separate table rows with a line"

HTML

<table cellspacing="0">
  <tr class="top bottom row">
    <td>one one</td>
    <td>one two</td>
  </tr>
  <tr class="top bottom row">
    <td>two one</td>
    <td>two two</td>
  </tr>
  <tr class="top bottom row">
    <td>three one</td>
    <td>three two</td>
  </tr>

</table>?

CSS:

tr.top td { border-top: thin solid black; }
tr.bottom td { border-bottom: thin solid black; }
tr.row td:first-child { border-left: thin solid black; }
tr.row td:last-child { border-right: thin solid black; }?

DEMO

What is the easiest way to initialize a std::vector with hardcoded elements?

If your compiler supports C++11, you can simply do:

std::vector<int> v = {1, 2, 3, 4};

This is available in GCC as of version 4.4. Unfortunately, VC++ 2010 seems to be lagging behind in this respect.

Alternatively, the Boost.Assign library uses non-macro magic to allow the following:

#include <boost/assign/list_of.hpp>
...
std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);

Or:

#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
...
std::vector<int> v;
v += 1, 2, 3, 4;

But keep in mind that this has some overhead (basically, list_of constructs a std::deque under the hood) so for performance-critical code you'd be better off doing as Yacoby says.

Creating a daemon in Linux

Try using the daemon function:

#include <unistd.h>

int daemon(int nochdir, int noclose);

From the man page:

The daemon() function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons.

If nochdir is zero, daemon() changes the calling process's current working directory to the root directory ("/"); otherwise, the current working directory is left unchanged.

If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors.

Oracle - Insert New Row with Auto Incremental ID

This is a simple way to do it without any triggers or sequences:

insert into WORKQUEUE (ID, facilitycode, workaction, description)
  values ((select max(ID)+1 from WORKQUEUE), 'J', 'II', 'TESTVALUES')

It worked for me but would not work with an empty table, I guess.

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

Hi I face the same problem today. After reading "Spentak"'s answer i tried to make code signing of my target to set to iOSDeveloper, and still did not work. But after i changing "Provisioning Profile" to "Automatic", the project got built and ran without any code signing errors.

How can I get Git to follow symlinks?

Hmmm, mount --bind doesn't seem to work on Darwin.

Does anyone have a trick that does?

[edited]

OK, I found the answer on Mac OS X is to make a hardlink. Except that that API is not exposed via ln, so you have to use your own tiny program to do this. Here is a link to that program:

Creating directory hard links in Mac OS X

Enjoy!

Automapper missing type map configuration or unsupported mapping - Error

I was trying to map an IEnumerable to an object. This is way I got this error. Maybe it helps.