Programs & Examples On #Thread exceptions

Python Loop: List Index Out of Range

When you call for i in a:, you are getting the actual elements, not the indexes. When we reach the last element, that is 3, b.append(a[i+1]-a[i]) looks for a[4], doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like

for i in range(0, len(a)-1): Do something

Your current code won't work yet for the do something part though ;)

How do I recognize "#VALUE!" in Excel spreadsheets?

in EXCEL 2013 i had to use IF function 2 times: 1st to identify error with ISERROR and 2nd to identify the specific type of error by ERROR.TYPE=3 in order to address this type of error. This way you can differentiate between error you want and other types.

When is a language considered a scripting language?

I always looked at scripting languages as a means to communicate with some sort of application or program. In contrast, a language which is compiled actually creates the program itself.

Now keep in mind that a scripting language usually adds on to or modifies the program that was initially created with a language that was compiled. Thus, it can certainly be part of the larger picture but the initial binaries are first created with a language that is compiled.

So I could create a scripting language which lets users perform various actions or customize my program. My program would interpret the scripted code and in turn call some kind of function. This is just a basic example. It just gives you a way to dynamically call routines within the program.

My program would have to parse the scripted code (you could refer to these as commands) and execute whatever action was intended in real time.

I see this question was already answered several times but I thought I would add my way of looking at things into the mix. Granted, some folks may disagree with this answer but this way of thinking has always helped me.

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

The issue here is that ng-repeat creates its own scope, so when you do selected=$index it creates a new a selected property in that scope rather than altering the existing one. To fix this you have two options:

Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:

$scope.selected = {value: 0};

<a ng-click="selected.value = $index">A{{$index}}</a>

See plunker

or

Use the $parent variable to access the correct property. Though less recommended as it increases coupling between scopes

<a ng-click="$parent.selected = $index">A{{$index}}</a>

See plunker

how to parse xml to java object?

One thing that is really important to understand considering you have an XML file as :

<customer id="100">
    <Age>29</Age>
    <NAME>mkyong</NAME>
</customer>

I am sorry to inform you but :

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

will not help you, as it tries to look for "age" instead of "Age" element name from the XML.

I encourage you to manually specify the element name matching the one in the XML file :

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

And if you have for example :

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Customer {
...

It means it will use java beans by default, and at this time if you specify that you must not set another

@XmlElement(name="NAME")

annotation above a setter method for an element <NAME>..</NAME> it will fail saying that there cannot be two elements on one single variables.

I hope that it helps.

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

A variation of Lea Verou solution with perfect indentation in multi-line entries could be something like this:

ul{
    list-style: none;
    position: relative;
    padding: 0;
    margin: 0;
}

li{
    padding-left: 1.5em; 
}

li:before {
    position: absolute;
    content: "•";
    color: red;
    left: 0;
}

Django. Override save for model

I have found one another simple way to store the data into the database

models.py

class LinkModel(models.Model):
    link = models.CharField(max_length=500)
    shortLink = models.CharField(max_length=30,unique=True)

In database I have only 2 variables

views.py

class HomeView(TemplateView):
    def post(self,request, *args, **kwargs):
        form = LinkForm(request.POST)

        if form.is_valid():
            text = form.cleaned_data['link'] # text for link

        dbobj = LinkModel()
        dbobj.link = text
        self.no = self.gen.generateShortLink() # no for shortLink
        dbobj.shortLink = str(self.no)
        dbobj.save()         # Saving from views.py

In this I have created the instance of model in views.py only and putting/saving data into 2 variables from views only.

What is the apply function in Scala?

1 - Treat functions as objects.

2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.

Handling InterruptedException in Java

The correct default choice is add InterruptedException to your throws list. An Interrupt indicates that another thread wishes your thread to end. The reason for this request is not made evident and is entirely contextual, so if you don't have any additional knowledge you should assume it's just a friendly shutdown, and anything that avoids that shutdown is a non-friendly response.

Java will not randomly throw InterruptedException's, all advice will not affect your application but I have run into a case where developer's following the "swallow" strategy became very inconvenient. A team had developed a large set of tests and used Thread.Sleep a lot. Now we started to run the tests in our CI server, and sometimes due to defects in the code would get stuck into permanent waits. To make the situation worse, when attempting to cancel the CI job it never closed because the Thread.Interrupt that was intended to abort the test did not abort the job. We had to login to the box and manually kill the processes.

So long story short, if you simply throw the InterruptedException you are matching the default intent that your thread should end. If you can't add InterruptedException to your throw list, I'd wrap it in a RuntimeException.

There is a very rational argument to be made that InterruptedException should be a RuntimeException itself, since that would encourage a better "default" handling. It's not a RuntimeException only because the designers stuck to a categorical rule that a RuntimeException should represent an error in your code. Since an InterruptedException does not arise directly from an error in your code, it's not. But the reality is that often an InterruptedException arises because there is an error in your code, (i.e. endless loop, dead-lock), and the Interrupt is some other thread's method for dealing with that error.

If you know there is rational cleanup to be done, then do it. If you know a deeper cause for the Interrupt, you can take on more comprehensive handling.

So in summary your choices for handling should follow this list:

  1. By default, add to throws.
  2. If not allowed to add to throws, throw RuntimeException(e). (Best choice of multiple bad options)
  3. Only when you know an explicit cause of the Interrupt, handle as desired. If your handling is local to your method, then reset interrupted by a call to Thread.currentThread().interrupt().

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

Can I set up HTML/Email Templates with ASP.NET?

Similar to Canavar's answer, but instead of NVelocity, I always use "StringTemplate" which I load the template from a configuration file, or load an external file using File.ReadAllText() and set the values.

It's a Java project but the C# port is solid and I've used it in several projects (just used it for email templating using the template in an external file).

Alternatives are always good.

Android Studio drawable folders

Actually you have selected Android from the tab change it to project.

Steps

enter image description here

Then you will found all folders.

enter image description here

OpenMP set_num_threads() is not working

Besides calling omp_get_num_threads() outside of the parallel region in your case, calling omp_set_num_threads() still doesn't guarantee that the OpenMP runtime will use exactly the specified number of threads. omp_set_num_threads() is used to override the value of the environment variable OMP_NUM_THREADS and they both control the upper limit of the size of the thread team that OpenMP would spawn for all parallel regions (in the case of OMP_NUM_THREADS) or for any consequent parallel region (after a call to omp_set_num_threads()). There is something called dynamic teams that could still pick smaller number of threads if the run-time system deems it more appropriate. You can disable dynamic teams by calling omp_set_dynamic(0) or by setting the environment variable OMP_DYNAMIC to false.

To enforce a given number of threads you should disable dynamic teams and specify the desired number of threads with either omp_set_num_threads():

omp_set_dynamic(0);     // Explicitly disable dynamic teams
omp_set_num_threads(4); // Use 4 threads for all consecutive parallel regions
#pragma omp parallel ...
{
    ... 4 threads used here ...
}

or with the num_threads OpenMP clause:

omp_set_dynamic(0);     // Explicitly disable dynamic teams
// Spawn 4 threads for this parallel region only
#pragma omp parallel ... num_threads(4)
{
    ... 4 threads used here ...
}

Setting Remote Webdriver to run tests in a remote computer using Java

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

How do I programmatically set the value of a select box element using JavaScript?

function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);

how to get current datetime in SQL?

NOW() returns 2009-08-05 15:13:00

CURDATE() returns 2009-08-05

CURTIME() returns 15:13:00

How to download fetch response in react as file

I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was

onClick = () => {
  // do something to compute or go fetch
  // the url we need from the server
  const url = goComputeOrFetchURL();

  // window.location forces the browser to prompt the user if they want to download it
  window.location = url
}

render() {
  return (
    <Button onClick={ this.onClick } />
  );
}

MVC pattern on Android

According to the explanation that the Xamarin team explained (on the iOS MVC "I know it seems weird, but wait a second"):

  • The model (data or application logic),
  • The view (user interface), and
  • The controller (code behind).

I can say this:

The model on Android is simply the parcelable object. The view is the XML layout, and the controller is the (activity + its fragment).

*This is just my opinion, not from any resource or a book.

How to get MAC address of your machine using a C program?

Expanding on the answer given by @user175104 ...

std::vector<std::string> GetAllFiles(const std::string& folder, bool recursive = false)
{
  // uses opendir, readdir, and struct dirent.
  // left as an exercise to the reader, as it isn't the point of this OP and answer.
}

bool ReadFileContents(const std::string& folder, const std::string& fname, std::string& contents)
{
  // uses ifstream to read entire contents
  // left as an exercise to the reader, as it isn't the point of this OP and answer.
}

std::vector<std::string> GetAllMacAddresses()
{
  std::vector<std::string> macs;
  std::string address;

  // from: https://stackoverflow.com/questions/9034575/c-c-linux-mac-address-of-all-interfaces
  //  ... just read /sys/class/net/eth0/address

  // NOTE: there may be more than one: /sys/class/net/*/address
  //  (1) so walk /sys/class/net/* to find the names to read the address of.

  std::vector<std::string> nets = GetAllFiles("/sys/class/net/", false);
  for (auto it = nets.begin(); it != nets.end(); ++it)
  {
    // we don't care about the local loopback interface
    if (0 == strcmp((*it).substr(-3).c_str(), "/lo"))
      continue;
    address.clear();
    if (ReadFileContents(*it, "address", address))
    {
      if (!address.empty())
      {
        macs.push_back(address);
      }
    }
  }
  return macs;
}

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

This CORS issue wasn't further elaborated (for other causes).

I'm having this issue currently under different reason. My front end is returning 'Access-Control-Allow-Origin' header error as well.

Just that I've pointed the wrong URL so this header wasn't reflected properly (in which i kept presume it did). localhost (front end) -> call to non secured http (supposed to be https), make sure the API end point from front end is pointing to the correct protocol.

Append a tuple to a list - what's the difference between two ways?

Because tuple(3, 4) is not the correct syntax to create a tuple. The correct syntax is -

tuple([3, 4])

or

(3, 4)

You can see it from here - https://docs.python.org/2/library/functions.html#tuple

How to keep the spaces at the end and/or at the beginning of a String?

use "" with the string resource value.

Example :

<string>"value with spaces"</string>

OR

use \u0020 code for spaces.

Copy row but with new id

SET @table = 'the_table';
SELECT GROUP_CONCAT(IF(COLUMN_NAME IN ('id'), 0, CONCAT("\`", COLUMN_NAME, "\`"))) FROM INFORMATION_SCHEMA.COLUMNS
                  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = @table INTO @columns;
SET @s = CONCAT('INSERT INTO ', @table, ' SELECT ', @columns,' FROM ', @table, ' WHERE id=1');
PREPARE stmt FROM @s;
EXECUTE stmt;

How to POST using HTTPclient content type = application/x-www-form-urlencoded

The best solution for me is:

// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");

// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}

Why do access tokens expire?

It is essentially a security measure. If your app is compromised, the attacker will only have access to the short-lived access token and no way to generate a new one.

Refresh tokens also expire but they are supposed to live much longer than the access token.

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

In my particular case, I had a similar error on a legacy website used in my organization. To solve the issue, I had to list the website a a "Trusted site".

To do so:

  • Click the Tools button, and then Internet options.
  • Go on the Security tab.
  • Click on Trusted sites and then on the sites button.
  • Enter the url of the website and click on Add.

I'm leaving this here in the remote case it will help someone.

stdcall and cdecl

Those things are Compiler- and Platform-specific. Neither the C nor the C++ standard say anything about calling conventions except for extern "C" in C++.

how does a caller know if it should free up the stack ?

The caller knows the calling convention of the function and handles the call accordingly.

At the call site, does the caller know if the function being called is a cdecl or a stdcall function ?

Yes.

How does it work ?

It is part of the function declaration.

How does the caller know if it should free up the stack or not ?

The caller knows the calling conventions and can act accordingly.

Or is it the linkers responsibility ?

No, the calling convention is part of a function's declaration so the compiler knows everything it needs to know.

If a function which is declared as stdcall calls a function(which has a calling convention as cdecl), or the other way round, would this be inappropriate ?

No. Why should it?

In general, can we say that which call will be faster - cdecl or stdcall ?

I don't know. Test it.

How do I start a program with arguments when debugging?

My suggestion would be to use Unit Tests.

In your application do the following switches in Program.cs:

#if DEBUG
    public class Program
#else
    class Program
#endif

and the same for static Main(string[] args).

Or alternatively use Friend Assemblies by adding

[assembly: InternalsVisibleTo("TestAssembly")]

to your AssemblyInfo.cs.

Then create a unit test project and a test that looks a bit like so:

[TestClass]
public class TestApplication
{
    [TestMethod]
    public void TestMyArgument()
    {
        using (var sw = new StringWriter())
        {
            Console.SetOut(sw); // this makes any Console.Writes etc go to sw

            Program.Main(new[] { "argument" });

            var result = sw.ToString();

            Assert.AreEqual("expected", result);
        }
    }
}

This way you can, in an automated way, test multiple inputs of arguments without having to edit your code or change a menu setting every time you want to check something different.

Any easy way to use icons from resources?

On Form_Load:

this.Icon = YourProjectNameSpace.Resources.YourResourceName.YouAppIconName;

Sort a List of Object in VB.NET

you must implement IComparer interface.

In this sample I've my custom object JSONReturn, I implement my class like this :

Friend Class JSONReturnComparer
    Implements IComparer(of JSONReturn)

    Public Function Compare(x As JSONReturn, y As JSONReturn) As Integer Implements    IComparer(Of JSONReturn).Compare
        Return String.Compare(x.Name, y.Name)
    End Function

End Class

I call my sort List method like this : alResult.Sort(new JSONReturnComparer())

Maybe it could help you

Material effect on button with background color

Use backgroundTint instead of background

Referring to the null object in Python

Use f string for getting this solved.

year=None
year_val= 'null' if year is None else  str(year)
print(f'{year_val}')

null

How to get Top 5 records in SqLite?

select * from [Table_Name] limit 5

How do I get the height and width of the Android Navigation Bar programmatically?

The NavigationBar height varies for some devices, but as well for some orientations. First you have to check if the device has a navbar, then if the device is a tablet or a not-tablet (phone) and finally you have to look at the orientation of the device in order to get the correct height.

public int getNavBarHeight(Context c) {
         int result = 0;
         boolean hasMenuKey = ViewConfiguration.get(c).hasPermanentMenuKey();
         boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);

         if(!hasMenuKey && !hasBackKey) {
             //The device has a navigation bar
             Resources resources = c.getResources();

             int orientation = resources.getConfiguration().orientation;
             int resourceId;
             if (isTablet(c)){
                 resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape", "dimen", "android");
             }  else {
                 resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_width", "dimen", "android");     
             }

             if (resourceId > 0) {
                 return resources.getDimensionPixelSize(resourceId);
             }
         }
         return result;
} 


private boolean isTablet(Context c) {
    return (c.getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK)
            >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}

Simple logical operators in Bash

What you've written actually almost works (it would work if all the variables were numbers), but it's not an idiomatic way at all.

  • (…) parentheses indicate a subshell. What's inside them isn't an expression like in many other languages. It's a list of commands (just like outside parentheses). These commands are executed in a separate subprocess, so any redirection, assignment, etc. performed inside the parentheses has no effect outside the parentheses.
    • With a leading dollar sign, $(…) is a command substitution: there is a command inside the parentheses, and the output from the command is used as part of the command line (after extra expansions unless the substitution is between double quotes, but that's another story).
  • { … } braces are like parentheses in that they group commands, but they only influence parsing, not grouping. The program x=2; { x=4; }; echo $x prints 4, whereas x=2; (x=4); echo $x prints 2. (Also braces require spaces around them and a semicolon before closing, whereas parentheses don't. That's just a syntax quirk.)
    • With a leading dollar sign, ${VAR} is a parameter expansion, expanding to the value of a variable, with possible extra transformations.
  • ((…)) double parentheses surround an arithmetic instruction, that is, a computation on integers, with a syntax resembling other programming languages. This syntax is mostly used for assignments and in conditionals.
    • The same syntax is used in arithmetic expressions $((…)), which expand to the integer value of the expression.
  • [[ … ]] double brackets surround conditional expressions. Conditional expressions are mostly built on operators such as -n $variable to test if a variable is empty and -e $file to test if a file exists. There are also string equality operators: "$string1" == "$string2" (beware that the right-hand side is a pattern, e.g. [[ $foo == a* ]] tests if $foo starts with a while [[ $foo == "a*" ]] tests if $foo is exactly a*), and the familiar !, && and || operators for negation, conjunction and disjunction as well as parentheses for grouping. Note that you need a space around each operator (e.g. [[ "$x" == "$y" ]], not [[ "$x"=="$y" ]]), and a space or a character like ; both inside and outside the brackets (e.g. [[ -n $foo ]], not [[-n $foo]]).
  • [ … ] single brackets are an alternate form of conditional expressions with more quirks (but older and more portable). Don't write any for now; start worrying about them when you find scripts that contain them.

This is the idiomatic way to write your test in bash:

if [[ $varA == 1 && ($varB == "t1" || $varC == "t2") ]]; then

If you need portability to other shells, this would be the way (note the additional quoting and the separate sets of brackets around each individual test, and the use of the traditional = operator rather than the ksh/bash/zsh == variant):

if [ "$varA" = 1 ] && { [ "$varB" = "t1" ] || [ "$varC" = "t2" ]; }; then

React Native fetch() Network Request Failed

You can handle it using this :

catch((error) => {
      this.setState({
        typing_animation_button: false,
      });
      console.log(error);
      if ('Timeout' || 'Network request failed') {
        toast_show = true;
        toast_type = 'error';
        toast_text = 'Network failure';
      }
      this.setState({
        disable_button: false,
      });
    });

convert string to char*

There are many ways. Here are at least five:

/*
 * An example of converting std::string to (const)char* using five
 * different methods. Error checking is emitted for simplicity.
 *
 * Compile and run example (using gcc on Unix-like systems):
 *
 *  $ g++ -Wall -pedantic -o test ./test.cpp
 *  $ ./test
 *  Original string (0x7fe3294039f8): hello
 *  s1 (0x7fe3294039f8): hello
 *  s2 (0x7fff5dce3a10): hello
 *  s3 (0x7fe3294000e0): hello
 *  s4 (0x7fe329403a00): hello
 *  s5 (0x7fe329403a10): hello
 */

#include <alloca.h>
#include <string>
#include <cstring>

int main()
{
    std::string s0;
    const char *s1;
    char *s2;
    char *s3;
    char *s4;
    char *s5;

    // This is the initial C++ string.
    s0 = "hello";

    // Method #1: Just use "c_str()" method to obtain a pointer to a
    // null-terminated C string stored in std::string object.
    // Be careful though because when `s0` goes out of scope, s1 points
    // to a non-valid memory.
    s1 = s0.c_str();

    // Method #2: Allocate memory on stack and copy the contents of the
    // original string. Keep in mind that once a current function returns,
    // the memory is invalidated.
    s2 = (char *)alloca(s0.size() + 1);
    memcpy(s2, s0.c_str(), s0.size() + 1);

    // Method #3: Allocate memory dynamically and copy the content of the
    // original string. The memory will be valid until you explicitly
    // release it using "free". Forgetting to release it results in memory
    // leak.
    s3 = (char *)malloc(s0.size() + 1);
    memcpy(s3, s0.c_str(), s0.size() + 1);

    // Method #4: Same as method #3, but using C++ new/delete operators.
    s4 = new char[s0.size() + 1];
    memcpy(s4, s0.c_str(), s0.size() + 1);

    // Method #5: Same as 3 but a bit less efficient..
    s5 = strdup(s0.c_str());

    // Print those strings.
    printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
    printf("s1 (%p): %s\n", s1, s1);
    printf("s2 (%p): %s\n", s2, s2);
    printf("s3 (%p): %s\n", s3, s3);
    printf("s4 (%p): %s\n", s4, s4);
    printf("s5 (%p): %s\n", s5, s5);

    // Release memory...
    free(s3);
    delete [] s4;
    free(s5);
}

Limit file format when using <input type="file">?

As mentioned in previous answers we cannot restrict user to select files for only given file formats. But it's really handy to use the accept tag on file attribute in html.

As for validation, we have to do it at the server side. We can also do it at client side in js but its not a foolproof solution. We must validate at server side.

For these requirements I really prefer struts2 Java web application development framework. With its built-in file upload feature, uploading files to struts2 based web apps is a piece of cake. Just mention the file formats that we would like to accept in our application and all the rest is taken care of by the core of framework itself. You can check it out at struts official site.

How to load up CSS files using Javascript?

There is a general jquery plugin that loads css and JS files synch and asych on demand. It also keeps track off what is already been loaded :) see: http://code.google.com/p/rloader/

hadoop copy a local file system folder to HDFS

You can use :

1.LOADING DATA FROM LOCAL FILE TO HDFS

Syntax:$hadoop fs –copyFromLocal

EX: $hadoop fs –copyFromLocal localfile1 HDIR

2. Copying data From HDFS to Local

Sys: $hadoop fs –copyToLocal < new file name>

EX: $hadoop fs –copyToLocal hdfs/filename myunx;

Inherit CSS class

As others have already mentioned, there is no concept of OOP inheritance in CSS. But, i have always used a work around for this.

Let's say i have two buttons, and except the background image URL, all other attributes are common. This is how i did it.

/*button specific attributes*/
.button1 {
    background-image: url("../Images/button1.gif");
}
/*button specific attributes*/
.button2 {
    background-image: url("../Images/button2.gif");
}

/*These are the shared attributes */
.button1, .button2 {
    cursor: pointer;
    background-repeat: no-repeat;
    width: 25px;
    height: 20px;
    border: 0;
}

Hope this helps somebody.

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

I made a MixIn class which you may inherit to be able to add a read_only iterable field which will disable and secure fields on the non-first edit:

(Based on Daniel's and Muhuk's answers)

from django import forms
from django.db.models.manager import Manager

# I used this instead of lambda expression after scope problems
def _get_cleaner(form, field):
    def clean_field():
         value = getattr(form.instance, field, None)
         if issubclass(type(value), Manager):
             value = value.all()
         return value
    return clean_field

class ROFormMixin(forms.BaseForm):
    def __init__(self, *args, **kwargs):
        super(ROFormMixin, self).__init__(*args, **kwargs)
        if hasattr(self, "read_only"):
            if self.instance and self.instance.pk:
                for field in self.read_only:
                    self.fields[field].widget.attrs['readonly'] = "readonly"
                    setattr(self, "clean_" + field, _get_cleaner(self, field))

# Basic usage
class TestForm(AModelForm, ROFormMixin):
    read_only = ('sku', 'an_other_field')

"Can't find Project or Library" for standard VBA functions

I've had this error on and off for around two years in a several XLSM files (which is most annoying as when it occurs there is nothing wrong with the file! - I suspect orphaned Excel processes are part of the problem)

The most efficient solution I had found has been to use Python with oletools https://github.com/decalage2/oletools/wiki/Install and extract the VBA code all the modules and save in a text file.

Then I simply rename the file to zip file (backup just in case!), open up this zip file and delete the xl/vbaProject.bin file. Rename back to XLSX and should be good to go.

Copy in the saved VBA code (which will need cleaning of line breaks, comments and other stuff. Will also need to add in missing libraries.

This has saved me when other methods haven't.

YMMV.

Fit Image in ImageButton in Android

Refer below link and try to find what you really want:

ImageView.ScaleType CENTER Center the image in the view, but perform no scaling.

ImageView.ScaleType CENTER_CROP Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).

ImageView.ScaleType CENTER_INSIDE Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

ImageView.ScaleType FIT_CENTER Scale the image using CENTER.

ImageView.ScaleType FIT_END Scale the image using END.

ImageView.ScaleType FIT_START Scale the image using START.

ImageView.ScaleType FIT_XY Scale the image using FILL.

ImageView.ScaleType MATRIX Scale using the image matrix when drawing.

https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

How to set the height of table header in UITableView?

If you changed height of tableView's headerView, just reset headerView's frame, then, reset headerView of tableView:

self.headerView.frame = newFrame;
self.tableView.tableHeaderView = self.headerView;

How to parse a String containing XML in Java and retrieve the value of the root node?

There is doing XML reading right, or doing the dodgy just to get by. Doing it right would be using proper document parsing.

Or... dodgy would be using custom text parsing with either wisuzu's response or using regular expressions with matchers.

Drop view if exists

Regarding the error

'CREATE VIEW' must be the first statement in a query batch.

Microsoft SQL Server has a quirky reqirement that CREATE VIEW be the only statement in a batch. This is also true of a few other statements, such as CREATE FUNCTION. It is not true of CREATE TABLE, so go figure …

The solution is to send your script to the server in small batches. One way to do this is to select a single statement and execute it. This is clearly inconvenient.

The more convenient solution is to get the client to send the script in small isolated batches.

The GO keyword is not strictly an SQL command, which is why you can’t end it with a semicolon like real SQL commands. Instead it is an instruction to the client to break the script at this point and to send the portion as a batch.

As a result, you end up writing something like:

DROP VIEW IF EXISTS … ;
GO
CREATE VIEW … AS … ;
GO

None of the other database servers I have encountered (PostgreSQL, MySQL, Oracle, SQLite) have this quirk, so the requirement appears to be Microsoft Only.

How to swap String characters in Java?

The following line of code will swap the first two characters in str:

return str.charAt(1) + str.charAt(0) + str.substring(2);

How to load specific image from assets with Swift

You can easily pick image from asset without UIImage(named: "green-square-Retina").

Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.

See this Stackoverflow answer for reference.

Position an element relative to its container

Absolute positioning positions an element relative to its nearest positioned ancestor. So put position: relative on the container, then for child elements, top and left will be relative to the top-left of the container so long as the child elements have position: absolute. More information is available in the CSS 2.1 specification.

How to get post slug from post in WordPress?

Wordpress: Get post/page slug

<?php 
// Custom function to return the post slug
function the_slug($echo=true){
  $slug = basename(get_permalink());
  do_action('before_slug', $slug);
  $slug = apply_filters('slug_filter', $slug);
  if( $echo ) echo $slug;
  do_action('after_slug', $slug);
  return $slug;
}
?>
<?php if (function_exists('the_slug')) { the_slug(); } ?>

How to find the most recent file in a directory using .NET, and without looping?

Short and simple:

new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.LastWriteTime).FirstOrDefault();

Get time of specific timezone

before you get too excited this was written in 2011

if I were to do this these days I would use Intl.DateTimeFormat. Here is a link to give you an idea of what type of support this had in 2011

original answer now (very) outdated

Date.getTimezoneOffset()

The getTimezoneOffset() method returns the time difference between Greenwich Mean Time (GMT) and local time, in minutes.

For example, If your time zone is GMT+2, -120 will be returned.

Note: This method is always used in conjunction with a Date object.

var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
//output:The local time zone is: GMT 11

What is the difference between MacVim and regular Vim?

MacVim is just Vim. Anything you are used to do in Vim will work exactly the same way in MacVim.

MacVim is more integrated in the whole OS than Vim in the Terminal or even GVim in Linux, it follows a lot of Mac OS X's conventions.

If you work mainly with GUI apps (YummyFTP + GitX + Charles, for example) you may prefer MacVim.

If you work mainly with CLI apps (ssh + svn + tcpdump, for example) you may prefer vim in the terminal.

Entering and leaving one realm (CLI) for the other (GUI) and vice-versa can be "expensive".

I use both MacVim and Vim depending on the task and the context: if I'm in CLI-land I'll just type vim filename and if I'm in GUI-land I'll just invoke Quicksilver and launch MacVim.

When I switched from TextMate I kind of liked the fact that MacVim supported almost all of the regular shortcuts Mac users are accustomed to. I added some of my own, mimiking TextMate but, since I was working in multiple environments I forced my self to learn the vim way. Now I use both MacVim and Vim almost exactly the same way. Using one or the other is just a question of context for me.

Also, like El Isra said, the default vim (CLI) in OS X is slightly outdated. You may install an up-to-date version via MacPorts or you can install MacVim and add an alias to your .profile:

alias vim='/path/to/MacVim.app/Contents/MacOS/Vim'

to have the same vim in MacVim and Terminal.app.

Another difference is that many great colorschemes out there work out of the box in MacVim but look terrible in the Terminal.app which only supports 8 colors (+ highlights) but you can use iTerm — which can be set up to support 256 colors — instead of Terminal.

So… basically my advice is to just use both.

EDIT: I didn't try it but the latest version of Terminal.app (in 10.7) is supposed to support 256 colors. I'm still on 10.6.x at work so I'll still use iTerm2 for a while.

EDIT: An even better way to use MacVim's CLI executable in your shell is to move the mvim script bundled with MacVim somewhere in your $PATH and use this command:

$ mvim -v

EDIT: Yes, Terminal.app now supports 256 colors. So if you don't need iTerm2's advanced features you can safely use the default terminal emulator.

Converting Swagger specification JSON to HTML documentation

I was not satisfied with swagger-codegen when I was looking for a tool to do this, so I wrote my own. Have a look at bootprint-swagger

The main goal compared to swagger-codegen is to provide an easy setup (though you'll need nodejs). And it should be easy to adapt styling and templates to your own needs, which is a core functionality of the bootprint-project

Unable to create Genymotion Virtual Device

Oracle VM ware has an update for Windows 10. I was getting this error until I installed this update.

How to list running screen sessions?

To list all of the screen sessions for a user, run the following command as that user:

screen -ls

To see all screen sessions on a specific machine you can do:

ls -laR /var/run/screen/

I get this on my machine:

gentle ~ # ls -laR /var/run/screen/

/var/run/screen/:
total 1
drwxrwxr-x  4 root utmp   96 Mar  1  2005 .
drwxr-xr-x 10 root root  840 Feb  1 03:10 ..
drwx------  2 josh users  88 Jan 13 11:33 S-josh
drwx------  2 root root   48 Feb 11 10:50 S-root

/var/run/screen/S-josh:
total 0
drwx------ 2 josh users 88 Jan 13 11:33 .
drwxrwxr-x 4 root utmp  96 Mar  1  2005 ..
prwx------ 1 josh users  0 Feb 11 10:41 12931.pts-0.gentle

/var/run/screen/S-root:
total 0
drwx------ 2 root root 48 Feb 11 10:50 .
drwxrwxr-x 4 root utmp 96 Mar  1  2005 ..

This is a rather brilliantly Unixy use of Unix Sockets wrapped in filesystem permissions to handle security, state, and streams.

is there a require for json in node.js

A nifty non-caching async one liner for node 15 modules:

import { readFile } from 'fs/promises';

const data = await readFile('{{ path }}').then(json => JSON.parse(json)).catch(() => null);

Start an external application from a Google Chrome Extension?

There's an extension for Chrome (SimpleGet) that has a plugin for Windows and Linux that can execute an app with command line parameters.....
http://pinel.cc/
http://code.google.com/p/simple-get/
http://www.chromeextensions.org/other/simple-get/

REST API Best practice: How to accept list of parameter values as input

First:

I think you can do it 2 ways

http://our.api.com/Product/<id> : if you just want one record

http://our.api.com/Product : if you want all records

http://our.api.com/Product/<id1>,<id2> :as James suggested can be an option since what comes after the Product tag is a parameter

Or the one I like most is:

You can use the the Hypermedia as the engine of application state (HATEOAS) property of a RestFul WS and do a call http://our.api.com/Product that should return the equivalent urls of http://our.api.com/Product/<id> and call them after this.

Second

When you have to do queries on the url calls. I would suggest using HATEOAS again.

1) Do a get call to http://our.api.com/term/pumas/productType/clothing/color/black

2) Do a get call to http://our.api.com/term/pumas/productType/clothing,bags/color/black,red

3) (Using HATEOAS) Do a get call to `http://our.api.com/term/pumas/productType/ -> receive the urls all clothing possible urls -> call the ones you want (clothing and bags) -> receive the possible color urls -> call the ones you want

How do I install chkconfig on Ubuntu?

As mentioned by @jerry you can add services with the below command.

update-rc.d <service> defaults
update-rc.d <service> start 20 3 4 5
update-rc.d -f <service>  remove

To validate them check the above commands you can check /etc/rc*.d/ directory where service start with "k" means it will not execute during the boot and service start with "S" will start during the boot.

# for runlevel symlinks:
ls /etc/rc*.d/

In the below screenshot you can see apache2 starting in runlevel2(S02apache2) and stopping in runlevel1(K01apache2)

enter image description here

enter image description here

You can also check the service status with the below command where "+" means service is in running state "-" is in stopped.

service --status-all

enter image description here

OR

install sysv-rc-conf utility.

apt-get install sysv-rc-conf
example
sysv-rc-conf --level 2345 apach22 on
man sysv-rc-conf

CSS blur on background image but not on content

jsfiddle.

<div> 
    <img class="class" src="http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465">
    </img>
    <span>
        Hello World!
    </span>
</div>

What about this? No absolute positioning on div, but instead on img and span.

Get name of currently executing test in JUnit 4

Try this instead:

public class MyTest {
        @Rule
        public TestName testName = new TestName();

        @Rule
        public TestWatcher testWatcher = new TestWatcher() {
            @Override
            protected void starting(final Description description) {
                String methodName = description.getMethodName();
                String className = description.getClassName();
                className = className.substring(className.lastIndexOf('.') + 1);
                System.err.println("Starting JUnit-test: " + className + " " + methodName);
            }
        };

        @Test
        public void testA() {
                assertEquals("testA", testName.getMethodName());
        }

        @Test
        public void testB() {
                assertEquals("testB", testName.getMethodName());
        }
}

The output looks like this:

Starting JUnit-test: MyTest testA
Starting JUnit-test: MyTest testB

NOTE: This DOES NOT work if your test is a subclass of TestCase! The test runs but the @Rule code just never runs.

How to include JavaScript file or library in Chrome console?

As a follow-up to the answer of @maciej-bukowski above ^^^, in modern browsers as of now (spring 2017) that support async/await you can load as follows. In this example we load the load html2canvas library:

_x000D_
_x000D_
async function loadScript(url) {_x000D_
  let response = await fetch(url);_x000D_
  let script = await response.text();_x000D_
  eval(script);_x000D_
}_x000D_
_x000D_
let scriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js'_x000D_
loadScript(scriptUrl);
_x000D_
_x000D_
_x000D_

If you run the snippet and then open your browser's console you should see the function html2canvas() is now defined.

Checking if a file is a directory or just a file

You can call the stat() function and use the S_ISREG() macro on the st_mode field of the stat structure in order to determine if your path points to a regular file:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int is_regular_file(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISREG(path_stat.st_mode);
}

Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.

Go / golang time.Now().UnixNano() convert to milliseconds?

At https://github.com/golang/go/issues/44196 randall77 suggested

time.Now().Sub(time.Unix(0,0)).Milliseconds()

which exploits the fact that Go's time.Duration already have Milliseconds method.

Load a UIView from nib in Swift

Tested in Xcode 7 beta 4 , Swift 2.0 and iOS9 SDK . The following code will assign xib to the uiview. You can able to use this custom xib view in storyboard and access the IBOutlet object also.

import UIKit

@IBDesignable class SimpleCustomView:UIView
{
    var view:UIView!;

    @IBOutlet weak var lblTitle: UILabel!

   @IBInspectable var lblTitleText : String?
        {
        get{
            return lblTitle.text;
        }
        set(lblTitleText)
        {
            lblTitle.text = lblTitleText!;
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        loadViewFromNib ()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        loadViewFromNib ()
    }
    func loadViewFromNib() {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: "SimpleCustomView", bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
        view.frame = bounds
        view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        self.addSubview(view);



    }


}

Access customview programatically

self.customView =  SimpleCustomView(frame: CGRectMake(100, 100, 200, 200))
        self.view.addSubview(self.customView!);

Source code - https://github.com/karthikprabhuA/CustomXIBSwift

How to make div follow scrolling smoothly with jQuery?

This worked for me like a charm.

JavaScript:

$(function() { //doc ready
    if (!($.browser == "msie" && $.browser.version < 7)) {
        var target = "#floating", top = $(target).offset().top - parseFloat($(target).css("margin-top").replace(/auto/, 0));
        $(window).scroll(function(event) {
            if (top <= $(this).scrollTop()) {
                $(target).addClass("fixed");
            } else {
                $(target).removeClass("fixed");
            }
        });
    }
});

CSS:

#floating.fixed{
    position:fixed;
    top:0;
}

Source: http://jqueryfordesigners.com/fixed-floating-elements/

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Using Let's Encrypt certificates

Assuming you've created your certificates and private keys with Let's Encrypt in /etc/letsencrypt/live/you.com:

1. Create a PKCS #12 file

openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out pkcs.p12 \
        -name letsencrypt

This combines your SSL certificate fullchain.pem and your private key privkey.pem into a single file, pkcs.p12.

You'll be prompted for a password for pkcs.p12.

The export option specifies that a PKCS #12 file will be created rather than parsed (according to the manual).

2. Create the Java keystore

keytool -importkeystore -destkeystore keystore.jks -srckeystore pkcs.p12 \
        -srcstoretype PKCS12 -alias letsencrypt

If keystore.jks doesn't exist, it will be created containing the pkcs.12 file created above. Otherwise, you'll import pkcs.12 into the existing keystore.


These instructions are derived from the post "Create a Java Keystore (.JKS) from Let's Encrypt Certificates" on this blog.

Here's more on the different kind of files in /etc/letsencrypt/live/you.com/.

Replace non ASCII character from string

You can try something like this. Special Characters range for alphabets starts from 192, so you can avoid such characters in the result.

String name = "A função";

StringBuilder result = new StringBuilder();
for(char val : name.toCharArray()) {
    if(val < 192) result.append(val);
}
System.out.println("Result "+result.toString());

How to reset Android Studio

On Mac OS X with Android Studio >= 1.0.0

Run these lines:

rm -rf ~/Library/Application Support/AndroidStudio
rm -rf ~/Library/Caches/AndroidStudio 
rm -rf ~/Library/Logs/AndroidStudio
rm -rf ~/Library/Preferences/AndroidStudio

How to call same method for a list of objects?

It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.

I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:

map(do_something, a_list_of_objects)

This replaces a bunch of code that looks like this:

 do_something(a)
 do_something(b)
 do_something(c)
 ...

But can also be achieved with a pedestrian "for" loop:

  for obj in a_list_of_objects:
       do_something(obj)

The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.

You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):

  [ do_something(x) for x in a_list_of_objects ]

For methods, I suppose either of these would work (with the same reservations):

map(lambda x: x.method_call(), a_list_of_objects)

or

[ x.method_call() for x in a_list_of_objects ]

So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.

How to get info on sent PHP curl request

curl_getinfo() must be added before closing the curl handler

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
curl_close($ch);

how to fix java.lang.IndexOutOfBoundsException

Use if(index.length() < 0) for Integer

or

Use if(index.equals(null) for String

Differences between contentType and dataType in jQuery ajax function

From the documentation:

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

Type: String

When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

and:

dataType (default: Intelligent Guess (xml, json, script, or html))

Type: String

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

They're essentially the opposite of what you thought they were.

Converting VS2012 Solution to VS2010

Just to elaborate on Bhavin's excellent answer - editing the solution file works but you may still get the incompatible error (as David reported) if you had .NET 4.5 selected as the default .NET version in your VS2012 project and your VS2010 enviroment doesn't support that.

To quickly fix that, open the VS2012 .csproj file in a text editor and change the TargetFrameworkVersion down to 4.0 (from 4.5). VS2010 will then happily load the "edited" solution and projects.

You'll also have to edit an app.config files that have references to .NET 4.5 in a similar way to allow them to run on a .NET 4.0 environment.

Custom CSS for <audio> tag?

There are CSS options for the audio tag.

Like: html 5 audio tag width

But if you play around with it you'll see results can be unexpected - as of August 2012.

Git - Pushing code to two remotes

To send to both remote with one command, you can create a alias for it:

git config alias.pushall '!git push origin devel && git push github devel'

With this, when you use the command git pushall, it will update both repositories.

Posting JSON Data to ASP.NET MVC

I solved using a "manual" deserialization. I'll explain in code

public ActionResult MyMethod([System.Web.Http.FromBody] MyModel model)
{
 if (module.Fields == null && !string.IsNullOrEmpty(Request.Form["fields"]))
 {
   model.Fields = JsonConvert.DeserializeObject<MyFieldModel[]>(Request.Form["fields"]);
 }
 //... more code
}

Convert Month Number to Month Name Function in SQL

I think this is the best way to get the month name when you have the month number

Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )

Or

Select DateName( month , DateAdd( month , @MonthNumber , -1 ) )

jquery animate background position

You can also use math combination "-=" to move background

$(this).animate( {backgroundPositionX: "-=20px"} ,500);

How can I get an HTTP response body as a string?

Following is the code snippet which shows better way to handle the response body as a String whether it's a valid response or error response for the HTTP POST request:

BufferedReader reader = null;
OutputStream os = null;
String payload = "";
try {
    URL url1 = new URL("YOUR_URL");
    HttpURLConnection postConnection = (HttpURLConnection) url1.openConnection();
    postConnection.setRequestMethod("POST");
    postConnection.setRequestProperty("Content-Type", "application/json");
    postConnection.setDoOutput(true);
    os = postConnection.getOutputStream();
    os.write(eventContext.getMessage().getPayloadAsString().getBytes());
    os.flush();

    String line;
    try{
        reader = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
    }
    catch(IOException e){
        if(reader == null)
            reader = new BufferedReader(new InputStreamReader(postConnection.getErrorStream()));
    }
    while ((line = reader.readLine()) != null)
        payload += line.toString();
}       
catch (Exception ex) {
            log.error("Post request Failed with message: " + ex.getMessage(), ex);
} finally {
    try {
        reader.close();
        os.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

Python error "ImportError: No module named"

Linux: Imported modules are located in /usr/local/lib/python2.7/dist-packages

If you're using a module compiled in C, don't forget to chmod the .so file after sudo setup.py install.

sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so

getApplication() vs. getApplicationContext()

It seems to have to do with context wrapping. Most classes derived from Context are actually a ContextWrapper, which essentially delegates to another context, possibly with changes by the wrapper.

The context is a general abstraction that supports mocking and proxying. Since many contexts are bound to a limited-lifetime object such as an Activity, there needs to be a way to get a longer-lived context, for purposes such as registering for future notifications. That is achieved by Context.getApplicationContext(). A logical implementation is to return the global Application object, but nothing prevents a context implementation from returning a wrapper or proxy with a suitable lifetime instead.

Activities and services are more specifically associated with an Application object. The usefulness of this, I believe, is that you can create and register in the manifest a custom class derived from Application and be certain that Activity.getApplication() or Service.getApplication() will return that specific object of that specific type, which you can cast to your derived Application class and use for whatever custom purpose.

In other words, getApplication() is guaranteed to return an Application object, while getApplicationContext() is free to return a proxy instead.

Convert a Unicode string to a string in Python (containing extra symbols)

See unicodedata.normalize

title = u"Klüft skräms inför på fédéral électoral große"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
'Kluft skrams infor pa federal electoral groe'

Current date and time - Default in MVC razor

Before you return your model from the controller, set your ReturnDate property to DateTime.Now()

myModel.ReturnDate = DateTime.Now()

return View(myModel)

Your view is not the right place to set values on properties so the controller is the better place for this.

You could even have it so that the getter on ReturnDate returns the current date/time.

private DateTime _returnDate = DateTime.MinValue;
public DateTime ReturnDate{
   get{
     return (_returnDate == DateTime.MinValue)? DateTime.Now() : _returnDate;
   }
   set{_returnDate = value;}
}

How to change options of <select> with jQuery?

Removing and adding DOM element is slower than modification of existing one.

If your option sets have same length, you may do something like this:

$('#my-select option')
.each(function(index) {
    $(this).text('someNewText').val('someNewValue');
});

In case your new option set has different length, you may delete/add empty options you really need, using some technique described above.

Setting background colour of Android layout element

The above answers are nice.You can also go like this programmatically if you want

First, your layout should have an ID. Add it by writing following +id line in res/layout/*.xml

<RelativeLayout ...
...
android:id="@+id/your_layout_id"
...
</RelativeLayout>

Then, in your Java code, make following changes.

RelativeLayout rl = (RelativeLayout)findViewById(R.id.your_layout_id);
rl.setBackgroundColor(Color.RED);

apart from this, if you have the color defined in colors.xml, then also you can do programmatically :

rl.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.red));

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

How can I explicitly free memory in Python?

Others have posted some ways that you might be able to "coax" the Python interpreter into freeing the memory (or otherwise avoid having memory problems). Chances are you should try their ideas out first. However, I feel it important to give you a direct answer to your question.

There isn't really any way to directly tell Python to free memory. The fact of that matter is that if you want that low a level of control, you're going to have to write an extension in C or C++.

That said, there are some tools to help with this:

Generate random string/characters in JavaScript

function randomString (strLength, charSet) {
    var result = [];

    strLength = strLength || 5;
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    while (--strLength) {
        result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
    }

    return result.join('');
}

This is as clean as it will get. It is fast too, http://jsperf.com/ay-random-string.

make iframe height dynamic based on content inside- JQUERY/Javascript

The simple solution is to measure the width and height of the content area, and then use those measurements to calculate the bottom padding percentage.

In this case, the measurements are 1680 x 720 px, so the padding on the bottom is 720 / 1680 = 0.43 * 100, which comes out to 43%.

.canvas-container {    
    position: relative;
    padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
    height: 0;
    overflow: hidden;   
}

.canvas-container iframe {    
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;   
}

How to detect if a browser is Chrome using jQuery?

When I test the answer @IE, I got always "true". The better way is this which works also @IE:

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

As described in this answer: https://stackoverflow.com/a/4565120/1201725

Jasmine JavaScript Testing - toBe vs toEqual

Looking at the Jasmine source code sheds more light on the issue.

toBe is very simple and just uses the identity/strict equality operator, ===:

  function(actual, expected) {
    return {
      pass: actual === expected
    };
  }

toEqual, on the other hand, is nearly 150 lines long and has special handling for built in objects like String, Number, Boolean, Date, Error, Element and RegExp. For other objects it recursively compares properties.

This is very different from the behavior of the equality operator, ==. For example:

var simpleObject = {foo: 'bar'};
expect(simpleObject).toEqual({foo: 'bar'}); //true
simpleObject == {foo: 'bar'}; //false

var castableObject = {toString: function(){return 'bar'}};
expect(castableObject).toEqual('bar'); //false
castableObject == 'bar'; //true

Creating a Zoom Effect on an image on hover using CSS?

_x000D_
_x000D_
    .img-wrap:hover img {_x000D_
        transform: scale(0.8);_x000D_
    }_x000D_
    .img-wrap img {_x000D_
        display: block;_x000D_
        transition: all 0.3s ease 0s;_x000D_
        width: 100%;_x000D_
    }
_x000D_
    <div class="img-wrap">_x000D_
    <img src="http://www.sampleimages/images.jpg"/> // Your image_x000D_
    </div>
_x000D_
_x000D_
_x000D_

This code is only for zoom-out effect.Set the div "img-wrap" according to your styles and insert the above style results zoom-out effect.For zoom-in effect you must increase the scale value(eg: for zoom-in,use transform: scale(1.3);

Check if a string has white space

Here is my suggested validation:

var isValid = false;

// Check whether this entered value is numeric.
function checkNumeric() {
    var numericVal = document.getElementById("txt_numeric").value;

    if(isNaN(numericVal) || numericVal == "" || numericVal == null || numericVal.indexOf(' ') >= 0) {
        alert("Please, enter a numeric value!");
        isValid = false;
    } else {
        isValid = true;
    }
}

In SQL, is UPDATE always faster than DELETE+INSERT?

The question of speed is irrelevant without a specific speed problem.

If you are writing SQL code to make a change to an existing row, you UPDATE it. Anything else is incorrect.

If you're going to break the rules of how code should work, then you'd better have a damn good, quantified reason for it, and not a vague idea of "This way is faster", when you don't have any idea what "faster" is.

How to support placeholder attribute in IE8 and 9

You can use any one of these polyfills:

These scripts will add support for the placeholder attribute in browsers that do not support it, and they do not require jQuery!

React-Native Button style not work

Instead of using button . you can use Text in react native and then make in touchable

<TouchableOpacity onPress={this._onPressButton}> 
   <Text style = {'your custome style'}>
       button name
   </Text>
</TouchableOpacity >

Difference between Key, Primary Key, Unique Key and Index in MySQL

Primary key - we can put only one primary key on a table into a table and we can not left that column blank when we are entering the values into the table.

Unique Key - we can put more than one unique key on a table and we may left that column blank when we are entering the values into the table. column take unique values (not same) when we applied primary & unique key.

Python module for converting PDF to text

I have used pdftohtml with the -xml argument, read the result with subprocess.Popen(), that will give you x coord, y coord, width, height, and font, of every snippet of text in the pdf. I think this is what 'evince' probably uses too because the same error messages spew out.

If you need to process columnar data, it gets slightly more complicated as you have to invent an algorithm that suits your pdf file. The problem is that the programs that make PDF files don't really necessarily lay out the text in any logical format. You can try simple sorting algorithms and it works sometimes, but there can be little 'stragglers' and 'strays', pieces of text that don't get put in the order you thought they would. So you have to get creative.

It took me about 5 hours to figure out one for the pdf's I was working on. But it works pretty good now. Good luck.

Detect rotation of Android phone in the browser with JavaScript

To detect an orientation change on an Android browser, attach a listener to the orientationchange or resize event on window:

// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    alert('HOLY ROTATING SCREENS BATMAN:' + window.orientation + " " + screen.width);
}, false);

Check the window.orientation property to figure out which way the device is oriented. With Android phones, screen.width or screen.height also updates as the device is rotated. (this is not the case with the iPhone).

How to extend / inherit components?

just use inheritance,Extend parent class in child class and declare constructor with parent class parameter and this parameter use in super().

1.parent class
@Component({
    selector: 'teams-players-box',
    templateUrl: '/maxweb/app/app/teams-players-box.component.html'
})
export class TeamsPlayersBoxComponent {
    public _userProfile:UserProfile;
    public _user_img:any;
    public _box_class:string="about-team teams-blockbox";
    public fullname:string;
    public _index:any;
    public _isView:string;
    indexnumber:number;
    constructor(
        public _userProfilesSvc: UserProfiles,
        public _router:Router,
    ){}
2.child class
@Component({

    selector: '[teams-players-eligibility]',
    templateUrl: '/maxweb/app/app/teams-players-eligibility.component.html'
})
export class TeamsPlayersEligibilityComponent extends TeamsPlayersBoxComponent{

    constructor (public _userProfilesSvc: UserProfiles,
            public _router:Router) {
            super(_userProfilesSvc,_router);
        }
}

Python: Open file in zip without temporarily extracting it

In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
    image = pygame.image.load(imgfile, 'img_01.png')
finally:
    imgfile.close()

How to convert milliseconds into human readable form?

This is a method I wrote. It takes an integer milliseconds value and returns a human-readable String:

public String convertMS(int ms) {
    int seconds = (int) ((ms / 1000) % 60);
    int minutes = (int) (((ms / 1000) / 60) % 60);
    int hours = (int) ((((ms / 1000) / 60) / 60) % 24);

    String sec, min, hrs;
    if(seconds<10)  sec="0"+seconds;
    else            sec= ""+seconds;
    if(minutes<10)  min="0"+minutes;
    else            min= ""+minutes;
    if(hours<10)    hrs="0"+hours;
    else            hrs= ""+hours;

    if(hours == 0)  return min+":"+sec;
    else    return hrs+":"+min+":"+sec;

}

How to read xml file contents in jQuery and display in html elements?

responseText is what you are looking for. Example:

    $.ajax({
...
complete: function(xhr, status) {
alert(xhr.responseText);
}
});

Where xml is your file. Remember this will be your xml in the form form of a string. You can parse it using xmlparse as some of them mentioned.

How to make script execution wait until jquery is loaded

I'm not super fond of the interval thingies. When I want to defer jquery, or anything actually, it usually goes something like this.

Start with:

<html>
 <head>
  <script>var $d=[];var $=(n)=>{$d.push(n)}</script>
 </head>

Then:

 <body>
  <div id="thediv"></div>

  <script>
    $(function(){
       $('#thediv').html('thecode');
    });
  </script>

  <script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

Then finally:

  <script>for(var f in $d){$d[f]();}</script>
 </body>
<html>

Or the less mind-boggling version:

<script>var def=[];function defer(n){def.push(n)}</script>
<script>
defer(function(){
   $('#thediv').html('thecode');
});
</script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>for(var f in def){def[f]();}</script>

And in the case of async you could execute the pushed functions on jquery onload.

<script async onload="for(var f in def){def[f]();}" 
src="jquery.min.js" type="text/javascript"></script>

Alternatively:

function loadscript(src, callback){
  var script = document.createElement('script');
  script.src = src
  script.async = true;
  script.onload = callback;
  document.body.appendChild(script);
};
loadscript("jquery.min", function(){for(var f in def){def[f]();}});

How to change Vagrant 'default' machine name?

If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:

Change the basebox name, when using "vagrant status"

 config.vm.define "tendo" do |tendo|
  end

Where "tendo" will be the name that will appear instead of default

Pass multiple arguments into std::thread

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

How to compile Tensorflow with SSE4.2 and AVX instructions?

Let me answer your 3rd question first:

If you want to run a self-compiled version within a conda-env, you can. These are the general instructions I run to get tensorflow to install on my system with additional instructions. Note: This build was for an AMD A10-7850 build (check your CPU for what instructions are supported...it may differ) running Ubuntu 16.04 LTS. I use Python 3.5 within my conda-env. Credit goes to the tensorflow source install page and the answers provided above.

git clone https://github.com/tensorflow/tensorflow 
# Install Bazel
# https://bazel.build/versions/master/docs/install.html
sudo apt-get install python3-numpy python3-dev python3-pip python3-wheel
# Create your virtual env with conda.
source activate YOUR_ENV
pip install six numpy wheel, packaging, appdir
# Follow the configure instructions at:
# https://www.tensorflow.org/install/install_sources
# Build your build like below. Note: Check what instructions your CPU 
# support. Also. If resources are limited consider adding the following 
# tag --local_resources 2048,.5,1.0 . This will limit how much ram many
# local resources are used but will increase time to compile.
bazel build -c opt --copt=-mavx --copt=-msse4.1 --copt=-msse4.2  -k //tensorflow/tools/pip_package:build_pip_package
# Create the wheel like so:
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
# Inside your conda env:
pip install /tmp/tensorflow_pkg/NAME_OF_WHEEL.whl
# Then install the rest of your stack
pip install keras jupyter etc. etc.

As to your 2nd question:

A self-compiled version with optimizations are well worth the effort in my opinion. On my particular setup, calculations that used to take 560-600 seconds now only take about 300 seconds! Although the exact numbers will vary, I think you can expect about a 35-50% speed increase in general on your particular setup.

Lastly your 1st question:

A lot of the answers have been provided above already. To summarize: AVX, SSE4.1, SSE4.2, MFA are different kinds of extended instruction sets on X86 CPUs. Many contain optimized instructions for processing matrix or vector operations.

I will highlight my own misconception to hopefully save you some time: It's not that SSE4.2 is a newer version of instructions superseding SSE4.1. SSE4 = SSE4.1 (a set of 47 instructions) + SSE4.2 (a set of 7 instructions).

In the context of tensorflow compilation, if you computer supports AVX2 and AVX, and SSE4.1 and SSE4.2, you should put those optimizing flags in for all. Don't do like I did and just go with SSE4.2 thinking that it's newer and should superseed SSE4.1. That's clearly WRONG! I had to recompile because of that which cost me a good 40 minutes.

How to give a Blob uploaded as FormData a file name?

When you are using Google Chrome you can use/abuse the Google Filesystem API for this. Here you can create a file with a specified name and write the content of a blob to it. Then you can return the result to the user.

I have not found a good way for Firefox yet; probably a small piece of Flash like downloadify is required to name a blob.

IE10 has a msSaveBlob() function in the BlobBuilder.

Maybe this is more for downloading a blob, but it is related.

How do I align spans or divs horizontally?

    <!-- CSS -->
<style rel="stylesheet" type="text/css">
.all { display: table; }
.menu { float: left; width: 30%; }
.content { margin-left: 35%; }
</style>

<!-- HTML -->
<div class="all">
<div class="menu">Menu</div>
<div class="content">Content</div>
</div>

another... try to use float: left; or right;, change the width for other values... it shoul work... also note that the 10% that arent used by the div its betwen them... sorry for bad english :)

When does System.getProperty("java.io.tmpdir") return "c:\temp"

Value of %TEMP% environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM, LOCALSYSTEM or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP% variable explicitly, Windows may use c:\temp or even c:\windows\temp folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!

Paste text on Android Emulator

Write command: adb devices (it will list the device currently connected) Select Textbox where you want to write text. Write command: adb shell input text "Yourtext" (make sure only one device is connected to run this command) Done!

Converting a JS object to an array using jQuery

After some tests, here is a general object to array function convertor:

You have the object:

var obj = {
    some_key_1: "some_value_1"
    some_key_2: "some_value_2"
};

The function:

function ObjectToArray(o)
{
    var k = Object.getOwnPropertyNames(o);
    var v = Object.values(o);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
}

Function Use:

var arr = ObjectToArray(obj);

You Get:

arr {
    key: [
        "some_key_1",
        "some_key_2"
    ],
    value: [
        "some_value_1",
        "some_value_2"
    ],
    length: 2
}

So then you can reach all keys & values like:

for (var i = 0; i < arr.length; i++)
{
    console.log(arr.key[i] + " = " + arr.value[i]);
}

Result in console:

some_key_1 = some_value_1
some_key_2 = some_value_2

Edit:

Or in prototype form:

Object.prototype.objectToArray = function()
{
    if (
        typeof this != 'object' ||
        typeof this.length != "undefined"
    ) {
        return false;
    }

    var k = Object.getOwnPropertyNames(this);
    var v = Object.values(this);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
};

And then use like:

console.log(obj.objectToArray);

When would you use the different git merge strategies?

As the answers above are not showing all strategy details. For example, some answer is missing the details about the import resolve option and the recursive which has many sub options as ours, theirs, patience, renormalize, etc.

Therefore, I would recommend to visit the official git documentation which explains all the possible features features:

https://git-scm.com/docs/merge-strategies

How can I run an external command asynchronously from Python?

What I am wondering is if this [os.system()] is the proper way to accomplish such a thing?

No. os.system() is not the proper way. That's why everyone says to use subprocess.

For more information, read http://docs.python.org/library/os.html#os.system

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section.

Python: download a file from an FTP server

urlretrieve is not work for me, and the official document said that They might become deprecated at some point in the future.

import shutil 
from urllib.request import URLopener
opener = URLopener()
url = 'ftp://ftp_domain/path/to/the/file'
store_path = 'path//to//your//local//storage'
with opener.open(url) as remote_file, open(store_path, 'wb') as local_file:
    shutil.copyfileobj(remote_file, local_file)

Change New Google Recaptcha (v2) Width

It's been late, but just want to help others if still facing an issue. I found nice JS solution here : https://github.com/google/recaptcha/issues/61#issuecomment-376484690


Here is JavaScript code using jQuery to do so:

$(document).ready(function () {        
    var width = $('.g-recaptcha').parent().width();
    if (width < 302) {
        var scale = width / 302;
        $('.g-recaptcha').css('transform', 'scale(' + scale + ')');
        $('.g-recaptcha').css('-webkit-transform', 'scale(' + scale + ')');
        $('.g-recaptcha').css('transform-origin', '0 0');
        $('.g-recaptcha').css('-webkit-transform-origin', '0 0');
    }
}); 

IMP Note : It will support All Devices, above and bellow 320px width as well.

Fetch the row which has the Max value for a column

Not being at work, I don't have Oracle to hand, but I seem to recall that Oracle allows multiple columns to be matched in an IN clause, which should at least avoid the options that use a correlated subquery, which is seldom a good idea.

Something like this, perhaps (can't remember if the column list should be parenthesised or not):

SELECT * 
FROM MyTable
WHERE (User, Date) IN
  ( SELECT User, MAX(Date) FROM MyTable GROUP BY User)

EDIT: Just tried it for real:

SQL> create table MyTable (usr char(1), dt date);
SQL> insert into mytable values ('A','01-JAN-2009');
SQL> insert into mytable values ('B','01-JAN-2009');
SQL> insert into mytable values ('A', '31-DEC-2008');
SQL> insert into mytable values ('B', '31-DEC-2008');
SQL> select usr, dt from mytable
  2  where (usr, dt) in 
  3  ( select usr, max(dt) from mytable group by usr)
  4  /

U DT
- ---------
A 01-JAN-09
B 01-JAN-09

So it works, although some of the new-fangly stuff mentioned elsewhere may be more performant.

missing private key in the distribution certificate on keychain

Delete the existing one from KeyChain, get and add the .p12 file to your mac from where the certificate was created.

To get .p12 from source Mac, go to KeyChain, expand the certificate, select both and export 2 items. This will save .p12 file in your location:

enter image description here

Reading file contents on the client-side in javascript in various browsers

There's a modern native alternative: File implements Blob, so we can call Blob.text().

_x000D_
_x000D_
async function readText(event) {
  const file = event.target.files.item(0)
  const text = await file.text();
  
  document.getElementById("output").innerText = text
}
_x000D_
<input type="file" onchange="readText(event)" />
<pre id="output"></pre>
_x000D_
_x000D_
_x000D_

Currently (September 2020) this is supported in Chrome and Firefox, for other Browser you need to load a polyfill, e.g. blob-polyfill.

Should have subtitle controller already set Mediaplayer error Android

A developer recently added subtitle support to VideoView.

When the MediaPlayer starts playing a music (or other source), it checks if there is a SubtitleController and shows this message if it's not set. It doesn't seem to care about if the source you want to play is a music or video. Not sure why he did that.

Short answer: Don't care about this "Exception".


Edit :

Still present in Lollipop,

If MediaPlayer is only used to play audio files and you really want to remove these errors in the logcat, the code bellow set an empty SubtitleController to the MediaPlayer.

It should not be used in production environment and may have some side effects.

static MediaPlayer getMediaPlayer(Context context){

    MediaPlayer mediaplayer = new MediaPlayer();

    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
        return mediaplayer;
    }

    try {
        Class<?> cMediaTimeProvider = Class.forName( "android.media.MediaTimeProvider" );
        Class<?> cSubtitleController = Class.forName( "android.media.SubtitleController" );
        Class<?> iSubtitleControllerAnchor = Class.forName( "android.media.SubtitleController$Anchor" );
        Class<?> iSubtitleControllerListener = Class.forName( "android.media.SubtitleController$Listener" );

        Constructor constructor = cSubtitleController.getConstructor(new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});

        Object subtitleInstance = constructor.newInstance(context, null, null);

        Field f = cSubtitleController.getDeclaredField("mHandler");

        f.setAccessible(true);
        try {
            f.set(subtitleInstance, new Handler());
        }
        catch (IllegalAccessException e) {return mediaplayer;}
        finally {
            f.setAccessible(false);
        }

        Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor", cSubtitleController, iSubtitleControllerAnchor);

        setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
        //Log.e("", "subtitle is setted :p");
    } catch (Exception e) {}

    return mediaplayer;
}

This code is trying to do the following from the hidden API

SubtitleController sc = new SubtitleController(context, null, null);
sc.mHandler = new Handler();
mediaplayer.setSubtitleAnchor(sc, null)

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

Complexities of binary tree traversals

Introduction

Hi

I was asked this question today in class, and it is a good question! I will explain here and hopefully get my more formal answer reviewed or corrected where it is wrong. :)

Previous Answers

The observation by @Assaf is also correct since binary tree traversal travels recursively to visit each node once.

But!, since it is a recursive algorithm, you often have to use more advanced methods to analyze run-time performance. When dealing with a sequential algorithm or one that uses for-loops, using summations will often be enough. So, what follows is a more detailed explanation of this analysis for those who are curious.

The Recurrence

As previously stated,

T(n) = 2*T(n/2) + 1

where T(n) is the number of operations executed in your traversal algorithm (in-order, pre-order, or post-order makes no difference.

Explanation of the Recurrence

There are two T(n) because inorder, preorder, and postorder traversals all call themselves on the left and right child node. So, think of each recursive call as a T(n). In other words, **left T(n/2) + right T(n/2) = 2 T(n/2) **. The "1" comes from any other constant time operations within the function, like printing the node value, et cetera. (It could honestly be a 1 or any constant number & the asymptotic run-time still computes to the same value. Explanation follows.).

Analysis

This recurrence actually can be analyzed using big theta using the masters' theorem. So, I will apply it here.

T(n) = 2*T(n/2) + constant

where constant is some constant (could be 1 or any other constant).

Using the Masters' Theorem , we have T(n) = a*T(n/b) + f(n).

So, a=2, b=2, f(n) = constant since f(n) = n^c = 1, then it follows that c = 0 since f(n) is a constant.

From here, we can see that a = 2 and b^c = 2 ^0 = 1. So, a>b^c or 2>2^0. So, c < logb(a) or 0 < log2(2)

From here we have T(n) = BigTheta(n^{logb(a)}) = BigTheta(n^1) = BigTheta(n)

If your not famliar with BigTheta(n), it is "similar" ( please bear with me :) ) to O(n) but it is a "tighter bound" or tighter approximation of the run-time. So, BigTheta(n) is both worst-case O(n), and best-case BigOmega(n) run-time.

I hope this helps. Take care.

How to read files from resources folder in Scala?

For Scala 2.11, if getLines doesn't do exactly what you want you can also copy the a file out of the jar to the local file system.

Here's a snippit that reads a binary google .p12 format API key from /resources, writes it to /tmp, and then uses the file path string as an input to a spark-google-spreadsheets write.

In the world of sbt-native-packager and sbt-assembly, copying to local is also useful with scalatest binary file tests. Just pop them out of resources to local, run the tests, and then delete.

import java.io.{File, FileOutputStream}
import java.nio.file.{Files, Paths}

def resourceToLocal(resourcePath: String) = {
  val outPath = "/tmp/" + resourcePath
  if (!Files.exists(Paths.get(outPath))) {
    val resourceFileStream = getClass.getResourceAsStream(s"/${resourcePath}")
    val fos = new FileOutputStream(outPath)
    fos.write(
      Stream.continually(resourceFileStream.read).takeWhile(-1 !=).map(_.toByte).toArray
    )
    fos.close()
  }
  outPath
}

val filePathFromResourcesDirectory = "google-docs-key.p12"
val serviceAccountId = "[something]@drive-integration-[something].iam.gserviceaccount.com"
val googleSheetId = "1nC8Y3a8cvtXhhrpZCNAsP4MBHRm5Uee4xX-rCW3CW_4"
val tabName = "Favorite Cities"

import spark.implicits
val df = Seq(("Brooklyn", "New York"), 
          ("New York City", "New York"), 
          ("San Francisco", "California")).
          toDF("City", "State")

df.write.
  format("com.github.potix2.spark.google.spreadsheets").
  option("serviceAccountId", serviceAccountId).
  option("credentialPath", resourceToLocal(filePathFromResourcesDirectory)).
  save(s"${googleSheetId}/${tabName}")

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

How do I do a multi-line string in node.js?

In addition to accepted answer:

`this is a 
single string`

which evaluates to: 'this is a\nsingle string'.

If you want to use string interpolation but without a new line, just add backslash as in normal string:

`this is a \
single string`

=> 'this is a single string'.

Bear in mind manual whitespace is necessary though:

`this is a\
single string`

=> 'this is asingle string'

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
-------------------------------------------------------------------
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.

Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

Can Google Chrome open local links?

The LocalLinks extension from the most popular answer didn't work for me (given, I was trying to use file:// to open a directory in windows explorer, not a file), so I looked into another workaround. I found that this "Open in IE" extension is a good workaround: https://chrome.google.com/webstore/detail/open-in-ie/iajffemldkkhodaedkcpnbpfabiglmdi

This isn't an ideal fix, as instead of clicking the link, users will have to right-click and choose Open in IE, but it at least makes the link functional.

One thing to note though, in IE10 (and IE9 after a certain update point) you will have to add the site to your Trusted Sites (Internet Options > Security > Trusted sites). If the site is not in trusted sites, the file:// link does not work in IE either.

Removing "bullets" from unordered list <ul>

You can remove the "bullets" by setting the "list-style-type: none;" Like

ul
{
    list-style-type: none;
}

OR

<ul class="menu custompozition4"  style="list-style-type: none;">
    <li class="item-507"><a href=#">Strategic Recruitment Solutions</a>
    </li>
    <li class="item-508"><a href="#">Executive Recruitment</a>
    </li>
    <li class="item-509"><a href="#">Leadership Development</a>
    </li>
    <li class="item-510"><a href="#">Executive Capability Review</a>
    </li>
    <li class="item-511"><a href="#">Board and Executive Coaching</a>
    </li>
    <li class="item-512"><a href="#">Cross Cultutral Coaching</a>
    </li>
    <li class="item-513"><a href="#">Team Enhancement &amp; Coaching</a>
    </li>
    <li class="item-514"><a href="#">Personnel Re-deployment</a>
    </li>
</ul>

How to scale an Image in ImageView to keep the aspect ratio

I use this:

<ImageView
android:id="@+id/logo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:scaleType="centerInside"
android:src="@drawable/logo" />

Send data from activity to fragment in Android

In your activity declare static variable

public static HashMap<String,ContactsModal> contactItems=new HashMap<String, ContactsModal>();

Then in your fragment do like follow

ActivityName.contactItems.put(Number,contactsModal);

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Follow the steps given below:

  1. Stop your MySQL server completely. This can be done by accessing the Services window inside Windows XP and Windows Server 2003, where you can stop the MySQL service.

  2. Open your MS-DOS command prompt using "cmd" inside the Run window. Inside it navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.

  3. Execute the following command in the command prompt: mysqld.exe -u root --skip-grant-tables

  4. Leave the current MS-DOS command prompt as it is, and open a new MS-DOS command prompt window.

  5. Navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.

  6. Enter mysql and press enter.

  7. You should now have the MySQL command prompt working. Type use mysql; so that we switch to the "mysql" database.

  8. Execute the following command to update the password:

    UPDATE user SET Password = PASSWORD('NEW_PASSWORD') WHERE User = 'root'; 
    

However, you can now run any SQL command that you wish.

After you are finished close the first command prompt and type exit; in the second command prompt windows to disconnect successfully. You can now start the MySQL service.

Why in C++ do we use DWORD rather than unsigned int?

When MS-DOS and Windows 3.1 operated in 16-bit mode, an Intel 8086 word was 16 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 16 bits.

When Windows NT operated in 32-bit mode, an Intel 80386 word was 32 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 32 bits. The names WORD and DWORD were no longer self-descriptive but they preserved the functionality of Microsoft programs.

When Windows operates in 64-bit mode, an Intel word is 64 bits, a Microsoft WORD is 16 bits, a Microsoft DWORD is 32 bits, and a typical compiler's unsigned int is 32 bits. The names WORD and DWORD are no longer self-descriptive, AND an unsigned int no longer conforms to the principle of least surprises, but they preserve the functionality of lots of programs.

I don't think WORD or DWORD will ever change.

WPF - add static items to a combo box

<ComboBox Text="Something">
            <ComboBoxItem Content="Item1"></ComboBoxItem >
            <ComboBoxItem Content="Item2"></ComboBoxItem >
            <ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>

How to change the display name for LabelFor in razor in mvc3?

@Html.LabelFor(model => model.SomekingStatus, "foo bar")

How to count occurrences of a column value efficiently in SQL?

If you're using Oracle, then a feature called analytics will do the trick. It looks like this:

select id, age, count(*) over (partition by age) from students;

If you aren't using Oracle, then you'll need to join back to the counts:

select a.id, a.age, b.age_count
  from students a
  join (select age, count(*) as age_count
          from students
         group by age) b
    on a.age = b.age

Getting value from a cell from a gridview on RowDataBound event

When you use a TemplateField and bind literal text to it like you are doing, asp.net will actually insert a control FOR YOU! It gets put into a DataBoundLiteralControl. You can see this if you look in the debugger near your line of code that is getting the empty text.

So, to access the information without changing your template to use a control, you would cast like this:

string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text;

That will get you your text!

Android: How to bind spinner to custom object list?

Simplest Solution

After scouring different solutions on SO, I found the following to be the simplest and cleanest solution for populating a Spinner with custom Objects. Here's the full implementation:

User.java

public class User{
    public int ID;
    public String name;

    @Override
    public String toString() {
        return this.name; // What to display in the Spinner list.
    }
}    

res/layout/spinner.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="14sp"
    android:textColor="#FFFFFF"
    android:spinnerMode="dialog" />

res/layout/your_activity_view.xml

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

    <Spinner android:id="@+id/user" />

</LinearLayout>

In Your Activity

List<User> users = User.all(); // This example assumes you're getting all Users but adjust it for your Class and needs.
ArrayAdapter userAdapter = new ArrayAdapter(this, R.layout.spinner, users);

Spinner userSpinner = (Spinner) findViewById(R.id.user);
userSpinner.setAdapter(userAdapter);
userSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // Get the value selected by the user
        // e.g. to store it as a field or immediately call a method
        User user = (User) parent.getSelectedItem();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
});

Getting Database connection in pure JPA setup

Where you want to get that connection is unclear. One possibility would be to get it from the underlying Hibernate Session used by the EntityManager. With JPA 1.0, you'll have to do something like this:

Session session = (Session)em.getDelegate();
Connection conn = session.connection();

Note that the getDelegate() is not portable, the result of this method is implementation specific: the above code works in JBoss, for GlassFish you'd have to adapt it - have a look at Be careful while using EntityManager.getDelegate().

In JPA 2.0, things are a bit better and you can do the following:

Connection conn = em.unwrap(Session.class).connection();

If you are running inside a container, you could also perform a lookup on the configured DataSource.

Setting href attribute at runtime

In jQuery 1.6+ it's better to use:

$(selector).prop('href',"http://www...") to set the value, and

$(selector).prop('href') to get the value

In short, .prop gets and sets values on the DOM object, and .attr gets and sets values in the HTML. This makes .prop a little faster and possibly more reliable in some contexts.

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

Your email variable is empty because of the scope, you should set a use clause such as:

Mail::send('emails.activation', $data, function($message) use ($email, $subject) {
    $message->to($email)->subject($subject);
});

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

I have the same problem today, stuck on the kb2999226 for over an hour. First, i thought it is because i am using a VM on my local machine. But decided to cancel the installation, then install kb2999226 first, then install the vs2015 community again, it works out much better, the installation move forward and progressing. thx.

Create Django model or update if exists

For only a small amount of objects the update_or_create works well, but if you're doing over a large collection it won't scale well. update_or_create always first runs a SELECT and thereafter an UPDATE.

for the_bar in bars:
    updated_rows = SomeModel.objects.filter(bar=the_bar).update(foo=100)
        if not updated_rows:
            # if not exists, create new
            SomeModel.objects.create(bar=the_bar, foo=100)

This will at best only run the first update-query, and only if it matched zero rows run another INSERT-query. Which will greatly increase your performance if you expect most of the rows to actually be existing.

It all comes down to your use case though. If you are expecting mostly inserts then perhaps the bulk_create() command could be an option.

Flutter- wrapping text

Using Ellipsis

Text(
  "This is a long text",
  overflow: TextOverflow.ellipsis,
),

enter image description here


Using Fade

Text(
  "This is a long text",
  overflow: TextOverflow.fade,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Using Clip

Text(
  "This is a long text",
  overflow: TextOverflow.clip,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Note:

If you are using Text inside a Row, you can put above Text inside Expanded like:

Expanded(
  child: AboveText(),
)

TypeScript sorting an array

Numbers

When sorting numbers, you can use the compact comparison:

var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

var sortedArray: number[] = numericArray.sort((n1,n2) => n1 - n2);

i.e. - rather than <.

Other Types

If you are comparing anything else, you'll need to convert the comparison into a number.

var stringArray: string[] = ['AB', 'Z', 'A', 'AC'];

var sortedArray: string[] = stringArray.sort((n1,n2) => {
    if (n1 > n2) {
        return 1;
    }

    if (n1 < n2) {
        return -1;
    }

    return 0;
});

Objects

For objects, you can sort based on a property, bear in mind the above information about being able to short-hand number types. The below example works irrespective of the type.

var objectArray: { age: number; }[] = [{ age: 10}, { age: 1 }, {age: 5}];

var sortedArray: { age: number; }[] = objectArray.sort((n1,n2) => {
    if (n1.age > n2.age) {
        return 1;
    }

    if (n1.age < n2.age) {
        return -1;
    }

    return 0;
});

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

javascript regular expression to not match a word

This can be done in 2 ways:

if (str.match(/abc|def/)) {
                       ...
                    }


if (/abc|def/.test(str)) {
                        ....
                    } 

How to cast Object to its actual type?

If your MyFunction() method is defined only in one class (and its descendants), try

void MyMethod(Object obj) 
{
    var o = obj as MyClass;
    if (o != null)
        o.MyFunction();
}

If you have a large number in unrelated classes defining the function you want to call, you should define an interface and make your classes define that interface:

interface IMyInterface
{
    void MyFunction();
}

void MyMethod(Object obj) 
{
    var o = obj as IMyInterface;
    if (o != null)
        o.MyFunction();
}

Collection was modified; enumeration operation may not execute in ArrayList

One way is to add the item(s) to be deleted to a new list. Then go through and delete those items.

How to add a new audio (not mixing) into a video using ffmpeg?

Nothing quite worked for me (I think it was because my input .mp4 video didn't had any audio) so I found this worked for me:

ffmpeg -i input_video.mp4 -i balipraiavid.wav -map 0:v:0 -map 1:a:0 output.mp4

Restart android machine

You can reboot the device by sending the following broadcast:

$ adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

Why does this AttributeError in python occur?

This happens because the scipy module doesn't have any attribute named sparse. That attribute only gets defined when you import scipy.sparse.

Submodules don't automatically get imported when you just import scipy; you need to import them explicitly. The same holds for most packages, although a package can choose to import its own submodules if it wants to. (For example, if scipy/__init__.py included a statement import scipy.sparse, then the sparse submodule would be imported whenever you import scipy.)

PHP, pass array through POST

Edit If you are asking about security, see my addendum at the bottom Edit

PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.

$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);

This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.

Addendum

I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.

Get path to execution directory of Windows Forms application

System.Windows.Forms.Application.StartupPath will solve your problem, I think

How to use if statements in underscore.js templates?

This should do the trick:

<% if (typeof(date) !== "undefined") { %>
    <span class="date"><%= date %></span>
<% } %>

Remember that in underscore.js templates if and for are just standard javascript syntax wrapped in <% %> tags.

How can I group by date time column without taking time into consideration

I believe you need to group by , in that day of the month of the year . so why not using TRUNK_DATE functions . The way it works is described below :

Group By DATE_TRUNC('day' , 'occurred_at_time')

get current date with 'yyyy-MM-dd' format in Angular 4

Try this:

   import * as moment from 'moment';

     ngOnInit() {
     this.date = moment().format("YYYY Do MMM");
                }

What are the differences between char literals '\n' and '\r' in Java?

It depends on which Platform you work. To get the correct result use -

System.getProperty("line.separator")

Row count on the Filtered data

If you try to count the number of rows in the already autofiltered range like this:

Rowz = rnData.SpecialCells(xlCellTypeVisible).Rows.Count

It will only count the number of rows in the first contiguous visible area of the autofiltered range. E.g. if the autofilter range is rows 1 through 10 and rows 3, 5, 6, 7, and 9 are filtered, four rows are visible (rows 2, 4, 8, and 10), but it would return 2 because the first contiguous visible range is rows 1 (the header row) and 2.

A more accurate alternative is this (assuming that ws contains the worksheet with the filtered data):

Rowz = ws.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1

We have to subtract 1 to remove the header row. We need to include the header row in our counted range because SpecialCells will throw an error if no cells are found, which we want to avoid.

The Cells property will give you an accurate count even if the Range has multiple Areas, unlike the Rows property. So we just take the first column of the autofilter range and count the number of visible cells.

Select columns based on string match - dplyr::select

You can try:

select(data, matches("search_string"))

It is more general than contains - you can use regex (e.g. "one_string|or_the_other").

For more examples, see: http://rpackages.ianhowson.com/cran/dplyr/man/select.html.

Can I use wget to check , but not download

If you are in a directory where only root have access to write in system. Then you can directly use wget www.example.com/wget-test using a standard user account. So it will hit the url but because of having no write permission file won't be saved.. This method is working fine for me as i am using this method for a cronjob. Thanks.

sthx

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

Command not found when using sudo

The other solutions I've seen here so far are based on some system definitions, but it's in fact possible to have sudo use the current PATH (with the env command) and/or the rest of the environment (with the -E option) just by invoking it right:

sudo -E env "PATH=$PATH" <command> [arguments]

In fact, one can make an alias out of it:

alias mysudo='sudo -E env "PATH=$PATH"'

(It's also possible to name the alias itself sudo, replacing the original sudo.)

Getting the first and last day of a month, using a given DateTime object

This is more a long comment on @Sergey and @Steffen's answers. Having written similar code myself in the past I decided to check what was most performant while remembering that clarity is important too.

Result

Here is an example test run result for 10 million iterations:

2257 ms for FirstDayOfMonth_AddMethod()
2406 ms for FirstDayOfMonth_NewMethod()
6342 ms for LastDayOfMonth_AddMethod()
4037 ms for LastDayOfMonth_AddMethodWithDaysInMonth()
4160 ms for LastDayOfMonth_NewMethod()
4212 ms for LastDayOfMonth_NewMethodWithReuseOfExtMethod()
2491 ms for LastDayOfMonth_SpecialCase()

Code

I used LINQPad 4 (in C# Program mode) to run the tests with compiler optimization turned on. Here is the tested code factored as Extension methods for clarity and convenience:

public static class DateTimeDayOfMonthExtensions
{
    public static DateTime FirstDayOfMonth_AddMethod(this DateTime value)
    {
        return value.Date.AddDays(1 - value.Day);
    }
    
    public static DateTime FirstDayOfMonth_NewMethod(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, 1);
    }
    
    public static DateTime LastDayOfMonth_AddMethod(this DateTime value)
    {
        return value.FirstDayOfMonth_AddMethod().AddMonths(1).AddDays(-1);
    }
    
    public static DateTime LastDayOfMonth_AddMethodWithDaysInMonth(this DateTime value)
    {
        return value.Date.AddDays(DateTime.DaysInMonth(value.Year, value.Month) - value.Day);
    }
    
    public static DateTime LastDayOfMonth_SpecialCase(this DateTime value)
    {
        return value.AddDays(DateTime.DaysInMonth(value.Year, value.Month) - 1);
    }
    
    public static int DaysInMonth(this DateTime value)
    {
        return DateTime.DaysInMonth(value.Year, value.Month);
    }
    
    public static DateTime LastDayOfMonth_NewMethod(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, DateTime.DaysInMonth(value.Year, value.Month));
    }

    public static DateTime LastDayOfMonth_NewMethodWithReuseOfExtMethod(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, value.DaysInMonth());
    }
}

void Main()
{
    Random rnd = new Random();
    DateTime[] sampleData = new DateTime[10000000];
    
    for(int i = 0; i < sampleData.Length; i++) {
        sampleData[i] = new DateTime(1970, 1, 1).AddDays(rnd.Next(0, 365 * 50));
    }
    
    GC.Collect();
    System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].FirstDayOfMonth_AddMethod();
    }
    string.Format("{0} ms for FirstDayOfMonth_AddMethod()", sw.ElapsedMilliseconds).Dump();
    
    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].FirstDayOfMonth_NewMethod();
    }
    string.Format("{0} ms for FirstDayOfMonth_NewMethod()", sw.ElapsedMilliseconds).Dump();
    
    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_AddMethod();
    }
    string.Format("{0} ms for LastDayOfMonth_AddMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_AddMethodWithDaysInMonth();
    }
    string.Format("{0} ms for LastDayOfMonth_AddMethodWithDaysInMonth()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_NewMethod();
    }
    string.Format("{0} ms for LastDayOfMonth_NewMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_NewMethodWithReuseOfExtMethod();
    }
    string.Format("{0} ms for LastDayOfMonth_NewMethodWithReuseOfExtMethod()", sw.ElapsedMilliseconds).Dump();

    for(int i = 0; i < sampleData.Length; i++) {
        sampleData[i] = sampleData[i].FirstDayOfMonth_AddMethod();
    }
    
    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_SpecialCase();
    }
    string.Format("{0} ms for LastDayOfMonth_SpecialCase()", sw.ElapsedMilliseconds).Dump();
    
}

Analysis

I was surprised by some of these results.

Although there is not much in it the FirstDayOfMonth_AddMethod was slightly faster than FirstDayOfMonth_NewMethod in most runs of the test. However, I think the latter has a slightly clearer intent and so I have a preference for that.

LastDayOfMonth_AddMethod was a clear loser against LastDayOfMonth_AddMethodWithDaysInMonth, LastDayOfMonth_NewMethod and LastDayOfMonth_NewMethodWithReuseOfExtMethod. Between the fastest three there is nothing much in it and so it comes down to your personal preference. I choose the clarity of LastDayOfMonth_NewMethodWithReuseOfExtMethod with its reuse of another useful extension method. IMHO its intent is clearer and I am willing to accept the small performance cost.

LastDayOfMonth_SpecialCase assumes you are providing the first of the month in the special case where you may have already calculated that date and it uses the add method with DateTime.DaysInMonth to get the result. This is faster than the other versions, as you would expect, but unless you are in a desperate need for speed I don't see the point of having this special case in your arsenal.

Conclusion

Here is an extension method class with my choices and in general agreement with @Steffen I believe:

public static class DateTimeDayOfMonthExtensions
{
    public static DateTime FirstDayOfMonth(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, 1);
    }
    
    public static int DaysInMonth(this DateTime value)
    {
        return DateTime.DaysInMonth(value.Year, value.Month);
    }
    
    public static DateTime LastDayOfMonth(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, value.DaysInMonth());
    }
}

If you have got this far, thank you for time! Its been fun :¬). Please comment if you have any other suggestions for these algorithms.

How to check null objects in jQuery

if (typeof($("#btext" + i)) == 'object'){
    $("#btext" + i).text("Branch " + i);
}

Git add all subdirectories

Most likely .gitignore files are at play. Note that .gitignore files can appear not only at the root level of the repo, but also at any sub level. You might try this from the root level to find them:

find . -name ".gitignore"

and then examine the results to see which might be preventing your subdirs from being added.

There also might be submodules involved. Check the offending directories for ".gitmodules" files.

CSS to stop text wrapping under image

For those who want some background info, here's a short article explaining why overflow: hidden works. It has to do with the so-called block formatting context. This is part of W3C's spec (ie is not a hack) and is basically the region occupied by an element with a block-type flow.

Every time it is applied, overflow: hidden creates a new block formatting context. But it's not the only property capable of triggering that behaviour. Quoting a presentation by Fiona Chan from Sydney Web Apps Group:

  • float: left / right
  • overflow: hidden / auto / scroll
  • display: table-cell and any table-related values / inline-block
  • position: absolute / fixed

How to convert ActiveRecord results into an array of hashes

as_json

You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json

# You can now add new records and return the result as json by calling `to_json`

tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json

serializable_hash

You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)

And if you want an ugly solution for Rails prior to v2.3

JSON.parse(tasks_records.to_json) # please don't do it

bower command not found

I am almost sure you are not actually getting it installed correctly. Since you are trying to install it globally, you will need to run it with sudo:

sudo npm install -g bower

href="javascript:" vs. href="javascript:void(0)"

When using javascript: in navigation the return value of the executed script, if there is one, becomes the content of a new document which is displayed in the browser. The void operator in JavaScript causes the return value of the expression following it to return undefined, which prevents this action from happening. You can try it yourself, copy the following into the address bar and press return:

javascript:"hello"

The result is a new page with only the word "hello". Now change it to:

javascript:void "hello"

...nothing happens.

When you write javascript: on its own there's no script being executed, so the result of that script execution is also undefined, so the browser does nothing. This makes the following more or less equivalent:

javascript:undefined;
javascript:void 0;
javascript:

With the exception that undefined can be overridden by declaring a variable with the same name. Use of void 0 is generally pointless, and it's basically been whittled down from void functionThatReturnsSomething().

As others have mentioned, it's better still to use return false; in the click handler than use the javascript: protocol.

select certain columns of a data table

The question I would ask is, why are you including the extra columns in your DataTable if they aren't required?

Maybe you should modify your SQL select statement so that it is looking at the specific criteria you are looking for as you are populating your DataTable.

You could also use LINQ to query your DataTable as Enumerable and create a List Object that represents only certain columns.

Other than that, hide the DataGridView Columns that you don't require.

Check if all checkboxes are selected

A class independent solution

var checkBox = 'input[type="checkbox"]';
if ($(checkBox+':checked').length == $(checkBox).length) {
   //Do Something
}

How do I change the default application icon in Java?

You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:

Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))

Do not forget to import:

import java.awt.Toolkit;

in the source code!

iTunes Connect: How to choose a good SKU?

Spending some time coming up with an SKU naming strategy can help you. You’ll be able to make it easy for team members to read and understand what each SKU represents. Use a value that is meaningful to your organization.

Ultimately, your SKU is a way to record important product information, so the more straightforward it is, the better for everyone.

Sticking to alphanumeric SKUs and substituting “-” or “_” for space is always the safest and best bet.

E.g. Your app name: Social Point, Submit year: 2020 = Your SKU is: Social_Point_2020

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

It didn't work for me either. I changed

CUSTOM_ELEMENTS_SCHEMA

for

NO_ERRORS_SCHEMA

which was suggested in this article: https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

Now it works.

Why Git is not allowing me to commit even after configuration?

That’s a typo. You’ve accidently set user.mail with no e. Fix it by setting user.email in the global configuration with

git config --global user.email "[email protected]"

How to check if a String contains any letter from a to z?

What about:

//true if it doesn't contain letters
bool result = hello.Any(x => !char.IsLetter(x));

Multipart forms from C# client

Below is the code which I'm using

    //This URL not exist, it's only an example.
    string url = "http://myBox.s3.amazonaws.com/";
    //Instantiate new CustomWebRequest class
    CustomWebRequest wr = new CustomWebRequest(url);
    //Set values for parameters
    wr.ParamsCollection.Add(new ParamsStruct("key", "${filename}"));
    wr.ParamsCollection.Add(new ParamsStruct("acl", "public-read"));
    wr.ParamsCollection.Add(new ParamsStruct("success_action_redirect", "http://www.yahoo.com"));
    wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-uuid", "14365123651274"));
    wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-tag", ""));
    wr.ParamsCollection.Add(new ParamsStruct("AWSAccessKeyId", "zzzz"));            
    wr.ParamsCollection.Add(new ParamsStruct("Policy", "adsfadsf"));
    wr.ParamsCollection.Add(new ParamsStruct("Signature", "hH6lK6cA="));
    //For file type, send the inputstream of selected file
    StreamReader sr = new StreamReader(@"file.txt");
    wr.ParamsCollection.Add(new ParamsStruct("file", sr, ParamsStruct.ParamType.File, "file.txt"));

    wr.PostData();

from the following link I've downloaded the same code http://www.codeproject.com/KB/cs/multipart_request_C_.aspx

Any Help

Bootstrap 4 - Responsive cards in card-columns

Another late answer, but I was playing with this and came up with a general purpose Sass solution that I found useful and many others might as well. To give an overview, this introduces new classes that can modify the column count of a .card-columns element in very similar ways to columns with .col-4 or .col-lg-3:

@import "bootstrap";

$card-column-counts: 1, 2, 3, 4, 5;

.card-columns {
    @each $column-count in $card-column-counts {
        &.card-columns-#{$column-count} {
            column-count: $column-count;
        }
    }

    @each $breakpoint in map-keys($grid-breakpoints) {
        @include media-breakpoint-up($breakpoint) {
            $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
            @each $column-count in $card-column-counts {
                &.card-columns#{$infix}-#{$column-count} {
                    column-count: $column-count;
                }
            }
        }
    }
}

The end result of this is if you have the following:

<div class="card-columns card-columns-2 card-columns-md-3 card-columns-xl-4">
   ...
</div>

Then you would have 2 columns by default, 3 for medium devices and up and 4 for xl devices and up. Additionally if you change your grid breakpoints this will automatically support those, and the $card-column-counts can be overridden to change the allowed numbers of columns.

Limiting floats to two decimal points

TLDR ;)

The rounding problem of input / output has been solved definitively by Python 2.7.0 and 3.1.

A correctly rounded number can be reversibly converted back and forth:
str -> float() -> repr() -> float() ... or Decimal -> float -> str -> Decimal
A Decimal type is not necessary for storage anymore.


(Naturally, it can be necessary to round a result of addition or subtraction of rounded numbers to eliminate the accumulated last bit errors. An explicit Decimal arithmetic can be still handy, but a conversion to string by str() (that is with rounding to 12 valid digits) is good enough usually if no extreme accuracy or no extreme number of successive arithmetic operations is required.)

Infinite test:

import random
from decimal import Decimal
for x in iter(random.random, None):           # Verify FOREVER that rounding is fixed :-)
    assert float(repr(x)) == x                # Reversible repr() conversion.
    assert float(Decimal(repr(x))) == x
    assert len(repr(round(x, 10))) <= 12      # Smart decimal places in repr() after round.
    if x >= 0.1:                              # Implicit rounding to 12 significant digits
        assert str(x) == repr(round(x, 12))   # by str() is good enough for small errors.
        y = 1000 * x                             # Decimal type is excessive for shopping
        assert str(y) == repr(round(y, 12 - 3))  # in a supermaket with Python 2.7+ :-)

Documentation

See the Release notes Python 2.7 - Other Language Changes the fourth paragraph:

Conversions between floating-point numbers and strings are now correctly rounded on most platforms. These conversions occur in many different places: str() on floats and complex numbers; the float and complex constructors; numeric formatting; serializing and de-serializing floats and complex numbers using the marshal, pickle and json modules; parsing of float and imaginary literals in Python code; and Decimal-to-float conversion.

Related to this, the repr() of a floating-point number x now returns a result based on the shortest decimal string that’s guaranteed to round back to x under correct rounding (with round-half-to-even rounding mode). Previously it gave a string based on rounding x to 17 decimal digits.

The related issue


More information: The formatting of float before Python 2.7 was similar to the current numpy.float64. Both types use the same 64 bit IEEE 754 double precision with 52 bit mantissa. A big difference is that np.float64.__repr__ is formatted frequently with an excessive decimal number so that no bit can be lost, but no valid IEEE 754 number exists between 13.949999999999999 and 13.950000000000001. The result is not nice and the conversion repr(float(number_as_string)) is not reversible with numpy. On the other hand: float.__repr__ is formatted so that every digit is important; the sequence is without gaps and the conversion is reversible. Simply: If you perhaps have a numpy.float64 number, convert it to normal float in order to be formatted for humans, not for numeric processors, otherwise nothing more is necessary with Python 2.7+.

Constructor in an Interface?

A problem that you get when you allow constructors in interfaces comes from the possibility to implement several interfaces at the same time. When a class implements several interfaces that define different constructors, the class would have to implement several constructors, each one satisfying only one interface, but not the others. It will be impossible to construct an object that calls each of these constructors.

Or in code:

interface Named { Named(String name); }
interface HasList { HasList(List list); }

class A implements Named, HasList {

  /** implements Named constructor.
   * This constructor should not be used from outside, 
   * because List parameter is missing
   */
  public A(String name)  { 
    ...
  }

  /** implements HasList constructor.
   * This constructor should not be used from outside, 
   * because String parameter is missing
   */
  public A(List list) {
    ...
  }

  /** This is the constructor that we would actually 
   * need to satisfy both interfaces at the same time
   */ 
  public A(String name, List list) {
    this(name);
    // the next line is illegal; you can only call one other super constructor
    this(list); 
  }
}

How to enable SOAP on CentOS

After hours of searching I think my problem was that command yum install php-soap installs the latest version of soap for the latest php version.

My php version was 7.027, but latest php version is 7.2 so I had to search for the right soap version and finaly found it HERE!

yum install rh-php70-php-soap

Now php -m | grep -i soap works, Output: soap

Do not forget to restart httpd service.

What are the best practices for SQLite on Android?

You can try to apply new architecture approach anounced at Google I/O 2017.

It also includes new ORM library called Room

It contains three main components: @Entity, @Dao and @Database

User.java

@Entity
public class User {
  @PrimaryKey
  private int uid;

  @ColumnInfo(name = "first_name")
  private String firstName;

  @ColumnInfo(name = "last_name")
  private String lastName;

  // Getters and setters are ignored for brevity,
  // but they're required for Room to work.
}

UserDao.java

@Dao
public interface UserDao {
  @Query("SELECT * FROM user")
  List<User> getAll();

  @Query("SELECT * FROM user WHERE uid IN (:userIds)")
  List<User> loadAllByIds(int[] userIds);

  @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
       + "last_name LIKE :last LIMIT 1")
  User findByName(String first, String last);

  @Insert
  void insertAll(User... users);

  @Delete
  void delete(User user);
}

AppDatabase.java

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
  public abstract UserDao userDao();
}

Error Code: 2013. Lost connection to MySQL server during query

I had the same problem - but for me the solution was a DB user with too strict permissions. I had to allow the Execute ability on the mysql table. After allowing that I had no dropping connections anymore

How to format a number as percentage in R?

I did some benchmarking for speed on these answers and was surprised to see percent in the scales package so touted, given its sluggishness. I imagine the advantage is its automatic detector for for proper formatting, but if you know what your data looks like it seems clear to be avoided.

Here are the results from trying to format a list of 100,000 percentages in (0,1) to a percentage in 2 digits:

library(microbenchmark)
x = runif(1e5)
microbenchmark(times = 100L, andrie1(), andrie2(), richie(), krlmlr())
# Unit: milliseconds
#   expr       min        lq      mean    median        uq       max
# 1 andrie1()  91.08811  95.51952  99.54368  97.39548 102.75665 126.54918 #paste(round())
# 2 andrie2()  43.75678  45.56284  49.20919  47.42042  51.23483  69.10444 #sprintf()
# 3  richie()  79.35606  82.30379  87.29905  84.47743  90.38425 112.22889 #paste(formatC())
# 4  krlmlr() 243.19699 267.74435 304.16202 280.28878 311.41978 534.55904 #scales::percent()

So sprintf emerges as a clear winner when we want to add a percent sign. On the other hand, if we only want to multiply the number and round (go from proportion to percent without "%", then round() is fastest:

# Unit: milliseconds
#        expr      min        lq      mean    median        uq       max
# 1 andrie1()  4.43576  4.514349  4.583014  4.547911  4.640199  4.939159 # round()
# 2 andrie2() 42.26545 42.462963 43.229595 42.960719 43.642912 47.344517 # sprintf()
# 3  richie() 64.99420 65.872592 67.480730 66.731730 67.950658 96.722691 # formatC()

How do I escape only single quotes?

Here is how I did it. Silly, but simple.

$singlequote = "'";
$picturefile = getProductPicture($id);

echo showPicture('.$singlequote.$picturefile.$singlequote.');

I was working on outputting HTML that called JavaScript code to show a picture...

What is the total amount of public IPv4 addresses?

Public IP Addresses

https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.

'1.0.0.0/8' to '191.0.0.0/8' are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:

import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
    '0.0.0.0/8',      '10.0.0.0/8',     '100.64.0.0/10', '127.0.0.0/8',
    '169.254.0.0/16', '172.16.0.0/12',  '192.0.0.0/24',  '192.0.2.0/24',
    '192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
    '203.0.113.0/24', '224.0.0.0/4',    '240.0.0.0/4',   '255.255.255.255/32'
)

IP Generator

Generates a JSON dump of IP Addresses and associated Geo information. Note that the valid public IP Address range is from '1.0.0.0/8' to '191.0.0.0/8' excluding the reserved Private IP Address ranges shown lower down in this readme.

docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip               ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip               ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip               ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0'   geo-ip               ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0'   geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip 

A little faster option for scanning all valid public addresses:

for i in $(seq 1 191); do \
    docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
    sleep 1; \ 
done

This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:

{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
 "continent": "North America", "continent_code": "NA",
 "state": "California", "country": "United States", "latitude": 37.418,
 "iso_code": "US", "state_code": "CA", "aso": "PubNub",
 "asn": "11404", "zip_code": "94107"}

Private and Reserved IP Range

The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses

MaxMind Geo IP

The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home

Android Device not recognized by adb

Go to prompt command and type "adb devices". If it is empty, then make sure you allowed for "MTP Transfer" or similar and you enabled debugging on your phone.

To enable debugging, follow this tutorial: https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm

Then type "adb devices" again. If a device is listed in there, then it should work now.

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Self-Signed Certificate Authorities pip / conda

After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:

NEVER disable all SSL verification!

This creates a bad security culture. Don't be that person.

tl;dr

pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify

# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt

But where do we get ca-bundle.crt?


Get an up to date CA Bundle

cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox

https://curl.haxx.se/docs/caextract.html

I recommend you open up this cacert.pem file in a text editor as we will need to add our self-signed CA to this file.

Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:

----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----

https://support.ssl.com/Knowledgebase/Article/View/19/0/der-vs-crt-vs-cer-vs-pem-certificates-and-how-to-convert-them


Getting our Self Signed Certificate

Below are a few options on how to get our self signed certificate:

  • Via OpenSSL CLI
  • Via Browser
  • Via Python Scripting

Get our Self-Signed Certificate by OpenSSL CLI

https://unix.stackexchange.com/questions/451207/how-to-trust-self-signed-certificate-in-curl-command-line/468360#468360

echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem

Get our Self-Signed Certificate Authority via Browser

Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.

Copy the contents of this exported file and paste it at the end of your cacerts.pem file.

For consistency rename this file cacerts.pem --> ca-bundle.crt and place it somewhere easy like:

# Windows
%USERPROFILE%\certs\ca-bundle.crt

# or *nix
$HOME/certs/cabundle.crt

Get our Self-Signed Certificate Authority via Python

Thanks to all the brilliant answers in:

How to get response SSL certificate from requests in python?

I have put together the following to attempt to take it a step further.

https://github.com/neozenith/get-ca-py


Finally

Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.

pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt

OR

pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt

THEN

pip config list
conda config --show ssl_verify

# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'

References

Expand Python Search Path to Other Source

The easiest way I find is to create a file "any_name.pth" and put it in your folder "\Lib\site-packages". You should find that folder wherever python is installed.

In that file, put a list of directories where you want to keep modules for importing. For instance, make a line in that file like this:

C:\Users\example...\example

You will be able to tell it works by running this in python:

import sys
for line in sys: print line

You will see your directory printed out, amongst others from where you can also import. Now you can import a "mymodule.py" file that sits in that directory as easily as:

import mymodule

This will not import subfolders. For that you could imagine creating a python script to create a .pth file containing all sub folders of a folder you define. Have it run at startup perhaps.

How to link an image and target a new window

<a href="http://www.google.com" target="_blank"> //gives blank window
<img width="220" height="250" border="0" align="center"  src=""/> // show image into new window
</a>

See the code