Programs & Examples On #Embedding

An embedding is one instance of some structure contained within another instance, such as a group that is a subgroup.

How do I embed a mp4 movie into my html?

Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

How do I force files to open in the browser instead of downloading (PDF)?

Open downloads.php from rootfile.

Then go to line 186 and change it to the following:

        if(preg_match("/\.jpg|\.gif|\.png|\.jpeg/i", $name)){
            $mime = getimagesize($download_location);
            if(!empty($mime)) {
                header("Content-Type: {$mime['mime']}");
            }
        }
        elseif(preg_match("/\.pdf/i", $name)){
            header("Content-Type: application/force-download");
            header("Content-type: application/pdf");
            header("Content-Disposition: inline; filename=\"".$name."\";");
        }

        else{
            header("Content-Type: application/force-download");
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=\"".$name."\";");
        }

Preloading @font-face fonts?

This answer is no longer up to date

Please refer to this updated answer: https://stackoverflow.com/a/46830425/4031815


Deprecated answer

I'm not aware of any current technique to avoid the flicker as the font loads, however you can minimize it by sending proper cache headers for your font and making sure that that request goes through as quickly as possible.

how to compare the Java Byte[] array?

If you're trying to use the array as a generic HashMap key, that's not going to work. Consider creating a custom wrapper object that holds the array, and whose equals(...) and hashcode(...) method returns the results from the java.util.Arrays methods. For example...

import java.util.Arrays;

public class MyByteArray {
   private byte[] data;

   // ... constructors, getters methods, setter methods, etc...


   @Override
   public int hashCode() {
      return Arrays.hashCode(data);
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      MyByteArray other = (MyByteArray) obj;
      if (!Arrays.equals(data, other.data))
         return false;
      return true;
   }


}

Objects of this wrapper class will work fine as a key for your HashMap<MyByteArray, OtherType> and will allow for clean use of equals(...) and hashCode(...) methods.

In WPF, what are the differences between the x:Name and Name attributes?

The only difference is that if you are using user Controls into a control from Same Assembly then Name will not identify your control and you will get an error " Use x:Name for controls in the same Assembly". So x:Name is the WPF versioning of naming controls in WPF. Name is just used as a Winform Legacy. They wanted to differentiate the naming of controls in WPF and winforms as they use attributes in Xaml to identify controls from other assemblies they used x: for Names of control.

Just keep in mind dont put a name for a control just for the sake of keeping it as it resides in memory as a blank and it will give you a warning that Name has been applied for a control buts its never used.

Run CRON job everyday at specific time

you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM

1 10 * * * php -f /var/www/package/index.php controller function

30 14 * * * php -f /var/www/package/index.php controller function

but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30 .

30 10,14 * * * php -f /var/www/package/index.php controller function

Determine the path of the executing BASH script

Assuming you type in the full path to the bash script, use $0 and dirname, e.g.:

#!/bin/bash
echo "$0"
dirname "$0"

Example output:

$ /a/b/c/myScript.bash
/a/b/c/myScript.bash
/a/b/c

If necessary, append the results of the $PWD variable to a relative path.

EDIT: Added quotation marks to handle space characters.

How to set custom favicon in Express?

If you are using Express > 4.0, you could go for serve-favicon

How might I schedule a C# Windows Service to perform a task daily?

A daily task? Sounds like it should just be a scheduled task (control panel) - no need for a service here.

JavaScript - Hide a Div at startup (load)

Barring the CSS solution. The fastest possible way is to hide it immediatly with a script.

<div id="hideme"></div>
<script type="text/javascript">
    $("#hideme").hide();
</script>

In this case I would recommend the CSS solution by Vega. But if you need something more complex (like an animation) you can use this approach.

This has some complications (see comments below). If you want this piece of script to really run as fast as possible you can't use jQuery, use native JS only and defer loading of all other scripts.

How schedule build in Jenkins?

In the job configuration one can define various build triggers. With periodically build you can schedule the build by defining the date or day of the week and the time to execute the build.

The format is as follows:

MINUTE (0-59), HOUR (0-23), DAY (1-31), MONTH (1-12), DAY OF THE WEEK (0-6)

The letter H, representing the word Hash can be inserted instead of any of the values, it will calculate the parameter based on the hash code of your project name, this is so that if you are building several projects on your build machine at the same time, lets say midnight each day, they do not all start there build execution at the same time, each project starts its execution at a different minute depending on its hash code. You can also specify the value to be between numbers, i.e. H(0,30) will return the hash code of the project where the possible hashes are 0-30

Examples:

start build daily at 08:30 in the morning, Monday - Friday:

  • 30 08 * * 1-5

weekday daily build twice a day, at lunchtime 12:00 and midnight 00:00, Sunday to Thursday:

  • 00 0,12 * * 0-4

start build daily in the late afternoon between 4:00 p.m. - 4:59 p.m. or 16:00 -16:59 depending on the projects hash:

  • H 16 * * 1-5

start build at midnight:

  • @midnight

or start build at midnight, every Saturday:

  • 59 23 * * 6

every first of every month between 2:00 a.m. - 02:30 a.m. :

  • H(0-30) 02 01 * *

more on CRON expressions

SQL permissions for roles

USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO  ---- Assign Role To users -------  CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username'  ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO 

Update R using RStudio

I would recommend using the Windows package installr to accomplish this. Not only will the package update your R version, but it will also copy and update all of your packages. There is a blog on the subject here. Simply run the following commands in R Studio and follow the prompts:

# installing/loading the package:
if(!require(installr)) {
install.packages("installr"); require(installr)} #load / install+load installr

# using the package:
updateR() # this will start the updating process of your R installation.  It will check for newer versions, and if one is available, will guide you through the decisions you'd need to make.

Slide a layout up from bottom of screen

Here is a solution as an extension of [https://stackoverflow.com/a/46644736/10249774]

Bottom panel is pushing main content upwards

https://imgur.com/a/6nxewE0

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
    android:id="@+id/my_button"
    android:layout_marginTop="10dp"
    android:onClick="onSlideViewButtonClick"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
<LinearLayout
android:id="@+id/main_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main "
    android:textSize="70dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main "
    android:textSize="70dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main "
    android:textSize="70dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main"
    android:textSize="70dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main"
    android:textSize="70dp"/>
</LinearLayout>
<LinearLayout
    android:id="@+id/footer_view"
    android:background="#a6e1aa"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_alignParentBottom="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="footer content"
        android:textSize="40dp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="footer content"
        android:textSize="40dp" />
  </LinearLayout>
</RelativeLayout>

MainActivity:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
private Button myButton;
private View footerView;
private View mainView;
private boolean isUp;
private int anim_duration = 700;

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

    footerView = findViewById(R.id.footer_view);
    mainView = findViewById(R.id.main_view);
    myButton = findViewById(R.id.my_button);

    // initialize as invisible (could also do in xml)
    footerView.setVisibility(View.INVISIBLE);
    myButton.setText("Slide up");
    isUp = false;
}
public void slideUp(View mainView , View footer_view){
    footer_view.setVisibility(View.VISIBLE);
    TranslateAnimation animate_footer = new TranslateAnimation(
            0,                 // fromXDelta
            0,                 // toXDelta
            footer_view.getHeight(),  // fromYDelta
            0);                // toYDelta
    animate_footer.setDuration(anim_duration);
    animate_footer.setFillAfter(true);
    footer_view.startAnimation(animate_footer);

    mainView.setVisibility(View.VISIBLE);
    TranslateAnimation animate_main = new TranslateAnimation(
            0,                 // fromXDelta
            0,                 // toXDelta
            0,  // fromYDelta
            (0-footer_view.getHeight()));                // toYDelta
    animate_main.setDuration(anim_duration);
    animate_main.setFillAfter(true);
    mainView.startAnimation(animate_main);
}
public void slideDown(View mainView , View footer_view){
    TranslateAnimation animate_footer = new TranslateAnimation(
            0,                 // fromXDelta
            0,                 // toXDelta
            0,                 // fromYDelta
            footer_view.getHeight()); // toYDelta
    animate_footer.setDuration(anim_duration);
    animate_footer.setFillAfter(true);
    footer_view.startAnimation(animate_footer);


    TranslateAnimation animate_main = new TranslateAnimation(
            0,                 // fromXDelta
            0,                 // toXDelta
            (0-footer_view.getHeight()),  // fromYDelta
            0);                // toYDelta
    animate_main.setDuration(anim_duration);
    animate_main.setFillAfter(true);
    mainView.startAnimation(animate_main);
}

public void onSlideViewButtonClick(View view) {
    if (isUp) {
        slideDown(mainView , footerView);
        myButton.setText("Slide up");
    } else {
        slideUp(mainView , footerView);
        myButton.setText("Slide down");
    }
    isUp = !isUp;
}
}

Find row in datatable with specific id

Make a string criteria to search for, like this:

string searchExpression = "ID = 5"

Then use the .Select() method of the DataTable object, like this:

DataRow[] foundRows = YourDataTable.Select(searchExpression);

Now you can loop through the results, like this:

int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
    // Get value of Calls here
    result = Int32.TryParse(dr["Calls"], out numberOfCalls);

    // Optionally, you can check the result of the attempted try parse here
    // and do something if you wish
    if(result)
    {
        // Try parse to 32-bit integer worked

    }
    else
    {
        // Try parse to 32-bit integer failed

    }
}

How to jump to top of browser page

_x000D_
_x000D_
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
        document.getElementById("myBtn").style.display = "block";_x000D_
    } else {_x000D_
        document.getElementById("myBtn").style.display = "none";_x000D_
    }_x000D_
   _x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
 _x000D_
     $('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  font-size: 20px;_x000D_
}_x000D_
_x000D_
#myBtn {_x000D_
  display: none;_x000D_
  position: fixed;_x000D_
  bottom: 20px;_x000D_
  right: 30px;_x000D_
  z-index: 99;_x000D_
  font-size: 18px;_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  cursor: pointer;_x000D_
  padding: 15px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
_x000D_
#myBtn:hover {_x000D_
  background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
_x000D_
_x000D_

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

Most certainly, export JAVA_HOME=/usr/bin/java is the culprit. This env var should point to the JDK or JRE installation directory. Googling shows that the best option for MacOS X seems to be export JAVA_HOME=/Library/Java/Home.

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

How to add a default "Select" option to this ASP.NET DropDownList control?

Although it is quite an old question, another approach is to change AppendDataBoundItems property. So the code will be:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                  OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
                  AppendDataBoundItems="True">
     <asp:ListItem Selected="True" Value="0" Text="Select"></asp:ListItem>
</asp:DropDownList>

How can I trigger the click event of another element in ng-click using angularjs?

I took the answer posted by Osiloke (Which was the easiest and most complete imho) and I added a change event listener. Works great! Thanks Osiloke. See below if you are interested:

HTML:

  <div file-button>
        <button class='btn btn-success btn-large'>Select your awesome file</button>
   </div>

Directive:

app.directive('fileButton', function() {
  return {
    link: function(scope, element, attributes) {

      var el = angular.element(element)
      var button = el.children()[0]

      el.css({
        position: 'relative',
        overflow: 'hidden',
        width: button.offsetWidth,
        height: button.offsetHeight
      })

      var fileInput = angular.element('<input id='+scope.file_button_id+' type="file" multiple />')
      fileInput.css({
        position: 'absolute',
        top: 0,
        left: 0,
        'z-index': '2',
        width: '100%',
        height: '100%',
        opacity: '0',
        cursor: 'pointer'
      })

      el.append(fileInput)
      document.getElementById(scope.file_button_id).addEventListener('change', scope.file_button_open, false); 
    }
  }
});

Controller:

$scope.file_button_id = "wo_files";    
$scope.file_button_open = function() 
{
  alert("Files are ready!");
}

How to sort with lambda in Python

Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

Should you use .htm or .html file extension? What is the difference, and which file is correct?

Neither!

If you're asking; "what would a website visitor rather type, htm or html" - it's much better to give them a nice descriptive URL with no extension. If they get used to going to yoursite/contact.html and you change it to yoursite/contact.php you've broken that link. If you use yoursite/contact/ then there's no problem when you switch technology.

How to encode the filename parameter of Content-Disposition header in HTTP?

Just an update since I was trying all this stuff today in response to a customer issue

  • With the exception of Safari configured for Japanese, all browsers our customer tested worked best with filename=text.pdf - where text is a customer value serialized by ASP.Net/IIS in utf-8 without url encoding. For some reason, Safari configured for English would accept and properly save a file with utf-8 Japanese name but that same browser configured for Japanese would save the file with the utf-8 chars uninterpreted. All other browsers tested seemed to work best/fine (regardless of language configuration) with the filename utf-8 encoded without url encoding.
  • I could not find a single browser implementing Rfc5987/8187 at all. I tested with the latest Chrome, Firefox builds plus IE 11 and Edge. I tried setting the header with just filename*=utf-8''texturlencoded.pdf, setting it with both filename=text.pdf; filename*=utf-8''texturlencoded.pdf. Not one feature of Rfc5987/8187 appeared to be getting processed correctly in any of the above.

Image comparison - fast algorithm

Below are three approaches to solving this problem (and there are many others).

  • The first is a standard approach in computer vision, keypoint matching. This may require some background knowledge to implement, and can be slow.

  • The second method uses only elementary image processing, and is potentially faster than the first approach, and is straightforward to implement. However, what it gains in understandability, it lacks in robustness -- matching fails on scaled, rotated, or discolored images.

  • The third method is both fast and robust, but is potentially the hardest to implement.

Keypoint Matching

Better than picking 100 random points is picking 100 important points. Certain parts of an image have more information than others (particularly at edges and corners), and these are the ones you'll want to use for smart image matching. Google "keypoint extraction" and "keypoint matching" and you'll find quite a few academic papers on the subject. These days, SIFT keypoints are arguably the most popular, since they can match images under different scales, rotations, and lighting. Some SIFT implementations can be found here.

One downside to keypoint matching is the running time of a naive implementation: O(n^2m), where n is the number of keypoints in each image, and m is the number of images in the database. Some clever algorithms might find the closest match faster, like quadtrees or binary space partitioning.


Alternative solution: Histogram method

Another less robust but potentially faster solution is to build feature histograms for each image, and choose the image with the histogram closest to the input image's histogram. I implemented this as an undergrad, and we used 3 color histograms (red, green, and blue), and two texture histograms, direction and scale. I'll give the details below, but I should note that this only worked well for matching images VERY similar to the database images. Re-scaled, rotated, or discolored images can fail with this method, but small changes like cropping won't break the algorithm

Computing the color histograms is straightforward -- just pick the range for your histogram buckets, and for each range, tally the number of pixels with a color in that range. For example, consider the "green" histogram, and suppose we choose 4 buckets for our histogram: 0-63, 64-127, 128-191, and 192-255. Then for each pixel, we look at the green value, and add a tally to the appropriate bucket. When we're done tallying, we divide each bucket total by the number of pixels in the entire image to get a normalized histogram for the green channel.

For the texture direction histogram, we started by performing edge detection on the image. Each edge point has a normal vector pointing in the direction perpendicular to the edge. We quantized the normal vector's angle into one of 6 buckets between 0 and PI (since edges have 180-degree symmetry, we converted angles between -PI and 0 to be between 0 and PI). After tallying up the number of edge points in each direction, we have an un-normalized histogram representing texture direction, which we normalized by dividing each bucket by the total number of edge points in the image.

To compute the texture scale histogram, for each edge point, we measured the distance to the next-closest edge point with the same direction. For example, if edge point A has a direction of 45 degrees, the algorithm walks in that direction until it finds another edge point with a direction of 45 degrees (or within a reasonable deviation). After computing this distance for each edge point, we dump those values into a histogram and normalize it by dividing by the total number of edge points.

Now you have 5 histograms for each image. To compare two images, you take the absolute value of the difference between each histogram bucket, and then sum these values. For example, to compare images A and B, we would compute

|A.green_histogram.bucket_1 - B.green_histogram.bucket_1| 

for each bucket in the green histogram, and repeat for the other histograms, and then sum up all the results. The smaller the result, the better the match. Repeat for all images in the database, and the match with the smallest result wins. You'd probably want to have a threshold, above which the algorithm concludes that no match was found.


Third Choice - Keypoints + Decision Trees

A third approach that is probably much faster than the other two is using semantic texton forests (PDF). This involves extracting simple keypoints and using a collection decision trees to classify the image. This is faster than simple SIFT keypoint matching, because it avoids the costly matching process, and keypoints are much simpler than SIFT, so keypoint extraction is much faster. However, it preserves the SIFT method's invariance to rotation, scale, and lighting, an important feature that the histogram method lacked.

Update:

My mistake -- the Semantic Texton Forests paper isn't specifically about image matching, but rather region labeling. The original paper that does matching is this one: Keypoint Recognition using Randomized Trees. Also, the papers below continue to develop the ideas and represent the state of the art (c. 2010):

java.lang.NoClassDefFoundError: Could not initialize class XXX

If you're working on an Android project, make sure you aren't calling any static methods on any Android classes. I'm only using JUnit + Mockito, so maybe some other frameworks might help you avoid the problem altogether, I'm not sure.

My problem was calling Uri.parse(uriString) as part of a static initializer for a unit test. The Uri class is an Android API, which is why the unit test build couldn't find it. I changed this value to null instead and everything went back to normal.

How can I stream webcam video with C#?

If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.

If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the DirectShow.Net library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.

In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.

Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - Programming Microsoft DirectShow - was out of print and going for around $350 for a used copy!

How to use Class<T> in Java?

Just to throw in another example, the generic version of Class (Class<T>) allows one to write generic functions such as the one below.

public static <T extends Enum<T>>Optional<T> optionalFromString(
        @NotNull Class<T> clazz,
        String name
) {
    return Optional<T> opt = Optional.ofNullable(name)
            .map(String::trim)
            .filter(StringUtils::isNotBlank)
            .map(String::toUpperCase)
            .flatMap(n -> {
                try {
                    return Optional.of(Enum.valueOf(clazz, n));
                } catch (Exception e) {
                    return Optional.empty();
                }
            });
}

How do I change the UUID of a virtual disk?

The following worked for me:

  1. run VBoxManage internalcommands sethduuid "VDI/VMDK file" twice (the first time is just to conveniently generate an UUID, you could use any other UUID generation method instead)

  2. open the .vbox file in a text editor

  3. replace the UUID found in Machine uuid="{...}" with the UUID you got when you ran sethduuid the first time

  4. replace the UUID found in HardDisk uuid="{...}" and in Image uuid="{}" (towards the end) with the UUID you got when you ran sethduuid the second time

What exactly is nullptr?

Let me first give you an implementation of unsophisticated nullptr_t

struct nullptr_t 
{
    void operator&() const = delete;  // Can't take address of nullptr

    template<class T>
    inline operator T*() const { return 0; }

    template<class C, class T>
    inline operator T C::*() const { return 0; }
};

nullptr_t nullptr;

nullptr is a subtle example of Return Type Resolver idiom to automatically deduce a null pointer of the correct type depending upon the type of the instance it is assigning to.

int *ptr = nullptr;                // OK
void (C::*method_ptr)() = nullptr; // OK
  • As you can above, when nullptr is being assigned to an integer pointer, a int type instantiation of the templatized conversion function is created. And same goes for method pointers too.
  • This way by leveraging template functionality, we are actually creating the appropriate type of null pointer every time we do, a new type assignment.
  • As nullptr is an integer literal with value zero, you can not able to use its address which we accomplished by deleting & operator.

Why do we need nullptr in the first place?

  • You see traditional NULL has some issue with it as below:

1?? Implicit conversion

char *str = NULL; // Implicit conversion from void * to char *
int i = NULL;     // OK, but `i` is not pointer type

2?? Function calling ambiguity

void func(int) {}
void func(int*){}
void func(bool){}

func(NULL);     // Which one to call?

  • Compilation produces the following error:
error: call to 'func' is ambiguous
    func(NULL);
    ^~~~
note: candidate function void func(bool){}
                              ^
note: candidate function void func(int*){}
                              ^
note: candidate function void func(int){}
                              ^
1 error generated.
compiler exit status 1

3?? Constructor overload

struct String
{
    String(uint32_t)    {   /* size of string */    }
    String(const char*) {       /* string */        }
};

String s1( NULL );
String s2( 5 );

  • In such cases, you need explicit cast (i.e., String s((char*)0)).

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

Wanted to share what caused the error in my case. Spend couple hours to figure this out, so hopefully it will help to save someone some time.

Strangely enough, the error was raised with the Enable drop directory quota setting being enabled for the domain.

enter image description here

I am not the expert and don't know the technical explanation, but unticking the mentioned setting sorted the problem.

Get JSF managed bean by name in any Servlet related class

In a servlet based artifact, such as @WebServlet, @WebFilter and @WebListener, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped by:

Bean bean = (Bean) request.getAttribute("beanName");

and @ManagedBean @SessionScoped by:

Bean bean = (Bean) request.getSession().getAttribute("beanName");

and @ManagedBean @ApplicationScoped by:

Bean bean = (Bean) getServletContext().getAttribute("beanName");

Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null. You'd then need to manually create the bean and use setAttribute("beanName", bean).


If you're able to use CDI @Named instead of the since JSF 2.3 deprecated @ManagedBean, then it's even more easy, particularly because you don't anymore need to manually create the beans:

@Inject
private Bean bean;

Note that this won't work when you're using @Named @ViewScoped because the bean can only be identified by JSF view state and that's only available when the FacesServlet has been invoked. So in a filter which runs before that, accessing an @Injected @ViewScoped will always throw ContextNotActiveException.


Only when you're inside @ManagedBean, then you can use @ManagedProperty:

@ManagedProperty("#{bean}")
private Bean bean;

Note that this doesn't work inside a @Named or @WebServlet or any other artifact. It really works inside @ManagedBean only.


If you're not inside a @ManagedBean, but the FacesContext is readily available (i.e. FacesContext#getCurrentInstance() doesn't return null), you can also use Application#evaluateExpressionGet():

FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);

which can be convenienced as follows:

@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
    FacesContext context = FacesContext.getCurrentInstance();
    return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}

and can be used as follows:

Bean bean = findBean("bean");

See also:

Convert Year/Month/Day to Day of Year in Python

If you have reason to avoid the use of the datetime module, then these functions will work.

def is_leap_year(year):
    """ if year is a leap year return True
        else return False """
    if year % 100 == 0:
        return year % 400 == 0
    return year % 4 == 0

def doy(Y,M,D):
    """ given year, month, day return day of year
        Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
    if is_leap_year(Y):
        K = 1
    else:
        K = 2
    N = int((275 * M) / 9.0) - K * int((M + 9) / 12.0) + D - 30
    return N

def ymd(Y,N):
    """ given year = Y and day of year = N, return year, month, day
        Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """    
    if is_leap_year(Y):
        K = 1
    else:
        K = 2
    M = int((9 * (K + N)) / 275.0 + 0.98)
    if N < 32:
        M = 1
    D = N - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
    return Y, M, D

Read XLSX file in Java

AFAIK there are no xlsx-libraries available yet. But there are some for old xls:

One library is jxls which internally uses the already mentioned POI.

2 other links: Handle Excel files, Java libraries to read and write Excel XLS document files.

What is the difference between 'my' and 'our' in Perl?

#!/usr/bin/perl -l

use strict;

# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'

our $lol = eval {$lol} || 'lol' ;

print $lol;

Is there a list of Pytz Timezones?

The timezone name is the only reliable way to specify the timezone.

You can find a list of timezone names here: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones Note that this list contains a lot of alias names, such as US/Eastern for the timezone that is properly called America/New_York.

If you programatically want to create this list from the zoneinfo database you can compile it from the zone.tab file in the zoneinfo database. I don't think pytz has an API to get them, and I also don't think it would be very useful.

Oracle SELECT TOP 10 records

try

SELECT * FROM users FETCH NEXT 10 ROWS ONLY;

How to Apply Gradient to background view of iOS Swift App

Xcode 11 • Swift 5.1


You can design your own Gradient View as follow:

@IBDesignable
public class Gradient: UIView {
    @IBInspectable var startColor:   UIColor = .black { didSet { updateColors() }}
    @IBInspectable var endColor:     UIColor = .white { didSet { updateColors() }}
    @IBInspectable var startLocation: Double =   0.05 { didSet { updateLocations() }}
    @IBInspectable var endLocation:   Double =   0.95 { didSet { updateLocations() }}
    @IBInspectable var horizontalMode:  Bool =  false { didSet { updatePoints() }}
    @IBInspectable var diagonalMode:    Bool =  false { didSet { updatePoints() }}

    override public class var layerClass: AnyClass { CAGradientLayer.self }

    var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }

    func updatePoints() {
        if horizontalMode {
            gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5)
        } else {
            gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1)
        }
    }
    func updateLocations() {
        gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
    }
    func updateColors() {
        gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
    }
    override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updatePoints()
        updateLocations()
        updateColors()
    }

}

enter image description here

apc vs eaccelerator vs xcache

I tested eAccelerator and XCache with Apache, Lighttp and Nginx with a Wordpress site. eAccelerator wins every time. The bad thing is only the missing packages for Debian and Ubuntu. After a PHP update often the server doesn't work anymore if the eAccelerator modules are not recompiled.

eAccelerator last RC is from 2009/07/15 (0.9.6 rc1) with support for PHP 5.3

How to check that Request.QueryString has a specific value or not in ASP.NET?

You can also try:

if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
   return;

Static vs class functions/variables in Swift classes?

static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods.

class properties will theoretically function in the same way (subclasses can override them), but they're not possible in Swift yet.

A method to count occurrences in a list

You can do something like this to count from a list of things.

IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);

int count = methodNames.Where(x => names.Contains(x)).Count();

To count a single element

string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};

int count = words.Where(x => x.Equals(occur)).Count();

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

What Is It?

This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.

When It Is Thrown

Given an array declared as:

byte[] array = new byte[4];

You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException to be thrown. Remember this when you create and access an array.

Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1 (where Length is total number of items in the array) so this code doesn't work:

array[array.Length] = 0;

Moreover please note that if you have a multidimensional array then you can't use Array.Length for both dimension, you have to use Array.GetLength():

int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
    for (int j=0; j < data.GetLength(1); ++j) {
        data[i, j] = 1;
    }
}

Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color. Each item represents a pixel, indices are from (0, 0) to (imageWidth - 1, imageHeight - 1).

Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
    for (int y = 0; y <= imageHeight; ++y) {
        pixels[x, y] = backgroundColor;
    }
}

This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]:

pixels[imageWidth, imageHeight] = Color.Black;

In another scenario you may get ArgumentOutOfRangeException for this code (for example if you're using GetPixel method on a Bitmap class).

Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can't grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>(), this example adds a new entry to an existing array:

Array.Resize(ref array, array.Length + 1);

Don't forget that valid indices are from 0 to Length - 1. If you simply try to assign an item at Length you'll get IndexOutOfRangeException (this behavior may confuse you if you think they may increase with a syntax similar to Insert method of other collections).

Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:

var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });

In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.

Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:

private static string[] RomanNumbers =
    new string[] { "I", "II", "III", "IV", "V" };

public static string Romanize(int number)
{
    return RomanNumbers[number];
}

Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it's also a well-known convention in use from many years) if they didn't find anything. Let's imagine you have an array of objects comparable with a string. You may think to write this code:

// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
    myArray[Array.IndexOf(myArray, "Debug")]);

// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
    myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);

This will fail if no items in myArray will satisfy search condition because Array.IndexOf() will return -1 and then array access will throw.

Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):

static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
    int[] result = new int[maximum + 1]; // Includes 0

    foreach (int number in numbers)
        ++result[number];

    return result;
}

Of course, it's a pretty terrible implementation but what I want to show is that it'll fail for negative numbers and numbers above maximum.

How it applies to List<T>?

Same cases as array - range of valid indexes - 0 (List's indexes always start with 0) to list.Count - accessing elements outside of this range will cause the exception.

Note that List<T> throws ArgumentOutOfRangeException for the same cases where arrays use IndexOutOfRangeException.

Unlike arrays, List<T> starts empty - so trying to access items of just created list lead to this exception.

var list = new List<int>();

Common case is to populate list with indexing (similar to Dictionary<int, T>) will cause exception:

list[0] = 42; // exception
list.Add(42); // correct

IDataReader and Columns
Imagine you're trying to read data from a database with this code:

using (var connection = CreateConnection()) {
    using (var command = connection.CreateCommand()) {
        command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";

        using (var reader = command.ExecuteReader()) {
            while (reader.Read()) {
                ProcessData(reader.GetString(2)); // Throws!
            }
        }
    }
}

GetString() will throw IndexOutOfRangeException because you're dataset has only two columns but you're trying to get a value from 3rd one (indices are always 0-based).

Please note that this behavior is shared with most IDataReader implementations (SqlDataReader, OleDbDataReader and so on).

You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with

 var data = dr["Colum1"];  // Missing the n in Column1.

This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn't exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of "Colum1".

Others
There is another (documented) case when this exception is thrown: if, in DataView, data column name being supplied to the DataViewSort property is not valid.

How to Avoid

In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you're developing a library), you may need to replace 0 with GetLowerBound(0) and .Length with GetUpperBound(0) (of course if you have parameters of type System.Array, it doesn't apply for T[]). Please note that in this case, upper bound is inclusive then this code:

for (int i=0; i < array.Length; ++i) { }

Should be rewritten like this:

for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }

Please note that this is not allowed (it'll throw InvalidCastException), that's why if your parameters are T[] you're safe about custom lower bound arrays:

void foo<T>(T[] array) { }

void test() {
    // This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
    foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}

Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException or ArgumentOutOfRangeException). In the next example, wrong parameters may cause IndexOutOfRangeException, users of this function may expect this because they're passing an array but it's not always so obvious. I'd suggest to always validate parameters for public functions:

static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
    if (from < 0 || from>= array.Length)
        throw new ArgumentOutOfRangeException("from");

    if (length < 0)
        throw new ArgumentOutOfRangeException("length");

    if (from + length > array.Length)
        throw new ArgumentException("...");

    for (int i=from; i < from + length; ++i)
        array[i] = function(i);
}

If function is private you may simply replace if logic with Debug.Assert():

Debug.Assert(from >= 0 && from < array.Length);

Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert(), throw a proper exception (more descriptive about the problem) or handle that like in this example:

class Table {
    public int SelectedIndex { get; set; }
    public Row[] Rows { get; set; }

    public Row SelectedRow {
        get {
            if (Rows == null)
                throw new InvalidOperationException("...");

            // No or wrong selection, here we just return null for
            // this case (it may be the reason we use this property
            // instead of direct access)
            if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
                return null;

            return Rows[SelectedIndex];
        }
}

Validate Return Values
In one of previous examples we directly used Array.IndexOf() return value. If we know it may fail then it's better to handle that case:

int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }

How to Debug

In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you'll need to debug your code. First of all, read this Eric Lippert's blog post about debugging of small programs, I won't repeat his words here but it's absolutely a must read.

You have source code, you have exception message with a stack trace. Go there, pick right line number and you'll see:

array[index] = newValue;

You found your error, check how index increases. Is it right? Check how array is allocated, is coherent with how index increases? Is it right according to your specifications? If you answer yes to all these questions, then you'll find good help here on StackOverflow but please first check for that by yourself. You'll save your own time!

A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can't figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you'll see exactly which line throws this exception, which array is involved and which index you're trying to use. Really, 99% of the times you'll solve it by yourself in a few minutes.

If this happens in production then you'd better to add assertions in incriminated code, probably we won't see in your code what you can't see by yourself (but you can always bet).

The VB.NET side of the story

Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.

In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.

' declares an array with space for 5 integer 
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer

So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException

For i As Integer = 0 To 4
    myArray(i) = i
Next

The VB.NET rule

This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration

How can I increment a char?

In Python 2.x, just use the ord and chr functions:

>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>> 

Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (ord receives Unicode chars and chr produces them).

But if you're interested in bytes (such as for processing some binary data stream), things are even simpler:

>>> bstr = bytes('abc', 'utf-8')
>>> bstr
b'abc'
>>> bstr[0]
97
>>> bytes([97, 98, 99])
b'abc'
>>> bytes([bstr[0] + 1, 98, 99])
b'bbc'

Checking whether the pip is installed?

You need to run pip list in bash not in python.

pip list
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
argparse (1.4.0)
Beaker (1.3.1)
cas (0.15)
cups (1.0)
cupshelpers (1.0)
decorator (3.0.1)
distribute (0.6.10)
---and other modules

Hibernate SessionFactory vs. JPA EntityManagerFactory

I want to add on this that you can also get Hibernate's session by calling getDelegate() method from EntityManager.

ex:

Session session = (Session) entityManager.getDelegate();

"ssl module in Python is not available" when installing package with pip3

In Ubuntu, this can help:

cd Python-3.6.2
./configure --with-ssl
make
sudo make install

How to run the sftp command with a password from Bash script?

Bash program to wait for sftp to ask for a password then send it along:

#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"Password\"
send \"your_password_here\r\"
interact "

You may need to install expect, change the wording of 'Password' to lowercase 'p' to match what your prompt receives. The problems here is that it exposes your password in plain text in the file as well as in the command history. Which nearly defeats the purpose of having a password in the first place.

BeautifulSoup Grab Visible Webpage Text

I completely respect using Beautiful Soup to get rendered content, but it may not be the ideal package for acquiring the rendered content on a page.

I had a similar problem to get rendered content, or the visible content in a typical browser. In particular I had many perhaps atypical cases to work with such a simple example below. In this case the non displayable tag is nested in a style tag, and is not visible in many browsers that I have checked. Other variations exist such as defining a class tag setting display to none. Then using this class for the div.

<html>
  <title>  Title here</title>

  <body>

    lots of text here <p> <br>
    <h1> even headings </h1>

    <style type="text/css"> 
        <div > this will not be visible </div> 
    </style>


  </body>

</html>

One solution posted above is:

html = Utilities.ReadFile('simple.html')
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
visible_texts = filter(visible, texts)
print(visible_texts)


[u'\n', u'\n', u'\n\n        lots of text here ', u' ', u'\n', u' even headings ', u'\n', u' this will not be visible ', u'\n', u'\n']

This solution certainly has applications in many cases and does the job quite well generally but in the html posted above it retains the text that is not rendered. After searching SO a couple solutions came up here BeautifulSoup get_text does not strip all tags and JavaScript and here Rendered HTML to plain text using Python

I tried both these solutions: html2text and nltk.clean_html and was surprised by the timing results so thought they warranted an answer for posterity. Of course, the speeds highly depend on the contents of the data...

One answer here from @Helge was about using nltk of all things.

import nltk

%timeit nltk.clean_html(html)
was returning 153 us per loop

It worked really well to return a string with rendered html. This nltk module was faster than even html2text, though perhaps html2text is more robust.

betterHTML = html.decode(errors='ignore')
%timeit html2text.html2text(betterHTML)
%3.09 ms per loop

Should I use Vagrant or Docker for creating an isolated environment?

With Vagrant now you can have Docker as a provider. http://docs.vagrantup.com/v2/docker/. Docker provider can be used instead of VirtualBox or VMware.

Please note that you can also use Docker for provisioning with Vagrant. This is very different than using Docker as a provider. http://docs.vagrantup.com/v2/provisioning/docker.html

This means you can replace Chef or Puppet with Docker. You can use combinations like Docker as provider (VM) with Chef as provisioner. Or you can use VirtualBox as provider and Docker as provisioner.

What exactly should be set in PYTHONPATH?

Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:

% python3 -c "import sys;print(sys.path)"
['', 
'/home/username/Documents/DjangoTutorial/mySite', 
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']

where the first path '' denotes the current dir., the 2nd path is via

%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite 

which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.

As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:

% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)

Note that if you start a Python script, the CWD will be the script's directory. For example:

username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages

You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:

username@bud:~/Documents/DjangoTutorial% python3 
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', 
'/home/username/Documents']
>>> from Python import Fibonacci as fibo

or via

% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['', 
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite', 
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo

Fully backup a git repo?

Expanding on the great answers by KingCrunch and VonC

I combined them both:

git clone --mirror [email protected]/reponame reponame.git
cd reponame.git
git bundle create reponame.bundle --all

After that you have a file called reponame.bundle that can be easily copied around. You can then create a new normal git repository from that using git clone reponame.bundle reponame.

Note that git bundle only copies commits that lead to some reference (branch or tag) in the repository. So tangling commits are not stored to the bundle.

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

How can I escape white space in a bash loop list?

I use

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in $( find "$1" -type d ! -path "$1" )
do
  echo $f
done
IFS=$SAVEIFS

Wouldn't that be enough?
Idea taken from http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html

MySQL INNER JOIN select only one row from second table

SELECT u.*, p.*, max(p.date)
FROM payments p
JOIN users u ON u.id=p.user_id AND u.package = 1
GROUP BY u.id
ORDER BY p.date DESC

Check out this sqlfiddle

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

The problem is that you're calling List<T>.Reverse() which returns void.

You could either do:

List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();

or:

IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();

The latter is more expensive, as reversing an arbitrary IEnumerable<T> involves buffering all of the data and then yielding it all - whereas List<T> can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>() extension method, instead of the List<T>.Reverse() instance method.)

More efficient yet, you could use:

string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();

This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.

NPM: npm-cli.js not found when running npm

On Windows 10:

  1. Press windows key, type edit the system environment variables then enter.
  2. Click environment variables...
  3. On the lower half of the window that opened with title Environment Variables there you will see a table titled System Variables, with two columns, the first one titled variable.
  4. Find the row with variable Path and click it.
  5. Click edit which will open a window titled Edit evironment variable.
  6. Here if you find

C:\Program Files\nodejs\node_modules\npm\bin

select it, and click edit button to your right, then edit the field to the path where you have the nodejs folder, in my case it was just shortening it to :

C:\Program Files\nodejs

Then I closed all my cmd or powershell terminals, opened them again and npm was working.

Android ListView Divider

Folks, here's why you should use 1px instead of 1dp or 1dip: if you specify 1dp or 1dip, Android will scale that down. On a 120dpi device, that becomes something like 0.75px translated, which rounds to 0. On some devices, that translates to 2-3 pixels, and it usually looks ugly or sloppy

For dividers, 1px is the correct height if you want a 1 pixel divider and is one of the exceptions for the "everything should be dip" rule. It'll be 1 pixel on all screens. Plus, 1px usually looks better on hdpi and above screens

"It's not 2012 anymore" edit: you may have to switch over to dp/dip starting at a certain screen density

How to compile makefile using MinGW?

I found a very good example here: https://bigcode.wordpress.com/2016/12/20/compiling-a-very-basic-mingw-windows-hello-world-executable-in-c-with-a-makefile/

It is a simple Hello.c (you can use c++ with g++ instead of gcc) using the MinGW on windows.

The Makefile looking like:

EXECUTABLE = src/Main.cpp

CC = "C:\MinGW\bin\g++.exe"
LDFLAGS = -lgdi32

src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)

all: myprog

myprog: $(obj)
    $(CC) -o $(EXECUTABLE) $^ $(LDFLAGS)

.PHONY: clean
clean:
    del $(obj) $(EXECUTABLE)

Enter triggers button click

By pressing 'Enter' on focused <input type="text"> you trigger 'click' event on the first positioned element: <button> or <input type="submit">. If you press 'Enter' in <textarea>, you just make a new text line.

See the example here.

Your code prevents to make a new text line in <textarea>, so you have to catch key press only for <input type="text">.

But why do you need to press Enter in text field? If you want to submit form by pressing 'Enter', but the <button> must stay the first in the layout, just play with the markup: put the <input type="submit"> code before the <button> and use CSS to save the layout you need.

Catching 'Enter' and saving markup:

$('input[type="text"]').keypress(function (e) {
    var code = e.keyCode || e.which;
    if (code === 13)
    e.preventDefault();
    $("form").submit(); /*add this, if you want to submit form by pressing `Enter`*/
});

Drawing a dot on HTML5 canvas

This should do the job

//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");

//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

If you are using the TestCaseSource attribute, ensure the source exists and respects the documentation, otherwise your tests will not be discovered.

How to do encryption using AES in Openssl

Check out this link it has a example code to encrypt/decrypt data using AES256CBC using EVP API.

https://github.com/saju/misc/blob/master/misc/openssl_aes.c

Also you can check the use of AES256 CBC in a detailed open source project developed by me at https://github.com/llubu/mpro

The code is detailed enough with comments and if you still need much explanation about the API itself i suggest check out this book Network Security with OpenSSL by Viega/Messier/Chandra (google it you will easily find a pdf of this..) read chapter 6 which is specific to symmetric ciphers using EVP API.. This helped me a lot actually understanding the reasons behind using various functions and structures of EVP.

and if you want to dive deep into the Openssl crypto library, i suggest download the code from the openssl website (the version installed on your machine) and then look in the implementation of EVP and aeh api implementation.

One more suggestion from the code you posted above i see you are using the api from aes.h instead use EVP. Check out the reason for doing this here OpenSSL using EVP vs. algorithm API for symmetric crypto nicely explained by Daniel in one of the question asked by me..

Add JavaScript object to JavaScript object

var jsonIssues = [
 {ID:'1',Name:'Some name',Notes:'NOTES'},
 {ID:'2',Name:'Some name 2',Notes:'NOTES 2'}
];

If you want to add to the array then you can do this

jsonIssues[jsonIssues.length] = {ID:'3',Name:'Some name 3',Notes:'NOTES 3'};

Or you can use the push technique that the other guy posted, which is also good.

jQuery - keydown / keypress /keyup ENTERKEY detection?

JavaScript/jQuery

$("#entersomething").keyup(function(e){ 
    var code = e.key; // recommended to use e.key, it's normalized across devices and languages
    if(code==="Enter") e.preventDefault();
    if(code===" " || code==="Enter" || code===","|| code===";"){
        $("#displaysomething").html($(this).val());
    } // missing closing if brace
});

HTML

<input id="entersomething" type="text" /> <!-- put a type attribute in -->
<div id="displaysomething"></div>

Laravel-5 how to populate select box from database with id value and name value

To populate the drop-down select box in laravel we have to follow the below steps.

From controller we have to get the value like this:

 public function addCustomerLoyaltyCardDetails(){
        $loyalityCardMaster = DB::table('loyality_cards')->pluck('loyality_card_id', 'loyalityCardNumber');
        return view('admin.AddCustomerLoyaltyCardScreen')->with('loyalityCardMaster',$loyalityCardMaster);
    }

And the same we can display in view:

 <select class="form-control" id="loyalityCardNumber" name="loyalityCardNumber" >
       @foreach ($loyalityCardMaster as $id => $name)                                     
            <option value="{{$name}}">{{$id}}</option>
       @endforeach
 </select>

This key value in drop down you can use as per your requirement. Hope it may help someone.

how to bold words within a paragraph in HTML/CSS?

Although your answer has many solutions I think this is a great way to save lines of code. Try using spans which is great for situations like yours.

  1. Create a class for making any item bold. So for paragraph text it would be
span.bold(This name can be anything do not include parenthesis) {
   font-weight: bold;
}
  1. In your html you can access that class like by using the span tags and adding a class of bold or whatever name you have chosen

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.

Copy struct to struct in C

I think you should cast the pointers to (void *) to get rid of the warnings.

memcpy((void *)&RTCclk, (void *)&RTCclkBuffert, sizeof RTCclk);

Also you have use sizeof without brackets, you can use this with variables but if RTCclk was defined as an array, sizeof of will return full size of the array. If you use use sizeof with type you should use with brackets.

sizeof(struct RTCclk)

How to return part of string before a certain character?

And note that first argument of subString is 0 based while second is one based.

Example:

String str= "0123456";
String sbstr= str.substring(0,5);

Output will be sbstr= 01234 and not sbstr = 012345

HTTP status code 0 - Error Domain=NSURLErrorDomain?

In iOS SDK When your API call time-outs, you get status 0 for that.

JSON to string variable dump

Here is the code I use. You should be able to adapt it to your needs.

function process_test_json() {
  var jsonDataArr = { "Errors":[],"Success":true,"Data":{"step0":{"collectionNameStr":"dei_ideas_org_Private","url_root":"http:\/\/192.168.1.128:8500\/dei-ideas_org\/","collectionPathStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwrootchapter0-2\\verity_collections\\","writeVerityLastFileNameStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot\\chapter0-2\\VerityLastFileName.txt","doneFlag":false,"state_dbrec":{},"errorMsgStr":"","fileroot":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot"}}};

  var htmlStr= "<h3 class='recurse_title'>[jsonDataArr] struct is</h3> " + recurse( jsonDataArr );
  alert( htmlStr );
  $( document.createElement('div') ).attr( "class", "main_div").html( htmlStr ).appendTo('div#out');
  $("div#outAsHtml").text( $("div#out").html() ); 
}
function recurse( data ) {
  var htmlRetStr = "<ul class='recurseObj' >"; 
  for (var key in data) {
        if (typeof(data[key])== 'object' && data[key] != null) {
            htmlRetStr += "<li class='keyObj' ><strong>" + key + ":</strong><ul class='recurseSubObj' >";
            htmlRetStr += recurse( data[key] );
            htmlRetStr += '</ul  ></li   >';
        } else {
            htmlRetStr += ("<li class='keyStr' ><strong>" + key + ': </strong>&quot;' + data[key] + '&quot;</li  >' );
        }
  };
  htmlRetStr += '</ul >';    
  return( htmlRetStr );
}

</script>
</head><body>
<button onclick="process_test_json()" >Run process_test_json()</button>
<div id="out"></div>
<div id="outAsHtml"></div>
</body>

Transposing a 2D-array in JavaScript

I didn't find an answer that satisfied me, so I wrote one myself, I think it is easy to understand and implement and suitable for all situations.

    transposeArray: function (mat) {
        let newMat = [];
        for (let j = 0; j < mat[0].length; j++) {  // j are columns
            let temp = [];
            for (let i = 0; i < mat.length; i++) {  // i are rows
                temp.push(mat[i][j]);  // so temp will be the j(th) column in mat
            }
            newMat.push(temp);  // then just push every column in newMat
        }
        return newMat;
    }

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

In my case, .composer was owned by root, so I did sudo rm -fr .composer and then my global require worked.

Be warned! You don't wanna use that command if you are not sure what you are doing.

How can I get the browser's scrollbar sizes?

This is a great answer: https://stackoverflow.com/a/986977/5914609

However in my case it did not work. And i spent hours searching for the solution.
Finally i've returned to above code and added !important to each style. And it worked.
I can not add comments below the original answer. So here is the fix:

function getScrollBarWidth () {
  var inner = document.createElement('p');
  inner.style.width = "100% !important";
  inner.style.height = "200px !important";

  var outer = document.createElement('div');
  outer.style.position = "absolute !important";
  outer.style.top = "0px !important";
  outer.style.left = "0px !important";
  outer.style.visibility = "hidden !important";
  outer.style.width = "200px !important";
  outer.style.height = "150px !important";
  outer.style.overflow = "hidden !important";
  outer.appendChild (inner);

  document.body.appendChild (outer);
  var w1 = inner.offsetWidth;
  outer.style.overflow = 'scroll !important';
  var w2 = inner.offsetWidth;
  if (w1 == w2) w2 = outer.clientWidth;

  document.body.removeChild (outer);

  return (w1 - w2);
};

PHP: Split a string in to an array foreach char

Since str_split() function is not multibyte safe, an easy solution to split UTF-8 encoded string is to use preg_split() with u (PCRE_UTF8) modifier.

preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )

What's the difference between a word and byte?

BYTE

I am trying to answer this question from C++ perspective.

The C++ standard defines ‘byte’ as “Addressable unit of data large enough to hold any member of the basic character set of the execution environment.”

What this means is that the byte consists of at least enough adjacent bits to accommodate the basic character set for the implementation. That is, the number of possible values must equal or exceed the number of distinct characters. In the United States, the basic character sets are usually the ASCII and EBCDIC sets, each of which can be accommodated by 8 bits. Hence it is guaranteed that a byte will have at least 8 bits.

In other words, a byte is the amount of memory required to store a single character.

If you want to verify ‘number of bits’ in your C++ implementation, check the file ‘limits.h’. It should have an entry like below.

#define CHAR_BIT      8         /* number of bits in a char */

WORD

A Word is defined as specific number of bits which can be processed together (i.e. in one attempt) by the machine/system. Alternatively, we can say that Word defines the amount of data that can be transferred between CPU and RAM in a single operation.

The hardware registers in a computer machine are word sized. The Word size also defines the largest possible memory address (each memory address points to a byte sized memory).

Note – In C++ programs, the memory addresses points to a byte of memory and not to a word.

How do I insert datetime value into a SQLite database?

This may not be the most popular or efficient method, but I tend to forgo strong datatypes in SQLite since they are all essentially dumped in as strings anyway.

I've written a thin C# wrapper around the SQLite library before (when using SQLite with C#, of course) to handle insertions and extractions to and from SQLite as if I were dealing with DateTime objects.

iFrame src change event detection?

Since version 3.0 of Jquery you might get an error

TypeError: url.indexOf is not a function

Which can be easily fix by doing

$('#iframe').on('load', function() {
    alert('frame has (re)loaded ');
});

CustomErrors mode="Off"

"Off" is case-sensitive.

Check if the "O" is in uppercase in your web.config file, I've suffered that a few times (as simple as it sounds)

Trimming text strings in SQL Server 2008

I would try something like this for a Trim function that takes into account all white-space characters defined by the Unicode Standard (LTRIM and RTRIM do not even trim new-line characters!):

_x000D_
_x000D_
IF OBJECT_ID(N'dbo.IsWhiteSpace', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.IsWhiteSpace;_x000D_
GO_x000D_
_x000D_
-- Determines whether a single character is white-space or not (according to the UNICODE standard)._x000D_
CREATE FUNCTION dbo.IsWhiteSpace(@c NCHAR(1)) RETURNS BIT_x000D_
BEGIN_x000D_
 IF (@c IS NULL) RETURN NULL;_x000D_
 DECLARE @WHITESPACE NCHAR(31);_x000D_
 SELECT @WHITESPACE = ' ' + NCHAR(13) + NCHAR(10) + NCHAR(9) + NCHAR(11) + NCHAR(12) + NCHAR(133) + NCHAR(160) + NCHAR(5760) + NCHAR(8192) + NCHAR(8193) + NCHAR(8194) + NCHAR(8195) + NCHAR(8196) + NCHAR(8197) + NCHAR(8198) + NCHAR(8199) + NCHAR(8200) + NCHAR(8201) + NCHAR(8202) + NCHAR(8232) + NCHAR(8233) + NCHAR(8239) + NCHAR(8287) + NCHAR(12288) + NCHAR(6158) + NCHAR(8203) + NCHAR(8204) + NCHAR(8205) + NCHAR(8288) + NCHAR(65279);_x000D_
 IF (CHARINDEX(@c, @WHITESPACE) = 0) RETURN 0;_x000D_
 RETURN 1;_x000D_
END_x000D_
GO_x000D_
_x000D_
IF OBJECT_ID(N'dbo.Trim', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.Trim;_x000D_
GO_x000D_
_x000D_
-- Removes all leading and tailing white-space characters. NULL is converted to an empty string._x000D_
CREATE FUNCTION dbo.Trim(@TEXT NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)_x000D_
BEGIN_x000D_
 -- Check tiny strings (NULL, 0 or 1 chars)_x000D_
 IF @TEXT IS NULL RETURN N'';_x000D_
 DECLARE @TEXTLENGTH INT = LEN(@TEXT);_x000D_
 IF @TEXTLENGTH < 2 BEGIN_x000D_
  IF (@TEXTLENGTH = 0) RETURN @TEXT;_x000D_
  IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1)) = 1) RETURN '';_x000D_
  RETURN @TEXT;_x000D_
 END_x000D_
 -- Check whether we have to LTRIM/RTRIM_x000D_
 DECLARE @SKIPSTART INT;_x000D_
 SELECT @SKIPSTART = dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1));_x000D_
 DECLARE @SKIPEND INT;_x000D_
 SELECT @SKIPEND = dbo.IsWhiteSpace(SUBSTRING(@TEXT, @TEXTLENGTH, 1));_x000D_
 DECLARE @INDEX INT;_x000D_
 IF (@SKIPSTART = 1) BEGIN_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- FULLTRIM_x000D_
   -- Determine start white-space length_x000D_
   SELECT @INDEX = 2;_x000D_
   WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise assign index as @SKIPSTART_x000D_
    SELECT @SKIPSTART = @INDEX;_x000D_
    -- Increase character index_x000D_
    SELECT @INDEX = (@INDEX + 1);_x000D_
   END_x000D_
   -- Return '' if the whole string is white-space_x000D_
   IF (@SKIPSTART = (@TEXTLENGTH - 1)) RETURN ''; _x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   END_x000D_
   -- Return trimmed string_x000D_
   RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART - @SKIPEND);_x000D_
  END _x000D_
  -- LTRIM_x000D_
  -- Determine start white-space length_x000D_
  SELECT @INDEX = 2;_x000D_
  WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
   -- Stop loop if no white-space_x000D_
   IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
   -- Otherwise assign index as @SKIPSTART_x000D_
   SELECT @SKIPSTART = @INDEX;_x000D_
   -- Increase character index_x000D_
   SELECT @INDEX = (@INDEX + 1);_x000D_
  END_x000D_
  -- Return trimmed string_x000D_
  RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART);_x000D_
 END ELSE BEGIN_x000D_
  -- RTRIM_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   END_x000D_
   -- Return trimmed string_x000D_
   RETURN SUBSTRING(@TEXT, 1, @TEXTLENGTH - @SKIPEND);_x000D_
  END _x000D_
 END_x000D_
 -- NO TRIM_x000D_
 RETURN @TEXT;_x000D_
END_x000D_
GO
_x000D_
_x000D_
_x000D_

Check if string begins with something?

A little more reusable function:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

How to update values using pymongo?

Something I did recently, hope it helps. I have a list of dictionaries and wanted to add a value to some existing documents.

for item in my_list:
    my_collection.update({"_id" : item[key] }, {"$set" : {"New_col_name" :item[value]}})

Logging POST data from $request_body

FWIW, this config worked for me:

location = /logpush.html {
  if ($request_method = POST) {
    access_log /var/log/nginx/push.log push_requests;
    proxy_pass $scheme://127.0.0.1/logsink;
    break;
  }   
  return 200 $scheme://$host/serviceup.html;
}   
#
location /logsink {
  return 200;
}

Using curl POST with variables defined in bash script functions

Existing answers point out that curl can post data from a file, and employ heredocs to avoid excessive quote escaping and clearly break the JSON out onto new lines. However there is no need to define a function or capture output from cat, because curl can post data from standard input. I find this form very readable:

curl -X POST -H 'Content-Type:application/json' --data '$@-' ${API_URL} << EOF
{
  "account": {
    "email": "$email",
    "screenName": "$screenName",
    "type": "$theType",
    "passwordSettings": {
      "password": "$password",
      "passwordConfirm": "$password"
    }
  },
  "firstName": "$firstName",
  "lastName": "$lastName",
  "middleName": "$middleName",
  "locale": "$locale",
  "registrationSiteId": "$registrationSiteId",
  "receiveEmail": "$receiveEmail",
  "dateOfBirth": "$dob",
  "mobileNumber": "$mobileNumber",
  "gender": "$gender",
  "fuelActivationDate": "$fuelActivationDate",
  "postalCode": "$postalCode",
  "country": "$country",
  "city": "$city",
  "state": "$state",
  "bio": "$bio",
  "jpFirstNameKana": "$jpFirstNameKana",
  "jpLastNameKana": "$jpLastNameKana",
  "height": "$height",
  "weight": "$weight",
  "distanceUnit": "MILES",
  "weightUnit": "POUNDS",
  "heightUnit": "FT/INCHES"
}
EOF

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

How to reload apache configuration for a site without restarting apache?

If you are using Ubuntu server, you can use systemctl

systemctl reload apache2

How to move the cursor word by word in the OS X Terminal

If you check Use option as meta key in the keyboard tab of the preferences, then the default emacs style commands for forward- and backward-word and ?F (Alt+F) and ?B (Alt+B) respectively.

I'd recommend reading From Bash to Z-Shell. If you want to increase your bash/zsh prowess!

Create a file if one doesn't exist - C

If fptr is NULL, then you don't have an open file. Therefore, you can't freopen it, you should just fopen it.

FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
    fptr = fopen("scores.dat", "wb");
}

note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.

A complete example

int main()
{
    FILE *fptr;
    char there_was_error = 0;
    char opened_in_read  = 1;
    fptr = fopen("scores.dat", "rb+");
    if(fptr == NULL) //if file does not exist, create it
    {
        opened_in_read = 0;
        fptr = fopen("scores.dat", "wb");
        if (fptr == NULL)
            there_was_error = 1;
    }
    if (there_was_error)
    {
        printf("Disc full or no permission\n");
        return EXIT_FAILURE;
    }
    if (opened_in_read)
        printf("The file is opened in read mode."
               " Let's read some cached data\n");
    else
        printf("The file is opened in write mode."
               " Let's do some processing and cache the results\n");
    return EXIT_SUCCESS;
}

Android Device Chooser -- device not showing up

Here is my checklist when my device is not shown:

  1. Make sure "USB debugging is turned in setting>Developer options.
  2. Check status bar on your device. It tells you if your phone is connected as Media Device (MTP) or Send images (PTP). My device is only listed when PTP is selected.
  3. Turn of windows firewall.
  4. Turn of any proxy programs ran on whole windows ports.
  5. And final solution to stop adb.exe from windows task manager and wait some seconds to restart automatically.

Tkinter: "Python may not be configured for Tk"

sudo apt-get install python3-tk

How to use NSURLConnection to connect with SSL for an untrusted cert?

If you're unwilling (or unable) to use private APIs, there's an open source (BSD license) library called ASIHTTPRequest that provides a wrapper around the lower-level CFNetwork APIs. They recently introduced the ability to allow HTTPS connections using self-signed or untrusted certificates with the -setValidatesSecureCertificate: API. If you don't want to pull in the whole library, you could use the source as a reference for implementing the same functionality yourself.

Delete all lines starting with # or ; in Notepad++

Maybe you should try

^[#;].*$

^ matches the beggining, $ the end.

Nested Recycler view height doesn't wrap its content

The code up above doesn't work well when you need to make your items "wrap_content", because it measures both items height and width with MeasureSpec.UNSPECIFIED. After some troubles I've modified that solution so now items can expand. The only difference is that it provides parents height or width MeasureSpec depends on layout orientation.

public class MyLinearLayoutManager extends LinearLayoutManager {

public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {


        if (getOrientation() == HORIZONTAL) {

            measureScrapChild(recycler, i,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    heightSpec,
                    mMeasuredDimension);

            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            measureScrapChild(recycler, i,
                    widthSpec,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }
    switch (widthMode) {
        case View.MeasureSpec.EXACTLY:
            width = widthSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    switch (heightMode) {
        case View.MeasureSpec.EXACTLY:
            height = heightSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    setMeasuredDimension(width, height);
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                               int heightSpec, int[] measuredDimension) {
    View view = recycler.getViewForPosition(position);
    recycler.bindViewToPosition(view, position);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                getPaddingLeft() + getPaddingRight(), p.width);
        int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                getPaddingTop() + getPaddingBottom(), p.height);
        view.measure(childWidthSpec, childHeightSpec);
        measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
        measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
        recycler.recycleView(view);
    }
}
}

memcpy() vs memmove()

The difference between memcpy and memmove is that

  1. in memmove, the source memory of specified size is copied into buffer and then moved to destination. So if the memory is overlapping, there are no side effects.

  2. in case of memcpy(), there is no extra buffer taken for source memory. The copying is done directly on the memory so that when there is memory overlap, we get unexpected results.

These can be observed by the following code:

//include string.h, stdio.h, stdlib.h
int main(){
  char a[]="hare rama hare rama";

  char b[]="hare rama hare rama";

  memmove(a+5,a,20);
  puts(a);

  memcpy(b+5,b,20);
  puts(b);
}

Output is:

hare hare rama hare rama
hare hare hare hare hare hare rama hare rama

ASP.NET MVC get textbox input value

you can do it so simple:

First: For Example in Models you have User.cs with this implementation

public class User
 {
   public string username { get; set; }
   public string age { get; set; }
 } 

We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this

public ActionResult Add()
{
  var model = new User();
  return View(model);
}

When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:

@model MyApp.Models.Student
@using (Html.BeginForm()) 
 {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.username, htmlAttributes: new { 
                           @class = "control-label col-md-2" })
            <div class="col-md-10">
                 @Html.EditorFor(model => model.username, new { 
                                 htmlAttributes = new { @class = "form-
                                 control" } })
                 @Html.ValidationMessageFor(model => model.userame, "", 
                                            new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.age, htmlAttributes: new { @class 
                           = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.age, new { htmlAttributes = 
                                new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.age, "", new { 
                                           @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" 
                 />
            </div>
        </div>
   </div>
}

So on button submit you will use it like this

[HttpPost]
public ActionResult Add(User user)
 {
   // now user.username has the value that user entered on form
 }

How to get $(this) selected option in jQuery?

Best and shortest way in my opinion for onchange events on the dropdown to get the selected option:

$('option:selected',this);

to get the value attribute:

$('option:selected',this).attr('value');

to get the shown part between the tags:

$('option:selected',this).text();

In your sample:

$("#select-id").change(function(){
  var cur_value = $('option:selected',this).text();
});

Rails select helper - Default selected value, how?

This should work for you. It just passes {:value => params[:pid] } to the html_options variable.

<%= f.select :project_id, @project_select, {}, {:value => params[:pid] } %>

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

The fields of your object have in turn their fields, some of which do not implement Serializable. In your case the offending class is TransformGroup. How to solve it?

  • if the class is yours, make it Serializable
  • if the class is 3rd party, but you don't need it in the serialized form, mark the field as transient
  • if you need its data and it's third party, consider other means of serialization, like JSON, XML, BSON, MessagePack, etc. where you can get 3rd party objects serialized without modifying their definitions.

Rails :include vs. :joins

.joins will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again

:includes will eager load the included associations and add them in memory. :includes loads all the included tables attributes. If you call associations on include query result, it will not fire any queries

How to divide flask app into multiple py files?

You can use simple trick which is import flask app variable from main inside another file, like:

test-routes.py

from __main__ import app

@app.route('/test', methods=['GET'])
def test():
    return 'it works!'

and in your main files, where you declared flask app, import test-routes, like:

app.py

from flask import Flask, request, abort

app = Flask(__name__)

# import declared routes
import test-routes

It works from my side.

Converting java.util.Properties to HashMap<String,String>

The problem is that Properties implements Map<Object, Object>, whereas the HashMap constructor expects a Map<? extends String, ? extends String>.

This answer explains this (quite counter-intuitive) decision. In short: before Java 5, Properties implemented Map (as there were no generics back then). This meant that you could put any Object in a Properties object. This is still in the documenation:

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead.

To maintain compatibility with this, the designers had no other choice but to make it inherit Map<Object, Object> in Java 5. It's an unfortunate result of the strive for full backwards compatibility which makes new code unnecessarily convoluted.

If you only ever use string properties in your Properties object, you should be able to get away with an unchecked cast in your constructor:

Map<String, String> map = new HashMap<String, String>( (Map<String, String>) properties);

or without any copies:

Map<String, String> map = (Map<String, String>) properties;

How to access to a child method from the parent in vue.js

Parent-Child communication in VueJS

Given a root Vue instance is accessible by all descendants via this.$root, a parent component can access child components via the this.$children array, and a child component can access it's parent via this.$parent, your first instinct might be to access these components directly.

The VueJS documentation warns against this specifically for two very good reasons:

  • It tightly couples the parent to the child (and vice versa)
  • You can't rely on the parent's state, given that it can be modified by a child component.

The solution is to use Vue's custom event interface

The event interface implemented by Vue allows you to communicate up and down the component tree. Leveraging the custom event interface gives you access to four methods:

  1. $on() - allows you to declare a listener on your Vue instance with which to listen to events
  2. $emit() - allows you to trigger events on the same instance (self)

Example using $on() and $emit():

_x000D_
_x000D_
const events = new Vue({}),_x000D_
    parentComponent = new Vue({_x000D_
      el: '#parent',_x000D_
      ready() {_x000D_
        events.$on('eventGreet', () => {_x000D_
          this.parentMsg = `I heard the greeting event from Child component ${++this.counter} times..`;_x000D_
        });_x000D_
      },_x000D_
      data: {_x000D_
        parentMsg: 'I am listening for an event..',_x000D_
        counter: 0_x000D_
      }_x000D_
    }),_x000D_
    childComponent = new Vue({_x000D_
      el: '#child',_x000D_
      methods: {_x000D_
      greet: function () {_x000D_
        events.$emit('eventGreet');_x000D_
        this.childMsg = `I am firing greeting event ${++this.counter} times..`;_x000D_
      }_x000D_
    },_x000D_
    data: {_x000D_
      childMsg: 'I am getting ready to fire an event.',_x000D_
      counter: 0_x000D_
    }_x000D_
  });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script>_x000D_
_x000D_
<div id="parent">_x000D_
  <h2>Parent Component</h2>_x000D_
  <p>{{parentMsg}}</p>_x000D_
</div>_x000D_
_x000D_
<div id="child">_x000D_
  <h2>Child Component</h2>_x000D_
  <p>{{childMsg}}</p>_x000D_
  <button v-on:click="greet">Greet</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Answer taken from the original post: Communicating between components in VueJS

Undefined reference to `sin`

You need to link with the math library, libm:

$ gcc -Wall foo.c -o foo -lm 

How to enable PHP's openssl extension to install Composer?

After editting the "right" files (all php.ini's). i had still the issue. My solution was:

  1. Adding a System variable: OPENSSL_CONF

    the value of OPENSSL_CONF should be the openssl.cnf file of your current php version.

for me it was:

  • C:\wamp\bin\php\php5.6.12\extras\ssl\openssl.cnf

-> Restart WAMP -> should work now

Source: http://php.net/manual/en/openssl.installation.php

Difference between clustered and nonclustered index

A comparison of a non-clustered index with a clustered index with an example

As an example of a non-clustered index, let’s say that we have a non-clustered index on the EmployeeID column. A non-clustered index will store both the value of the

EmployeeID

AND a pointer to the row in the Employee table where that value is actually stored. But a clustered index, on the other hand, will actually store the row data for a particular EmployeeID – so if you are running a query that looks for an EmployeeID of 15, the data from other columns in the table like

EmployeeName, EmployeeAddress, etc

. will all actually be stored in the leaf node of the clustered index itself.

This means that with a non-clustered index extra work is required to follow that pointer to the row in the table to retrieve any other desired values, as opposed to a clustered index which can just access the row directly since it is being stored in the same order as the clustered index itself. So, reading from a clustered index is generally faster than reading from a non-clustered index.

Can I use a binary literal in C or C++?

You can use binary literals. They are standardized in C++14. For example,

int x = 0b11000;

Support in GCC

Support in GCC began in GCC 4.3 (see https://gcc.gnu.org/gcc-4.3/changes.html) as extensions to the C language family (see https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html#C-Extensions), but since GCC 4.9 it is now recognized as either a C++14 feature or an extension (see Difference between GCC binary literals and C++14 ones?)

Support in Visual Studio

Support in Visual Studio started in Visual Studio 2015 Preview (see https://www.visualstudio.com/news/vs2015-preview-vs#C++).

sqlalchemy filter multiple columns

You can simply call filter multiple times:

query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
                                 filter(User.lastname.like(searchVar2))

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I had this issue when I was trying to render an object on a child component that was receiving props.

I fixed this when I realized that my code was trying to render an object and not the object key's value that I was trying to render.

Read a HTML file into a string variable in memory

You can do it the simple way:

string pathToHTMLFile = @"C:\temp\someFile.html";
string htmlString = File.ReadAllText(pathToHTMLFile);

Or you could stream it in with FileStream/StreamReader:

using (FileStream fs = File.Open(pathToHTMLFile, FileMode.Open, FileAccess.ReadWrite))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        htmlString = sr.ReadToEnd();
    }
}

This latter method allows you to open the file while still permitting others to perform Read/Write operations on the file. I can't imagine an HTML file being very big, but it has the added benefit of streaming the file instead of capturing it as one large chunk like the first method.

Gradle version 2.2 is required. Current version is 2.10

I Had similar issue. Every project has his own gradle folder, check if in your project root there's another gradle folder:

/my_projects_root_folder/project/gradle
/my_projects_root_folder/gradle

If so, in every folder you'll find /gradle/wrapper/gradle-wrapper.properties.

Check if in /my_projects_root_folder/gradle/gradle-wrapper.properties gradle version at least match /my_projects_root_folder/ project/ gradle/ gradle-wrapper.properties gradle version

Or just delete/rename your /my_projects_root_folder/gradle and restart android studio and let Gradle sync work and download required gradle.

How to set div width using ng-style

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

How to use the pass statement?

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

Variable is accessed within inner class. Needs to be declared final

As @Veger said, you can make it final so that the variable can be used in the inner class.

final ViewPager pager = (ViewPager) findViewById(R.id.fieldspager);

I called it pager rather than mPager because you are using it as a local variable in the onCreate method. The m prefix is cusomarily reserved for class member variables (i.e. variables that are declared at the beginning of the class and are available to all class methods).

If you actually do need a class member variable, it doesn't work to make it final because you can't use findViewById to set its value until onCreate. The solution is to not use an anonymous inner class. This way the mPager variable doesn't need to be declared final and can be used throughout the class.

public class MainActivity extends AppCompatActivity {

    private ViewPager mPager;
    private Button mButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // ...

        mPager = (ViewPager) findViewById(R.id.fieldspager);

        // ...

        mButton.setOnClickListener(myButtonClickHandler);
    }


    View.OnClickListener myButtonClickHandler = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mPager.setCurrentItem(2, true);
        }
    };
}

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

How to use enums as flags in C++?

As above(Kai) or do the following. Really enums are "Enumerations", what you want to do is have a set, therefore you should really use stl::set

enum AnimalFlags
{
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8
};

int main(void)
{
    AnimalFlags seahawk;
    //seahawk= CanFly | EatsFish | Endangered;
    seahawk= static_cast<AnimalFlags>(CanFly | EatsFish | Endangered);
}

jQuery AJAX Character Encoding

I was having similar problems, working in a content comments system in our Spanish Portal. What finally solved my problem, after many hours of searching, instead of messing with jQuery charset, that seems to use utf-8 no matter what, it was to decode from utf-8 back to ISO-8859-1 in the PHP that processed the ajax POST. In PHP there is a built in function, utf8_decode(), so the first thing I do with the comments string is this:

$comentario = utf8_decode($_POST['comentario']);

(and then I used nl2br() and htmlentities() PHP functions in order to prepare the text to be stored with html entities instead of special chars)

Good Luck & Peace all over! Seba

Get the generated SQL statement from a SqlCommand object?

Extended Kon's code to help debug a stored procedure:

    private void ExtractSqlCommandForDebugging(SqlCommand cmd)
    {
        string sql = "exec " + cmd.CommandText;
        bool first = true;
        foreach (SqlParameter p in cmd.Parameters)
        {
            string value = ((p.Value == DBNull.Value) ? "null"
                            : (p.Value is string) ? "'" + p.Value + "'"
                            : p.Value.ToString());
            if (first)
            {
                sql += string.Format(" {0}={1}", p.ParameterName, value);
                first = false;
            }
            else
            {
                sql += string.Format("\n , {0}={1}", p.ParameterName, value);
            }
        }
        sql += "\nGO";
        Debug.WriteLine(sql);
    }

In my first test case, it generated:

exec dbo.MyStoredProcName @SnailMail=False
 , @Email=True
 , @AcceptSnailMail=False
 , @AcceptEmail=False
 , @DistanceMiles=-1
 , @DistanceLocationList=''
 , @ExcludeDissatisfied=True
 , @ExcludeCodeRed=True
 , @MinAge=null
 , @MaxAge=18
 , @GenderTypeID=-1
 , @NewThisYear=-1
 , @RegisteredThisYear=-1
 , @FormersTermGroupList=''
 , @RegistrationStartDate=null
 , @RegistrationEndDate=null
 , @DivisionList='25'
 , @LocationList='29,30'
 , @OneOnOneOPL=-1
 , @JumpStart=-1
 , @SmallGroup=-1
 , @PurchasedEAP=-1
 , @RedeemedEAP=-1
 , @ReturnPlanYes=False
 , @MinNetPromoter=-1
 , @MinSurveyScore=-1
 , @VIPExclusionTypes='-2'
 , @FieldSelectionMask=65011584
 , @DisplayType=0
GO

You will probably need to add some more conditional "..is..." type assignments, e.g. for dates and times.

When should a class be Comparable and/or Comparator?

Implementing Comparable means "I can compare myself with another object." This is typically useful when there's a single natural default comparison.

Implementing Comparator means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

From the selectors specification:

Attribute values must be CSS identifiers or strings.

Identifiers cannot start with a number. Strings must be quoted.

1 is therefore neither a valid identifier nor a string.

Use "1" (which is a string) instead.

var a = document.querySelector('a[data-a="1"]');

How do I delete specific lines in Notepad++?

Using regex and find&replace, you can delete all the lines containing #region without leaving empty lines. Because for some reason Ray's method didn't work on my machine I searched for (.*#region.*\n)|(\n.*#region.*) and left the replace box empty.

That regex ensures that the if #region is found on the first line, the ending newline is deleted, and if it is found on the last line the preceding newline is deleted.

Still, Ray's solution is the better one if it works for you.

Filtering a list of strings based on contents

Tried this out quickly in the interactive shell:

>>> l = ['a', 'ab', 'abc', 'bac']
>>> [x for x in l if 'ab' in x]
['ab', 'abc']
>>>

Why does this work? Because the in operator is defined for strings to mean: "is substring of".

Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:

l = ['a', 'ab', 'abc', 'bac']
result = []
for s in l:
   if 'ab' in s:
       result.append(s)

jQuery Button.click() event is triggered twice

in my case, i was using the change command like this way

$(document).on('change', '.select-brand', function () {...my codes...});

and then i changed the way to

$('.select-brand').on('change', function () {...my codes...});

and it solved my problem.

how to add background image to activity?

You can set the "background image" to an activity by setting android:background xml attributes as followings:

(Here, for example, Take a LinearLayout for an activity and setting a background image for the layout(i.e. indirectly to an activity))

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

ALTER DATABASE failed because a lock could not be placed on database

In SQL Management Studio, go to Security -> Logins and double click your Login. Choose Server Roles from the left column, and verify that sysadmin is checked.

In my case, I was logged in on an account without that privilege.

HTH!

Package opencv was not found in the pkg-config search path

Hi first of all i would like you to use 'Synaptic Package Manager'. You just need to goto the ubuntu software center and search for synaptic package manager.. The beauty of this is that all the packages you need are easily available here. Second it will automatically configures all your paths. Now install this then search for opencv packages over there if you found the package with the green box then its installed but else the package is not in the right place so you need to reinstall it but from package manager this time. If installed then you can do this only, you just need to fill the OpenCV_DIR variable with the path of opencv (containing the OpenCVConfig.cmake file)

    export OpenCV_DIR=<path_of_opencv>

Converting Float to Dollars and Cents

Personally, I like this much better (which, granted, is just a different way of writing the currently selected "best answer"):

money = float(1234.5)
print('$' + format(money, ',.2f'))

Or, if you REALLY don't like "adding" multiple strings to combine them, you could do this instead:

money = float(1234.5)
print('${0}'.format(format(money, ',.2f')))

I just think both of these styles are a bit easier to read. :-)

(of course, you can still incorporate an If-Else to handle negative values as Eric suggests too)

C# Switch-case string starting with

If you knew that the length of conditions you would care about would all be the same length then you could:

switch(mystring.substring(0, Math.Min(3, mystring.Length))
{
  case "abc":
    //do something
    break;
  case "xyz":
    //do something else
    break;
  default:
    //do a different thing
    break;
}

The Math.Min(3, mystring.Length) is there so that a string of less than 3 characters won't throw an exception on the sub-string operation.

There are extensions of this technique to match e.g. a bunch of 2-char strings and a bunch of 3-char strings, where some 2-char comparisons matching are then followed by 3-char comparisons. Unless you've a very large number of such strings though, it quickly becomes less efficient than simple if-else chaining for both the running code and the person who has to maintain it.

Edit: Added since you've now stated they will be of different lengths. You could do the pattern I mentioned of checking the first X chars and then the next Y chars and so on, but unless there's a pattern where most of the strings are the same length this will be both inefficient and horrible to maintain (a classic case of premature pessimisation).

The command pattern is mentioned in another answer, so I won't give details of that, as is that where you map string patterns to IDs, but they are option.

I would not change from if-else chains to command or mapping patterns to gain the efficiency switch sometimes has over if-else, as you lose more in the comparisons for the command or obtaining the ID pattern. I would though do so if it made code clearer.

A chain of if-else's can work pretty well, either with string comparisons or with regular expressions (the latter if you have comparisons more complicated than the prefix-matches so far, which would probably be simpler and faster, I'm mentioning reg-ex's just because they do sometimes work well with more general cases of this sort of pattern).

If you go for if-elses, try to consider which cases are going to happen most often, and make those tests happen before those for less-common cases (though of course if "starts with abcd" is a case to look for it would have to be checked before "starts with abc").

How to execute a shell script in PHP?

If you are having a small script that you need to run (I simply needed to copy a file), I found it much easier to call the commands on the PHP script by calling

exec("sudo cp /tmp/testfile1 /var/www/html/testfile2");

and enabling such transaction by editing (or rather adding) a permitting line to the sudoers by first calling sudo visudo and adding the following line to the very end of it

www-data ALL=(ALL) NOPASSWD:/bin/cp /tmp/testfile1 /var/www/html/testfile2

All I wanted to do was to copy a file and I have been having problems with doing so because of the root password problem, and as you mentioned I did NOT want to expose the system to have no password for all root transactions.

Is bool a native C type?

stdbool.h was introduced in c99

What is the difference between "px", "dip", "dp" and "sp"?

Where to use what & relationship between px & dp?

Density-independent pixel (dp)

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. As described above, the density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple:

px = dp * (dpi / 160).

For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

Understanding pixel to dp and vice versa is very essential (especially for giving exact dp values to creative team)

dp = px * 160 / dpi

MDPI = 160 dpi || Therefore, on MDPI 1 px = 1 dp
For example, if you want to convert 20 pixel to dp, use the above formula,
dp = 20 * 160 / 160 = 20.
So, 20 pixel = 20 dp.

HDPI = 240 dpi - So, on HDPI 1.5 px = 1 dp
XHDPI = 320 dpi - So, on XHDPI 2 px = 1 dp
XXHDPI = 480 dpi - So, on XXHDPI 3 px = 1 dp

For example, let us consider Nexus 4.
If 24 pixels to be converted to dp and if it is a Nexus 4 screen, developers can
convert it to dp easily by the following calculation :
dp = 24 * 160 / 320 = 12 dp
Screen dimension:
768 x 1280 pixel resolution (320 ppi or 320dpi)
Optional (screen size):
 4.7" diagonal
  • Try to get all pixel values in even numbers from the creative team. Otherwise precision lose will happen while multiplying with 0.5.

px

It is explained above. Try to avoid in layout files. But there are some cases, where px is required. for example, ListView divider line. px is better here for giving a one-pixel line as a divider for all across screen resolutions.

sp

Use sp for font sizes. Then only the font inside the application will change while device fonts size changes (that is, Display -> Fonts on Device). If you want to keep a static sized font inside the app, you can give the font dimension in dp. In such a case, it will never change. Developers may get such a requirement for some specific screens, for that, developers can use dp instead of sp. In all other cases, sp is recommended.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

AlexRobbins' answer worked for me, except that the first two lines need to be in the model (perhaps this was assumed?), and should reference self:

def book_author(self):
  return self.book.author

Then the admin part works nicely.

How to make sure that a certain Port is not occupied by any other process

You can use "netstat" to check whether a port is available or not.

Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

You have to put : before port number to get the actual output

Ex netstat -anp | find ":8080"

Dealing with HTTP content in HTTPS pages

Sometimes like in facebook apps we can not have non-secure contents in secure page. also we can not make local those contents. for example an app which will load in iFrame is not a simple content and we can not make it local.

I think we should never load http contents in https, also we should not fallback https page to http version to prevent error dialog.

the only way which will ensure user's security is to use https version of all contents, http://web.archive.org/web/20120502131549/http://developers.facebook.com/blog/post/499/

Storyboard - refer to ViewController in AppDelegate

Generally, the system should be handling view controller instantiation with a storyboard. What you want is to traverse the viewController hierarchy by grabbing a reference to the self.window.rootViewController as opposed to initializing view controllers, which should already be initialized correctly if you've setup your storyboard properly.

So, let's say your rootViewController is a UINavigationController and then you want to send something to its top view controller, you would do it like this in your AppDelegate's didFinishLaunchingWithOptions:

UINavigationController *nav = (UINavigationController *) self.window.rootViewController;
MyViewController *myVC = (MyViewController *)nav.topViewController;
myVC.data = self.data;

In Swift if would be very similar:

let nav = self.window.rootViewController as! UINavigationController;
let myVC = nav.topViewController as! MyViewController
myVc.data = self.data

You really shouldn't be initializing view controllers using storyboard id's from the app delegate unless you want to bypass the normal way storyboard is loaded and load the whole storyboard yourself. If you're having to initialize scenes from the AppDelegate you're most likely doing something wrong. I mean imagine you, for some reason, want to send data to a view controller way down the stack, the AppDelegate shouldn't be reaching way into the view controller stack to set data. That's not its business. It's business is the rootViewController. Let the rootViewController handle its own children! So, if I were bypassing the normal storyboard loading process by the system by removing references to it in the info.plist file, I would at most instantiate the rootViewController using instantiateViewControllerWithIdentifier:, and possibly its root if it is a container, like a UINavigationController. What you want to avoid is instantiating view controllers that have already been instantiated by the storyboard. This is a problem I see a lot. In short, I disagree with the accepted answer. It is incorrect unless the posters means to remove loading of the storyboard from the info.plist since you will have loaded 2 storyboards otherwise, which makes no sense. It's probably not a memory leak because the system initialized the root scene and assigned it to the window, but then you came along and instantiated it again and assigned it again. Your app is off to a pretty bad start!

Private class declaration

private makes the class accessible only to the class in which it is declared. If we make entire class private no one from outside can access the class and makes it useless.

Inner class can be made private because the outer class can access inner class where as it is not the case with if you make outer class private.

What is the difference between a schema and a table and a database?

As MusiGenesis put so nicely, in most databases:

schema : database : table :: floor plan : house : room

But, in Oracle it may be easier to think of:

schema : database : table :: owner : house : room

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

yes, I know, I'm too late (as always). Here is my piece of code (based on the reply of mk2). Maybe this helps someone:

std::vector<std::string> find_serial_ports()
{
 std::vector<std::string> ports;
    std::filesystem::path kdr_path{"/proc/tty/drivers"};
    if (std::filesystem::exists(kdr_path))
    {
        std::ifstream ifile(kdr_path.generic_string());
        std::string line;
        std::vector<std::string> prefixes;
        while (std::getline(ifile, line))
        {
            std::vector<std::string> items;
            auto it = line.find_first_not_of(' ');
            while (it != std::string::npos)
            {

                auto it2 = line.substr(it).find_first_of(' ');
                if (it2 == std::string::npos)
                {
                    items.push_back(line.substr(it));
                    break;
                }
                it2 += it;
                items.push_back(line.substr(it, it2 - it));
                it = it2 + line.substr(it2).find_first_not_of(' ');
            }
            if (items.size() >= 5)
            {
                if (items[4] == "serial" && items[0].find("serial") != std::string::npos)
                {
                    prefixes.emplace_back(items[1]);
                }
            }
        }
        ifile.close();
        for (auto& p: std::filesystem::directory_iterator("/dev"))
        {
            for (const auto& pf : prefixes)
            {
                auto dev_path = p.path().generic_string();
                if (dev_path.size() >= pf.size() && std::equal(dev_path.begin(), dev_path.begin() + pf.size(), pf.begin()))
                {
                    ports.emplace_back(dev_path);
                }
            }
        }
    }
    return ports;
}

Convert JS Object to form data

Recursively

_x000D_
_x000D_
const toFormData = (f => f(f))(h => f => f(x => h(h)(f)(x)))(f => fd => pk => d => {_x000D_
  if (d instanceof Object) {_x000D_
    Object.keys(d).forEach(k => {_x000D_
      const v = d[k]_x000D_
      if (pk) k = `${pk}[${k}]`_x000D_
      if (v instanceof Object && !(v instanceof Date) && !(v instanceof File)) {_x000D_
        return f(fd)(k)(v)_x000D_
      } else {_x000D_
        fd.append(k, v)_x000D_
      }_x000D_
    })_x000D_
  }_x000D_
  return fd_x000D_
})(new FormData())()_x000D_
_x000D_
let data = {_x000D_
  name: 'John',_x000D_
  age: 30,_x000D_
  colors: ['red', 'green', 'blue'],_x000D_
  children: [_x000D_
    { name: 'Max', age: 3 },_x000D_
    { name: 'Madonna', age: 10 }_x000D_
  ]_x000D_
}_x000D_
console.log('data', data)_x000D_
document.getElementById("data").insertAdjacentHTML('beforeend', JSON.stringify(data))_x000D_
_x000D_
let formData = toFormData(data)_x000D_
_x000D_
for (let key of formData.keys()) {_x000D_
  console.log(key, formData.getAll(key).join(','))_x000D_
  document.getElementById("item").insertAdjacentHTML('beforeend', `<li>${key} = ${formData.getAll(key).join(',')}</li>`)_x000D_
}
_x000D_
<p id="data"></p>_x000D_
<ul id="item"></ul>
_x000D_
_x000D_
_x000D_

How to support placeholder attribute in IE8 and 9

You could use this jQuery plugin: https://github.com/mathiasbynens/jquery-placeholder

But your link seems to be also a good solution.

ReportViewer Client Print Control "Unable to load client print control"?

In my case when I get this message IE suggest me to install add-on from Microsoft. After install problem solved.

My software:
IE9 but work also on older
SQL SERVER 2008 R2

How to initialize a private static const map in C++?

If the map is to contain only entries that are known at compile time and the keys to the map are integers, then you do not need to use a map at all.

char get_value(int key)
{
    switch (key)
    {
        case 1:
            return 'a';
        case 2:
            return 'b';
        case 3:
            return 'c';
        default:
            // Do whatever is appropriate when the key is not valid
    }
}

Can I scroll a ScrollView programmatically in Android?

The answer from Pragna does not work always, try this:

mScrollView.post(new Runnable() { 
        public void run() { 
             mScrollView.scrollTo(0, mScrollView.getBottom());
        } 
});

or

mScrollView.post(new Runnable() { 
        public void run() { 
             mScrollView.fullScroll(mScrollView.FOCUS_DOWN);
        } 
});

if You want to scroll to start

mScrollView.post(new Runnable() { 
        public void run() { 
             mScrollView.fullScroll(mScrollView.FOCUS_UP);
        } 
});

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Apache - MySQL Service detected with wrong path. / Ports already in use

Ok so i found out the problem :)

ctrl+alt+delete to start task manager, once you get to task manager go to services. find MySQL and right click on it. Then click stop process. That worked for me and i hope it works for you :D

Dealing with "Xerces hell" in Java/Maven?

What would help, except for excluding, is modular dependencies.

With one flat classloading (standalone app), or semi-hierarchical (JBoss AS/EAP 5.x) this was a problem.

But with modular frameworks like OSGi and JBoss Modules, this is not so much pain anymore. The libraries may use whichever library they want, independently.

Of course, it's still most recommendable to stick with just a single implementation and version, but if there's no other way (using extra features from more libs), then modularizing might save you.

A good example of JBoss Modules in action is, naturally, JBoss AS 7 / EAP 6 / WildFly 8, for which it was primarily developed.

Example module definition:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.jboss.msc">
    <main-class name="org.jboss.msc.Version"/>
    <properties>
        <property name="my.property" value="foo"/>
    </properties>
    <resources>
        <resource-root path="jboss-msc-1.0.1.GA.jar"/>
    </resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="org.jboss.logging"/>
        <module name="org.jboss.modules"/>
        <!-- Optional deps -->
        <module name="javax.inject.api" optional="true"/>
        <module name="org.jboss.threads" optional="true"/>
    </dependencies>
</module>

In comparison with OSGi, JBoss Modules is simpler and faster. While missing certain features, it's sufficient for most projects which are (mostly) under control of one vendor, and allow stunning fast boot (due to paralelized dependencies resolving).

Note that there's a modularization effort underway for Java 8, but AFAIK that's primarily to modularize the JRE itself, not sure whether it will be applicable to apps.

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Random record from MongoDB

Using Map/Reduce, you can certainly get a random record, just not necessarily very efficiently depending on the size of the resulting filtered collection you end up working with.

I've tested this method with 50,000 documents (the filter reduces it to about 30,000), and it executes in approximately 400ms on an Intel i3 with 16GB ram and a SATA3 HDD...

db.toc_content.mapReduce(
    /* map function */
    function() { emit( 1, this._id ); },

    /* reduce function */
    function(k,v) {
        var r = Math.floor((Math.random()*v.length));
        return v[r];
    },

    /* options */
    {
        out: { inline: 1 },
        /* Filter the collection to "A"ctive documents */
        query: { status: "A" }
    }
);

The Map function simply creates an array of the id's of all documents that match the query. In my case I tested this with approximately 30,000 out of the 50,000 possible documents.

The Reduce function simply picks a random integer between 0 and the number of items (-1) in the array, and then returns that _id from the array.

400ms sounds like a long time, and it really is, if you had fifty million records instead of fifty thousand, this may increase the overhead to the point where it becomes unusable in multi-user situations.

There is an open issue for MongoDB to include this feature in the core... https://jira.mongodb.org/browse/SERVER-533

If this "random" selection was built into an index-lookup instead of collecting ids into an array and then selecting one, this would help incredibly. (go vote it up!)

How to access Spring MVC model object in javascript file?

You can't access java objects from JavaScript because there are no objects on client side. It only receives plain HTML page (hidden fields can help but it's not very good approach).

I suggest you to use ajax and @ResponseBody.

Convert/cast an stdClass object to another class

Changed function for deep casting (using recursion)

/**
 * Translates type
 * @param $destination Object destination
 * @param stdClass $source Source
 */
private static function Cast(&$destination, stdClass $source)
{
    $sourceReflection = new \ReflectionObject($source);
    $sourceProperties = $sourceReflection->getProperties();
    foreach ($sourceProperties as $sourceProperty) {
        $name = $sourceProperty->getName();
        if (gettype($destination->{$name}) == "object") {
            self::Cast($destination->{$name}, $source->$name);
        } else {
            $destination->{$name} = $source->$name;
        }
    }
}

Array length in angularjs returns undefined

use:

$scope.users.length;

Instead of:

$scope.users.lenght;

And next time "spell-check" your code.

SSL: CERTIFICATE_VERIFY_FAILED with Python3

I have a lib what use https://requests.readthedocs.io/en/master/ what use https://pypi.org/project/certifi/ but I have a custom CA included in my /etc/ssl/certs.

So I solved my problem like this:

# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like again)
export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt"
# If you have a virtualenv:
. ./.venv/bin/activate
# Get the current certifi CA bundle
CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'`

test -L $CERTFI_PATH || rm $CERTFI_PATH
test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH

Et voilà !

Where is the syntax for TypeScript comments documented?

You can add information about parameters, returns, etc. as well using:

/**
* This is the foo function
* @param bar This is the bar parameter
* @returns returns a string version of bar
*/
function foo(bar: number): string {
    return bar.toString()
}

This will cause editors like VS Code to display it as the following:

enter image description here

What is the difference between Sublime text and Github's Atom

I tried Atom and it looks really nice BUT there is one major problem (at least in v 0.84):

It doesn't support vertical select Alt+Drag - this is a must for every modern code editor.

Reference excel worksheet by name?

There are several options, including using the method you demonstrate, With, and using a variable.

My preference is option 4 below: Dim a variable of type Worksheet and store the worksheet and call the methods on the variable or pass it to functions, however any of the options work.

Sub Test()
  Dim SheetName As String
  Dim SearchText As String
  Dim FoundRange As Range

  SheetName = "test"      
  SearchText = "abc"

  ' 0. If you know the sheet is the ActiveSheet, you can use if directly.
  Set FoundRange = ActiveSheet.UsedRange.Find(What:=SearchText)
  ' Since I usually have a lot of Subs/Functions, I don't use this method often.
  ' If I do, I store it in a variable to make it easy to change in the future or
  ' to pass to functions, e.g.: Set MySheet = ActiveSheet
  ' If your methods need to work with multiple worksheets at the same time, using
  ' ActiveSheet probably isn't a good idea and you should just specify the sheets.

  ' 1. Using Sheets or Worksheets (Least efficient if repeating or calling multiple times)
  Set FoundRange = Sheets(SheetName).UsedRange.Find(What:=SearchText)
  Set FoundRange = Worksheets(SheetName).UsedRange.Find(What:=SearchText)

  ' 2. Using Named Sheet, i.e. Sheet1 (if Worksheet is named "Sheet1"). The
  ' sheet names use the title/name of the worksheet, however the name must
  ' be a valid VBA identifier (no spaces or special characters. Use the Object
  ' Browser to find the sheet names if it isn't obvious. (More efficient than #1)
  Set FoundRange = Sheet1.UsedRange.Find(What:=SearchText)

  ' 3. Using "With" (more efficient than #1)
  With Sheets(SheetName)
    Set FoundRange = .UsedRange.Find(What:=SearchText)
  End With
  ' or possibly...
  With Sheets(SheetName).UsedRange
    Set FoundRange = .Find(What:=SearchText)
  End With

  ' 4. Using Worksheet variable (more efficient than 1)
  Dim MySheet As Worksheet
  Set MySheet = Worksheets(SheetName)
  Set FoundRange = MySheet.UsedRange.Find(What:=SearchText)

  ' Calling a Function/Sub
  Test2 Sheets(SheetName) ' Option 1
  Test2 Sheet1 ' Option 2
  Test2 MySheet ' Option 4

End Sub

Sub Test2(TestSheet As Worksheet)
    Dim RowIndex As Long
    For RowIndex = 1 To TestSheet.UsedRange.Rows.Count
        If TestSheet.Cells(RowIndex, 1).Value = "SomeValue" Then
            ' Do something
        End If
    Next RowIndex
End Sub

HTML: How to center align a form

Being form a block element, you can center-align it by setting its side margins to auto:

form { margin: 0 auto; }

EDIT:
As @moomoochoo correctly pointed out, this rule will only work if the block element (your form, in this case) has been assigned a specific width.
Also, this 'trick' will not work for floating elements.

Get content uri from file path in android

Easiest and the robust way for creating Content Uri content:// from a File is to use FileProvider. Uri provided by FileProvider can be used also providing Uri for sharing files with other apps too. To get File Uri from a absolute path of File you can use DocumentFile.fromFile(new File(path, name)), it's added in Api 22, and returns null for versions below.

File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);

Using C# to check if string contains a string in string array

You can also do the same thing as Anton Gogolev suggests to check if any item in stringArray1 matches any item in stringArray2:

if(stringArray1.Any(stringArray2.Contains))

And likewise all items in stringArray1 match all items in stringArray2:

if(stringArray1.All(stringArray2.Contains))

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

From the Apple Developer Forum (account required):

"The compiler and linker are capable of using features and performing optimizations that do not work on older OS versions. -mmacosx-version-min tells the tools what OS versions you need to work with, so the tools can disable optimizations that won't run on those OS versions. If you need to run on older OS versions then you must use this flag.

"The downside to -mmacosx-version-min is that the app's performance may be worse on newer OS versions then it could have been if it did not need to be backwards-compatible. In most cases the differences are small."

presentViewController and displaying navigation bar

If you use NavigationController in Swift 2.x

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let targetViewController = storyboard.instantiateViewControllerWithIdentifier("targetViewControllerID") as? TargetViewController
self.navigationController?.pushViewController(targetViewController!, animated: true)

How do I load an url in iframe with Jquery

here is Iframe in view:

<iframe class="img-responsive" id="ifmReport" width="1090" height="1200" >

    </iframe>

Load it in script:

 $('#ifmReport').attr('src', '/ReportViewer/ReportViewer.aspx');

Python debugging tips

There is a full online course called "Software Debugging" by Andreas Zeller on Udacity, packed with tips about debugging:

Course Summary

In this class you will learn how to debug programs systematically, how to automate the debugging process and build several automated debugging tools in Python.

Why Take This Course?

At the end of this course you will have a solid understanding about systematic debugging, will know how to automate debugging and will have built several functional debugging tools in Python.

Prerequisites and Requirements

Basic knowledge of programming and Python at the level of Udacity CS101 or better is required. Basic understanding of Object-oriented programming is helpful.

Highly recommended.

How can I convert byte size into a human-readable format in Java?

Kotlin Version via Extension Property

If you are using kotlin, it's pretty easy to format file size by these extension properties. It is loop-free and completely based on pure math.


HumanizeUtils.kt

import java.io.File
import kotlin.math.log2
import kotlin.math.pow

/**
 * @author aminography
 */

val File.formatSize: String
    get() = length().formatAsFileSize

val Int.formatAsFileSize: String
    get() = toLong().formatAsFileSize

val Long.formatAsFileSize: String
    get() = log2(if (this != 0L) toDouble() else 1.0).toInt().div(10).let {
        val precision = when (it) {
            0 -> 0; 1 -> 1; else -> 2
        }
        val prefix = arrayOf("", "K", "M", "G", "T", "P", "E", "Z", "Y")
        String.format("%.${precision}f ${prefix[it]}B", toDouble() / 2.0.pow(it * 10.0))
    }

Usage:

println("0:          " + 0.formatAsFileSize)
println("170:        " + 170.formatAsFileSize)
println("14356:      " + 14356.formatAsFileSize)
println("968542985:  " + 968542985.formatAsFileSize)
println("8729842496: " + 8729842496.formatAsFileSize)

println("file: " + file.formatSize)

Result:

0:          0 B
170:        170 B
14356:      14.0 KB
968542985:  923.67 MB
8729842496: 8.13 GB

file: 6.15 MB

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

How to run a Command Prompt command with Visual Basic code?

Here is an example:

Process.Start("CMD", "/C Pause")


/C  Carries out the command specified by string and then terminates
/K  Carries out the command specified by string but remains

And here is a extended function: (Notice the comment-lines using CMD commands.)

#Region " Run Process Function "

' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe")) 
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")

Private Function Run_Process(ByVal Process_Name As String, _
                             Optional Process_Arguments As String = Nothing, _
                             Optional Read_Output As Boolean = False, _
                             Optional Process_Hide As Boolean = False, _
                             Optional Process_TimeOut As Integer = 999999999)

    ' Returns True if "Read_Output" argument is False and Process was finished OK
    ' Returns False if ExitCode is not "0"
    ' Returns Nothing if process can't be found or can't be started
    ' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.

    Try

        Dim My_Process As New Process()
        Dim My_Process_Info As New ProcessStartInfo()

        My_Process_Info.FileName = Process_Name ' Process filename
        My_Process_Info.Arguments = Process_Arguments ' Process arguments
        My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
        My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
        My_Process_Info.RedirectStandardOutput = Read_Output '  Redirect (1) Output
        My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
        My_Process.EnableRaisingEvents = True ' Raise events
        My_Process.StartInfo = My_Process_Info
        My_Process.Start() ' Run the process NOW

        My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)

        Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
        If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0

        If Read_Output = True Then
            Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
            Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
            ' Return output by priority
            If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
            If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
        End If

    Catch ex As Exception
        'MsgBox(ex.Message)
        Return Nothing ' Returns nothing if the process can't be found or started.
    End Try

    Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.

End Function

#End Region

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

This is how I solved it, You can follow step by step here:

MongoDB Steps:

  • Download the latest 64-bit MSI version of MongoDB for Windows.

  • Run the installer (.msi file)

  • Add it to your PATH of environment variables. it Should be from:
    C:\Program Files\MongoDB\Server\3.0\bin

now Create a “\data\db” folder in C:/ which is used by mongodb to store all data. You should have this folder:

C:\data\db

Note: This is the default directory location expected by mongoDB, don’t create anywhere else

.

Finally, open command prompt and type:

>> mongod

You should see it asking for permissions (allow it) and then listen to a port. After that is done, open another command prompt, leaving the previous one running the server.

Type in the new command prompt

>> mongo

You should see it display the version and connect to a test database.

This proves successful install!=)

Reference link

Numpy AttributeError: 'float' object has no attribute 'exp'

You convert type np.dot(X, T) to float32 like this:

z=np.array(np.dot(X, T),dtype=np.float32)

def sigmoid(X, T):
    return (1.0 / (1.0 + np.exp(-z)))

Hopefully it will finally work!

Form Submit jQuery does not work

Because when you call $( "#form_id" ).submit(); it triggers the external submit handler which prevents the default action, instead use

$( "#form_id" )[0].submit();       

or

$form.submit();//declare `$form as a local variable by using var $form = this;

When you call the dom element's submit method programatically, it won't trigger the submit handlers attached to the element

Rails DateTime.now without Time

If you're happy to require 'active_support/core_ext', then you can use

DateTime.now.midnight # => Sat, 19 Nov 2011 00:00:00 -0800

Why does an onclick property set with setAttribute fail to work in IE?

In some cases the examples listed here didn't work out for me in Internet Explorer.

Since you have to set the property with a method like this (without brackets)

HtmlElement.onclick = myMethod;

it won't work if you have to pass an object-name or even parameters. For the Internet Explorer you should create a new object in runtime:

HtmlElement.onclick = new Function('myMethod(' + someParameter + ')');

Works also on other browsers.

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

How do I break a string across more than one line of code in JavaScript?

A good solution here for VSCode users, if a string breaking down into multiple lines causes the problem (I faced this when I had to test a long JWT token, and somehow using template literals didn't do the trick.)

Check if array is empty or null

You should check for '' (empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0 will work just fine.

Find objects between two dates MongoDB

To clarify. What is important to know is that:

  • Yes, you have to pass a Javascript Date object.
  • Yes, it has to be ISODate friendly
  • Yes, from my experience getting this to work, you need to manipulate the date to ISO
  • Yes, working with dates is generally always a tedious process, and mongo is no exception

Here is a working snippet of code, where we do a little bit of date manipulation to ensure Mongo (here i am using mongoose module and want results for rows whose date attribute is less than (before) the date given as myDate param) can handle it correctly:

var inputDate = new Date(myDate.toISOString());
MyModel.find({
    'date': { $lte: inputDate }
})

How to Set a Custom Font in the ActionBar Title?

use new toolbar in support library design your actionbar as your own or use below code

Inflating Textview is not an good option try Spannable String builder

Typeface font2 = Typeface.createFromAsset(getAssets(), "fonts/<your font in assets folder>");   
SpannableStringBuilder SS = new SpannableStringBuilder("MY Actionbar Tittle");
SS.setSpan (new CustomTypefaceSpan("", font2), 0, SS.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
actionBar.setTitle(ss);

copy below class

public class CustomTypefaceSpan extends TypefaceSpan{

    private final Typeface newType;

    public CustomTypefaceSpan(String family, Typeface type) {
        super(family);
        newType = type;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);
    }

    private static void applyCustomTypeFace(Paint paint, Typeface tf) {
        int oldStyle;
        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();
        }

        int fake = oldStyle & ~tf.getStyle();
        if ((fake & Typeface.BOLD) != 0) {
            paint.setFakeBoldText(true);
        }

        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }

        paint.setTypeface(tf);
    }

}

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

Python Binomial Coefficient

Here's a version that actually uses the correct formula . :)

#! /usr/bin/env python

''' Calculate binomial coefficient xCy = x! / (y! (x-y)!)
'''

from math import factorial as fac


def binomial(x, y):
    try:
        return fac(x) // fac(y) // fac(x - y)
    except ValueError:
        return 0


#Print Pascal's triangle to test binomial()
def pascal(m):
    for x in range(m + 1):
        print([binomial(x, y) for y in range(x + 1)])


def main():
    #input = raw_input
    x = int(input("Enter a value for x: "))
    y = int(input("Enter a value for y: "))
    print(binomial(x, y))


if __name__ == '__main__':
    #pascal(8)
    main()

...

Here's an alternate version of binomial() I wrote several years ago that doesn't use math.factorial(), which didn't exist in old versions of Python. However, it returns 1 if r is not in range(0, n+1).

def binomial(n, r):
    ''' Binomial coefficient, nCr, aka the "choose" function 
        n! / (r! * (n - r)!)
    '''
    p = 1    
    for i in range(1, min(r, n - r) + 1):
        p *= n
        p //= i
        n -= 1
    return p

.rar, .zip files MIME Type

You should not trust $_FILES['upfile']['mime'], check MIME type by yourself. For that purpose, you may use fileinfo extension, enabled by default as of PHP 5.3.0.

  $fileInfo = new finfo(FILEINFO_MIME_TYPE);
  $fileMime = $fileInfo->file($_FILES['upfile']['tmp_name']);
  $validMimes = array( 
    'zip' => 'application/zip',
    'rar' => 'application/x-rar',
  );

  $fileExt = array_search($fileMime, $validMimes, true);
  if($fileExt != 'zip' && $fileExt != 'rar')
    throw new RuntimeException('Invalid file format.');

NOTE: Don't forget to enable the extension in your php.ini and restart your server:

extension=php_fileinfo.dll

How to convert a string with comma-delimited items to a list in Python?

Like this:

>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]

Alternatively, you can use eval() if you trust the string to be safe:

>>> text = 'a,b,c'
>>> text = eval('[' + text + ']')

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

pull/push from multiple remote locations

I took the liberty to expand the answer from nona-urbiz; just add this to your ~/.bashrc:

git-pullall () { for RMT in $(git remote); do git pull -v $RMT $1; done; }    
alias git-pullall=git-pullall

git-pushall () { for RMT in $(git remote); do git push -v $RMT $1; done; }
alias git-pushall=git-pushall

Usage:

git-pullall master

git-pushall master ## or
git-pushall

If you do not provide any branch argument for git-pullall then the pull from non-default remotes will fail; left this behavior as it is, since it's analogous to git.

Objective-C: Extract filename from path string

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

Configuring Log4j Loggers Programmatically

If someone comes looking for configuring log4j2 programmatically in Java, then this link could help: (https://www.studytonight.com/post/log4j2-programmatic-configuration-in-java-class)

Here is the basic code for configuring a Console Appender:

ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

builder.setStatusLevel(Level.DEBUG);
// naming the logger configuration
builder.setConfigurationName("DefaultLogger");

// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
// add a layout like pattern, json etc
appenderBuilder.add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d %p %c [%t] %m%n"));
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
rootLogger.add(builder.newAppenderRef("Console"));

builder.add(appenderBuilder);
builder.add(rootLogger);
Configurator.reconfigure(builder.build());

This will reconfigure the default rootLogger and will also create a new appender.

Insert ellipsis (...) into HTML tag if content too wide

Pure CSS Multi-line Ellipsis for text content:

_x000D_
_x000D_
.container{_x000D_
    position: relative;  /* Essential */_x000D_
    background-color: #bbb;  /* Essential */_x000D_
    padding: 20px; /* Arbritrary */_x000D_
}_x000D_
.text {_x000D_
    overflow: hidden;  /* Essential */_x000D_
    /*text-overflow: ellipsis; Not needed */_x000D_
    line-height: 16px;  /* Essential */_x000D_
    max-height: 48px; /* Multiples of line-height */_x000D_
}_x000D_
.ellipsis {_x000D_
    position: absolute;/* Relies on relative container */_x000D_
    bottom: 20px; /* Matches container padding */_x000D_
    right: 20px; /* Matches container padding */_x000D_
    height: 16px; /* Matches line height */_x000D_
    width: 30px; /* Arbritrary */_x000D_
    background-color: inherit; /* Essential...or specify a color */_x000D_
    padding-left: 8px; /* Arbritrary */_x000D_
}
_x000D_
<div class="container">_x000D_
    <div class="text">_x000D_
        Lorem ipsum dolor sit amet, consectetur eu in adipiscing elit. Aliquam consectetur venenatis blandit. Praesent vehicula, libero non pretium vulputate, lacus arcu facilisis lectus, sed feugiat tellus nulla eu dolor. Nulla porta bibendum lectus quis euismod. Aliquam volutpat ultricies porttitor. Cras risus nisi, accumsan vel cursus ut, sollicitudin vitae dolor. Fusce scelerisque eleifend lectus in bibendum. Suspendisse lacinia egestas felis a volutpat. Aliquam volutpat ultricies porttitor. Cras risus nisi, accumsan vel cursus ut, sollicitudin vitae dolor. Fusce scelerisque eleifend lectus in bibendum. Suspendisse lacinia egestas felis a volutpat._x000D_
    </div>_x000D_
    <div class="ellipsis">...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Please checkout the snippet for a live example.

Angularjs checkbox checked by default on load and disables Select list when checked

Do it in the controller ( controller as syntax below)

controller:

vm.question= {};
vm.question.active = true;

form

<input ng-model="vm.question.active" type="checkbox" id="active" name="active">

Get selected value/text from Select on change

No need for an onchange function. You can grab the value in one line:

document.getElementById("select_id").options[document.getElementById("select_id").selectedIndex].value;

Or, split it up for better readability:

var select_id = document.getElementById("select_id");

select_id.options[select_id.selectedIndex].value;

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

Even though you are using ASMM, you can set a minimum size for the large pool (MMAN will not shrink it below that value). You can also try pinning some objects and increasing SGA_TARGET.

catch specific HTTP error in python

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

Remove duplicates in the list using linq

An universal extension method:

public static class EnumerableExtensions
{
    public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> enumerable, Func<T, TKey> keySelector)
    {
        return enumerable.GroupBy(keySelector).Select(grp => grp.First());
    }
}

Example of usage:

var lstDst = lst.DistinctBy(item => item.Key);

How do I create a Bash alias?

It works for me on macOS Majave

You can do a few simple steps:

1) open terminal

2) sudo nano /.bash_profile

3) add your aliases, as example:

# some aliases
alias ll='ls -alF'
alias la='ls -A'
alias eb="sudo nano ~/.bash_profile && source ~/.bash_profile"
#docker aliases
alias d='docker'
alias dc='docker-compose'
alias dnax="docker rm $(docker ps -aq)"
#git aliases
alias g='git'
alias new="git checkout -b"
alias last="git log -2"
alias gg='git status'
alias lg="git log --pretty=format:'%h was %an, %ar, message: %s' --graph"
alias nah="git reset --hard && git clean -df"
alias squash="git rebase -i HEAD~2"

4) source /.bash_profile

Done. Use and enjoy!

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

<input type="hidden" id="date"/>
<script>document.getElementById("date").value = new Date().toJSON().slice(0,10)</script>

How to configure Glassfish Server in Eclipse manually

I had the same problem, to resolve it, go windows -> preferences -> servers and select runtime environment, and now you will see a new window, in the upper right you will see a option: Download additional server adapter, click and install the glassfish server.

How to upload (FTP) files to server in a bash script?

You can use a heredoc to do this e.g.

ftp -n $Server <<End-Of-Session
# -n option disables auto-logon

user anonymous "$Password"
binary
cd $Directory
put "$Filename.lsm"
put "$Filename.tar.gz"
bye
End-Of-Session

so the ftp process is fed on stdin with everything up to End-Of-Session. A useful tip for spawning any process, not just ftp! Note that this saves spawning a separate process (echo, cat etc.). Not a major resource saving, but worth bearing in mind.

How to install plugin for Eclipse from .zip

It depends on what the zip contains. Take a look to see if it got content.jar and artifacts.jar. If it does, it is an archived updated site. Install from it the same way as you install from a remote site.

If the zip doesn't contain content.jar and artifacts.jar, go to your Eclipse install's dropins directory, create a subfolder (name doesn't matter) and expand your zip into that folder. Restart Eclipse.

Find nearest latitude/longitude with an SQL query

Here is my full solution implemented in PHP.

This solution uses the Haversine formula as presented in http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL.

It should be noted that the Haversine formula experiences weaknesses around the poles. This answer shows how to implement the vincenty Great Circle Distance formula to get around this, however I chose to just use Haversine because it's good enough for my purposes.

I'm storing latitude as DECIMAL(10,8) and longitude as DECIMAL(11,8). Hopefully this helps!

showClosest.php

<?PHP
/**
 * Use the Haversine Formula to display the 100 closest matches to $origLat, $origLon
 * Only search the MySQL table $tableName for matches within a 10 mile ($dist) radius.
 */
include("./assets/db/db.php"); // Include database connection function
$db = new database(); // Initiate a new MySQL connection
$tableName = "db.table";
$origLat = 42.1365;
$origLon = -71.7559;
$dist = 10; // This is the maximum distance (in miles) away from $origLat, $origLon in which to search
$query = "SELECT name, latitude, longitude, 3956 * 2 * 
          ASIN(SQRT( POWER(SIN(($origLat - latitude)*pi()/180/2),2)
          +COS($origLat*pi()/180 )*COS(latitude*pi()/180)
          *POWER(SIN(($origLon-longitude)*pi()/180/2),2))) 
          as distance FROM $tableName WHERE 
          longitude between ($origLon-$dist/cos(radians($origLat))*69) 
          and ($origLon+$dist/cos(radians($origLat))*69) 
          and latitude between ($origLat-($dist/69)) 
          and ($origLat+($dist/69)) 
          having distance < $dist ORDER BY distance limit 100"; 
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
    echo $row['name']." > ".$row['distance']."<BR>";
}
mysql_close($db);
?>

./assets/db/db.php

<?PHP
/**
 * Class to initiate a new MySQL connection based on $dbInfo settings found in dbSettings.php
 *
 * @example $db = new database(); // Initiate a new database connection
 * @example mysql_close($db); // close the connection
 */
class database{
    protected $databaseLink;
    function __construct(){
        include "dbSettings.php";
        $this->database = $dbInfo['host'];
        $this->mysql_user = $dbInfo['user'];
        $this->mysql_pass = $dbInfo['pass'];
        $this->openConnection();
        return $this->get_link();
    }
    function openConnection(){
    $this->databaseLink = mysql_connect($this->database, $this->mysql_user, $this->mysql_pass);
    }

    function get_link(){
    return $this->databaseLink;
    }
}
?>

./assets/db/dbSettings.php

<?php
$dbInfo = array(
    'host'      => "localhost",
    'user'      => "root",
    'pass'      => "password"
);
?>

It may be possible to increase performance by using a MySQL stored procedure as suggested by the "Geo-Distance-Search-with-MySQL" article posted above.

I have a database of ~17,000 places and the query execution time is 0.054 seconds.

Difference between MEAN.js and MEAN.io

First of all, MEAN is an acronym for MongoDB, Express, Angular and Node.js.

It generically identifies the combined used of these technologies in a "stack". There is no such a thing as "The MEAN framework".

Lior Kesos at Linnovate took advantage of this confusion. He bought the domain MEAN.io and put some code at https://github.com/linnovate/mean

They luckily received a lot of publicity, and theree are more and more articles and video about MEAN. When you Google "mean framework", mean.io is the first in the list.

Unfortunately the code at https://github.com/linnovate/mean seems poorly engineered.

In February I fell in the trap myself. The site mean.io had a catchy design and the Github repo had 1000+ stars. The idea of questioning the quality did not even pass through my mind. I started experimenting with it but it did not take too long to stumble upon things that were not working, and puzzling pieces of code.

The commit history was also pretty concerning. They re-engineered the code and directory structure multiple times, and merging the new changes is too time consuming.

The nice things about both mean.io and mean.js code is that they come with Bootstrap integration. They also come with Facebook, Github, Linkedin etc authentication through PassportJs and an example of a model (Article) on the backend on MongoDB that sync with the frontend model with AngularJS.

According to Linnovate's website:

Linnovate is the leading Open Source company in Israel, with the most experienced team in the country, dedicated to the creation of high-end open source solutions. Linnovate is the only company in Israel which gives an A-Z services for enterprises for building and maintaining their next web project.

From the website it looks like that their core skill set is Drupal (a PHP content management system) and only lately they started using Node.js and AngularJS.

Lately I was reading the Mean.js Blog and things became clearer. My understanding is that the main Javascript developer (Amos Haviv) left Linnovate to work on Mean.js leaving MEAN.io project with people that are novice Node.js developers that are slowing understanding how things are supposed to work.

In the future things may change but for now I would avoid to use mean.io. If you are looking for a boilerplate for a quickstart Mean.js seems a better option than mean.io.

Programmatically generate video or animated GIF in Python?

I'd recommend not using images2gif from visvis because it has problems with PIL/Pillow and is not actively maintained (I should know, because I am the author).

Instead, please use imageio, which was developed to solve this problem and more, and is intended to stay.

Quick and dirty solution:

import imageio
images = []
for filename in filenames:
    images.append(imageio.imread(filename))
imageio.mimsave('/path/to/movie.gif', images)

For longer movies, use the streaming approach:

import imageio
with imageio.get_writer('/path/to/movie.gif', mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)

How to save local data in a Swift app?

They Say Use NSUserDefaults

When I was implementing long term (after app close) data storage for the first time, everything I read online pointed me towards NSUserDefaults. However, I wanted to store a dictionary and, although possible, it was proving to be a pain. I spent hours trying to get type-errors to go away.

NSUserDefaults is Also Limited in Function

Further reading revealed how the read/write of NSUserDefaults really forces the app to read/write everything or nothing, all at once, so it isn't efficient. Then I learned that retrieving an array isn't straight forward. I realized that if you're storing more than a few strings or booleans, NSUserDefaults really isn't ideal.

It's also not scalable. If you're learning how to code, learn the scalable way. Only use NSUserDefaults for storing simple strings or booleans related to preferences. Store arrays and other data using Core Data, it's not as hard as they say. Just start small.

Update: Also, if you add Apple Watch support, there's another potential consideration. Your app's NSUserDefaults is now automatically sent to the Watch Extension.

Using Core Data

So I ignored the warnings about Core Data being a more difficult solution and started reading. Within three hours I had it working. I had my table array being saved in Core Data and reloading the data upon opening the app back up! The tutorial code was easy enough to adapt and I was able to have it store both title and detail arrays with only a little extra experimenting.

So for anyone reading this post who's struggling with NSUserDefault type issues or whose need is more than storing strings, consider spending an hour or two playing with core data.

Here's the tutorial I read:

http://www.raywenderlich.com/85578/first-core-data-app-using-swift

If you didn't check "Core Data"

If you didn't check "Core Data"when you created your app, you can add it after and it only takes five minutes:

http://craig24.com/2014/12/how-to-add-core-data-to-an-existing-swift-project-in-xcode/

http://blog.zeityer.com/post/119012600864/adding-core-data-to-an-existing-swift-project

How to Delete from Core Data Lists

Delete Data from Coredata Swift

using javascript to detect whether the url exists before display in iframe

I created this method, it is ideal because it aborts the connection without downloading it in its entirety, ideal for checking if videos or large images exist, decreasing the response time and the need to download the entire file

// if-url-exist.js v1
function ifUrlExist(url, callback) {
    let request = new XMLHttpRequest;
    request.open('GET', url, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.setRequestHeader('Accept', '*/*');
    request.onprogress = function(event) {
        let status = event.target.status;
        let statusFirstNumber = (status).toString()[0];
        switch (statusFirstNumber) {
            case '2':
                request.abort();
                return callback(true);
            default:
                request.abort();
                return callback(false);
        };
    };
    request.send('');
};

Example of use:

ifUrlExist(url, function(exists) {
    console.log(exists);
});

Convert named list to vector with values only

Use unlist with use.names = FALSE argument.

unlist(myList, use.names=FALSE)