Programs & Examples On #Ereg replace

ereg_replace() is a PHP function that performs string replacement using regular expressions.

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

Add colorbar to existing axis

The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

For example:

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()

enter image description here

Distinct() with lambda?

You can use InlineComparer

public class InlineComparer<T> : IEqualityComparer<T>
{
    //private readonly Func<T, T, bool> equalsMethod;
    //private readonly Func<T, int> getHashCodeMethod;
    public Func<T, T, bool> EqualsMethod { get; private set; }
    public Func<T, int> GetHashCodeMethod { get; private set; }

    public InlineComparer(Func<T, T, bool> equals, Func<T, int> hashCode)
    {
        if (equals == null) throw new ArgumentNullException("equals", "Equals parameter is required for all InlineComparer instances");
        EqualsMethod = equals;
        GetHashCodeMethod = hashCode;
    }

    public bool Equals(T x, T y)
    {
        return EqualsMethod(x, y);
    }

    public int GetHashCode(T obj)
    {
        if (GetHashCodeMethod == null) return obj.GetHashCode();
        return GetHashCodeMethod(obj);
    }
}

Usage sample:

  var comparer = new InlineComparer<DetalleLog>((i1, i2) => i1.PeticionEV == i2.PeticionEV && i1.Etiqueta == i2.Etiqueta, i => i.PeticionEV.GetHashCode() + i.Etiqueta.GetHashCode());
  var peticionesEV = listaLogs.Distinct(comparer).ToList();
  Assert.IsNotNull(peticionesEV);
  Assert.AreNotEqual(0, peticionesEV.Count);

Source: https://stackoverflow.com/a/5969691/206730
Using IEqualityComparer for Union
Can I specify my explicit type comparator inline?

How to find the location of the Scheduled Tasks folder

There are multiple issues with the MMC however as on almost every PC in my business the ask scheduler API will not open and has somehow been corrupted. So you cannot edit, delete or otherwise modify tasks that were developed before the API decided not to run anymore. The only way we have found to fix that issue is to totally wipe away a persons profile under the C:\Users\ area and force the system to recreate the log in once the person logs back in. This seems to fix the API issue and it works again, however the tasks are often not visible anymore to that user since the tasks developed are specific to the user and not the machine in Windows 7. The other odd thing is that sometimes, although not with any frequency that can be analyzed, the tasks still run even though the API is corrupted and will not open. The cause of this issue is apparently not known but there are many "fixes" described on various websites, but the user profile deletion and adding anew seems to work every time for at least a little while. The tasks are saved as XML now in WIN 7, so if you do find them in the system32/tasks folder you can delete them, or copy them to a new drive and then import them back into task scheduler. We went with the system scheduler software from Splinterware though since we had the same corruption issue multiple times even with the fix that does not seem to be permanent.

How do I get the position selected in a RecyclerView?

To complement @tyczj answer:

Generic Adapter Pseido code:

public abstract class GenericRecycleAdapter<T, K extends RecyclerView.ViewHolder> extends RecyclerView.Adapter{ 

private List<T> mList;
//default implementation code 

public abstract int getLayout();

@Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(getLayout(), parent, false);
        return getCustomHolder(v);
    }

    public Holders.TextImageHolder getCustomHolder(View v) {
        return new Holders.TextImageHolder(v){
            @Override
            public void onClick(View v) {
                onItem(mList.get(this.getAdapterPosition()));
            }
        };
    }

abstract void onItem(T t);

 @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    onSet(mList.get(position), (K) holder);

}

public abstract void onSet(T item, K holder);

}

ViewHolder:

public class Holders  {

    public static class TextImageHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        public TextView text;

        public TextImageHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.text);
            text.setOnClickListener(this);


        }

        @Override
        public void onClick(View v) {

        }
    }


}

Adapter usage:

public class CategoriesAdapter extends GenericRecycleAdapter<Category, Holders.TextImageHolder> {


    public CategoriesAdapter(List<Category> list, Context context) {
        super(list, context);
    }

    @Override
    void onItem(Category category) {

    }


    @Override
    public int getLayout() {
        return R.layout.categories_row;
    }

    @Override
    public void onSet(Category item, Holders.TextImageHolder holder) {

    }



}

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

Docker-Compose persistent data MySQL

There are 3 ways:

First way

You need specify the directory to store mysql data on your host machine. You can then remove the data container. Your mysql data will be saved on you local filesystem.

Mysql container definition must look like this:

mysql:
  container_name: flask_mysql
  restart: always
  image: mysql:latest
  environment:
    MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this
    MYSQL_USER: 'test'
    MYSQL_PASS: 'pass'
volumes:
 - /opt/mysql_data:/var/lib/mysql
ports:
  - "3306:3306"

Second way

Would be to commit the data container before typing docker-compose down:

docker commit my_data_container
docker-compose down

Third way

Also you can use docker-compose stop instead of docker-compose down (then you don't need to commit the container)

Check if value already exists within list of dictionaries?

Here's one way to do it:

if not any(d['main_color'] == 'red' for d in a):
    # does not exist

The part in parentheses is a generator expression that returns True for each dictionary that has the key-value pair you are looking for, otherwise False.


If the key could also be missing the above code can give you a KeyError. You can fix this by using get and providing a default value. If you don't provide a default value, None is returned.

if not any(d.get('main_color', default_value) == 'red' for d in a):
    # does not exist

Filter data.frame rows by a logical condition

I was working on a dataframe and having no luck with the provided answers, it always returned 0 rows, so I found and used grepl:

df = df[grepl("downlink",df$Transmit.direction),]

Which basically trimmed my dataframe to only the rows that contained "downlink" in the Transmit direction column. P.S. If anyone can guess as to why I'm not seeing the expected behavior, please leave a comment.

Specifically to the original question:

expr[grepl("hesc",expr$cell_type),]

expr[grepl("bj fibroblast|hesc",expr$cell_type),]

What is the max size of VARCHAR2 in PL/SQL and SQL?

Not sure what you meant with "Can I increase the size of this variable without worrying about the SQL limit?". As long you do not try to insert a more than 4000 VARCHAR2 into a VARCHAR2 SQL column there is nothing to worry about.

Here is the exact reference (this is 11g but true also for 10g)

http://docs.oracle.com/cd/E11882_01/appdev.112/e17126/datatypes.htm

VARCHAR2 Maximum Size in PL/SQL: 32,767 bytes Maximum Size in SQL 4,000 bytes

Deleting all pending tasks in celery / rabbitmq

From the docs:

$ celery -A proj purge

or

from proj.celery import app
app.control.purge()

(EDIT: Updated with current method.)

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

Just use this website: http://ticons.fokkezb.nl :)

It makes it easier for you, and generates the correct sizes directly

How to check if a file exists in the Documents directory in Swift?

Swift 4 example:

var filePath: String {
    //manager lets you examine contents of a files and folders in your app.
    let manager = FileManager.default

    //returns an array of urls from our documentDirectory and we take the first
    let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
    //print("this is the url path in the document directory \(String(describing: url))")

    //creates a new path component and creates a new file called "Data" where we store our data array
    return(url!.appendingPathComponent("Data").path)
}

I put the check in my loadData function which I called in viewDidLoad.

override func viewDidLoad() {
    super.viewDidLoad()

    loadData()
}

Then I defined loadData below.

func loadData() {
    let manager = FileManager.default

    if manager.fileExists(atPath: filePath) {
        print("The file exists!")

        //Do what you need with the file. 
        ourData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! Array<DataObject>         
    } else {
        print("The file DOES NOT exist! Mournful trumpets sound...")
    }
}

Changing password with Oracle SQL Developer

SQL Developer has a built-in reset password option that may work for your situation. It requires adding Oracle Instant Client to the workstation as well. When instant client is in the path when SQL developer launches you will get the following option enabled:

SQL Developer: Drop Down menu showing reset password option

Oracle Instant Client does not need admin privileges to install, just the ability to write to a directory and add that directory to the users path. Most users have the privileges to do this.

Recap: In order to use Reset Password on Oracle SQL Developer:

  1. You must unpack the Oracle Instant Client in a directory
  2. You must add the Oracle Instant Client directory to the users path
  3. You must then restart Oracle SQL Developer

At this point you can right click a data source and reset your password.

See http://www.thatjeffsmith.com/archive/2012/11/resetting-your-oracle-user-password-with-sql-developer/ for a complete walk-through

Also see the comment in the oracle docs: http://docs.oracle.com/cd/E35137_01/appdev.32/e35117/dialogs.htm#RPTUG41808

An alternative configuration to have SQL Developer (tested on version 4.0.1) recognize and use the Instant Client on OS X is:

  1. Set path to Instant Client in Preferences -> Database -> Advanced -> Use Oracle Client
  2. Verify the Instance Client can be loaded succesfully using the Configure... -> Test... options from within the preferences dialog
  3. (OS X) Refer to this question to resolve issues related to DYLD_LIBRARY_PATH environment variable. I used the following command and then restarted SQL Developer to pick up the change:

    $ launchctl setenv DYLD_LIBRARY_PATH /path/to/oracle/instantclient_11_2

JSON array get length

I came here and looking how to get the number of elements inside a JSONArray. From your question i used length() like that:

JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());

and it worked as expected. On the other hand jar.size();(as proposed in the other answer) is not working for me.

So for future users searching (like me) how to get the size of a JSONArray, length() works just fine.

Why use argparse rather than optparse?

Why should I use it instead of optparse? Are their new features I should know about?

@Nicholas's answer covers this well, I think, but not the more "meta" question you start with:

Why has yet another command-line parsing module been created?

That's the dilemma number one when any useful module is added to the standard library: what do you do when a substantially better, but backwards-incompatible, way to provide the same kind of functionality emerges?

Either you stick with the old and admittedly surpassed way (typically when we're talking about complicated packages: asyncore vs twisted, tkinter vs wx or Qt, ...) or you end up with multiple incompatible ways to do the same thing (XML parsers, IMHO, are an even better example of this than command-line parsers -- but the email package vs the myriad old ways to deal with similar issues isn't too far away either;-).

You may make threatening grumbles in the docs about the old ways being "deprecated", but (as long as you need to keep backwards compatibility) you can't really take them away without stopping large, important applications from moving to newer Python releases.

(Dilemma number two, not directly related to your question, is summarized in the old saying "the standard library is where good packages go to die"... with releases every year and a half or so, packages that aren't very, very stable, not needing releases any more often than that, can actually suffer substantially by being "frozen" in the standard library... but, that's really a different issue).

Could not resolve this reference. Could not locate the assembly

I had the same warning in VS 2017. As it turned out in my case I had added a unit test project and needed to set a dependency for the unit test on the DLL it was testing.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

Install package : Microsoft.AspNet.WebApi.Cors

go to : App_Start --> WebApiConfig

Add :

var cors = new EnableCorsAttribute("http://localhost:4200", "", ""); config.EnableCors(cors);

Note : If you add '/' as end of the particular url not worked for me.

How to select following sibling/xml tag using xpath

Try the following-sibling axis (following-sibling::td).

How do I convert a dictionary to a JSON String in C#?

If your context allows it (technical constraints, etc.), use the JsonConvert.SerializeObject method from Newtonsoft.Json : it will make your life easier.

Dictionary<string, string> localizedWelcomeLabels = new Dictionary<string, string>();
localizedWelcomeLabels.Add("en", "Welcome");
localizedWelcomeLabels.Add("fr", "Bienvenue");
localizedWelcomeLabels.Add("de", "Willkommen");
Console.WriteLine(JsonConvert.SerializeObject(localizedWelcomeLabels));

// Outputs : {"en":"Welcome","fr":"Bienvenue","de":"Willkommen"}

Prompt for user input in PowerShell

Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.

   Param(
     [Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
     [SecureString]$password
   )

   $pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

If you want to debug and see the value of the password you just read, use:

   write-host $pw

How do I get a button to open another activity?

Button T=(Button)findViewById(R.id.button_timer);
T.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent i=new Intent(getApplicationContext(),YOURACTIVITY.class);
        startActivity(i);
    }
});

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

sizing div based on window width

A good trick is to use inner box-shadow, and let it do all the fading for you rather than applying it to the image.

HTML Display Current date

Here's one way. You have to get the individual components from the date object (day, month & year) and then build and format the string however you wish.

_x000D_
_x000D_
n =  new Date();_x000D_
y = n.getFullYear();_x000D_
m = n.getMonth() + 1;_x000D_
d = n.getDate();_x000D_
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
_x000D_
<p id="date"></p>
_x000D_
_x000D_
_x000D_

Difference between logger.info and logger.debug

I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.

The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception, you might call Logger.error. If you want to print the value of a variable at any given point, you might call Logger.debug. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.

In the case of log4j at least, the ordering of log levels is:

DEBUG < INFO < WARN < ERROR < FATAL

Here is a short example from that article demonstrating how log levels work.

   // get a logger instance named "com.foo"
   Logger logger = Logger.getLogger("com.foo");

   // Now set its level. Normally you do not need to set the
   // level of a logger programmatically. This is usually done
   // in configuration files.
   logger.setLevel(Level.INFO);

   Logger barlogger = Logger.getLogger("com.foo.Bar");

   // This request is enabled, because WARN >= INFO.
   logger.warn("Low fuel level.");

   // This request is disabled, because DEBUG < INFO.
   logger.debug("Starting search for nearest gas station.");

   // The logger instance barlogger, named "com.foo.Bar",
   // will inherit its level from the logger named
   // "com.foo" Thus, the following request is enabled
   // because INFO >= INFO.
   barlogger.info("Located nearest gas station.");

   // This request is disabled, because DEBUG < INFO.
   barlogger.debug("Exiting gas station search");

Is there a simple way that I can sort characters in a string in alphabetical order

Yes; copy the string to a char array, sort the char array, then copy that back into a string.

static string SortString(string input)
{
    char[] characters = input.ToArray();
    Array.Sort(characters);
    return new string(characters);
}

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

Efficient way to iterate your ArrayList followed by this link. This type will improve the performance of looping during iteration

int size = list.size();

for(int j = 0; j < size; j++) {
    System.out.println(list.get(i));
}

Get Selected value from dropdown using JavaScript

Maybe it's the comma in your if condition.

function answers() {
var answer=document.getElementById("mySelect");
 if(answer[answer.selectedIndex].value == "To measure time.") {
  alert("That's correct!"); 
 }
}

You can also write it like this.

function answers(){
 document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}

how to evenly distribute elements in a div next to each other?

In the 'old days' you'd use a table and your menu items would be evenly spaced without having to explicitly state the width for the number of items.

If it wasn't for IE 6 and 7 (if that is of concern) then you can do the same in CSS.

<div class="demo">
    <span>Span 1</span>
    <span>Span 2</span>
    <span>Span 3</span>
</div>

CSS:

div.demo {
    display: table;
    width: 100%;
    table-layout: fixed;    /* For cells of equal size */
}
div.demo span {
    display: table-cell;
    text-align: center;
}

Without having to adjust for the number of items.

Example without table-layout:fixed - the cells are evenly distributed across the full width, but they are not necessarily of equal size since their width is determined by their contents.

Example with table-layout:fixed - the cells are of equal size, regardless of their contents. (Thanks to @DavidHerse in comments for this addition.)

If you want the first and last menu elements to be left and right justified, then you can add the following CSS:

div.demo span:first-child {
    text-align: left;
}
div.demo span:last-child {
    text-align: right;
}

How is CountDownLatch used in Java Multithreading?

If you add some debug after your call to latch.countDown(), this may help you understand its behaviour better.

latch.countDown();
System.out.println("DONE "+this.latch); // Add this debug

The output will show the Count being decremented. This 'count' is effectively the number of Runnable tasks (Processor objects) you've started against which countDown() has not been invoked and hence is blocked the main thread on its call to latch.await().

DONE java.util.concurrent.CountDownLatch@70e69696[Count = 2]
DONE java.util.concurrent.CountDownLatch@70e69696[Count = 1]
DONE java.util.concurrent.CountDownLatch@70e69696[Count = 0]

How to change the size of the radio button using CSS?

Resizing the default widget doesn’t work in all browsers, but you can make custom radio buttons with JavaScript. One of the ways is to create hidden radio buttons and then place your own images on your page. Clicking on these images changes the images (replaces the clicked image with an image with a radio button in a selected state and replaces the other images with radio buttons in an unselected state) and selects the new radio button.

Anyway, there is documentation on this subject. For example, read this: Styling Checkboxes and Radio Buttons with CSS and JavaScript.

Linker Error C++ "undefined reference "

Your error shows you are not compiling file with the definition of the insert function. Update your command to include the file which contains the definition of that function and it should work.

CSS smooth bounce animation

In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:

.ball {
  animation: bounce 1s infinite alternate;
  -webkit-animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from {
    margin-top: 0;
  }
  to {
    margin-top: -15px;
  }
}

Twitter Bootstrap button click to toggle expand/collapse text section above button

Based on the doc

<div class="row">
    <div class="span4 collapse-group">
        <h2>Heading</h2>
        <p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
        <p><a class="btn" href="#">View details &raquo;</a></p>
    </div>
</div>
$('.row .btn').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    var $collapse = $this.closest('.collapse-group').find('.collapse');
    $collapse.collapse('toggle');
});

Working demo.

iOS - Build fails with CocoaPods cannot find header files

I was on the GM seed of Xcode 5.0 and I couldn't get any of these answers to work. I tried every single answer on SO on multiple different questions about header imports w/ cocoapods.

FINALLY I found a solution that worked for me: I upgraded to Xcode 5.0 via the Mac AppStore (installed on top of the GM seed) and now the header imports are working as expected.

I also still had a beta version of Xcode 5 on my system and I deleted that as well. Maybe it was a combination of the two things, but hopefully this helps someone else.

How to verify if $_GET exists?

You can use isset function:

if(isset($_GET['id'])) {
    // id index exists
}

You can create a handy function to return default value if index doesn't exist:

function Get($index, $defaultValue) {
    return isset($_GET[$index]) ? $_GET[$index] : $defaultValue;
}

// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');

You can also try to validate it at the same time:

function GetInt($index, $defaultValue) {
    return isset($_GET[$index]) && ctype_digit($_GET[$index])
            ? (int)$_GET[$index] 
            : $defaultValue;
}

// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);

Check if Variable is Empty - Angular 2

Lets say we have a variable called x, as below:

var x;

following statement is valid,

x = 10;
x = "a";
x = 0;
x = undefined;
x = null;

1. Number:

x = 10;
if(x){
//True
}

and for x = undefined or x = 0 (be careful here)

if(x){
 //False
}

2. String x = null , x = undefined or x = ""

if(x){
  //False
}

3 Boolean x = false and x = undefined,

if(x){
  //False
}

By keeping above in mind we can easily check, whether variable is empty, null, 0 or undefined in Angular js. Angular js doest provide separate API to check variable values emptiness.

Disable the postback on an <ASP:LinkButton>

ASPX code:

<asp:LinkButton ID="someID" runat="server" Text="clicky"></asp:LinkButton>

Code behind:

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        someID.Attributes.Add("onClick", "return false;");
    }
}

What renders as HTML is:

<a onclick="return false;" id="someID" href="javascript:__doPostBack('someID','')">clicky</a>

In this case, what happens is the onclick functionality becomes your validator. If it is false, the "href" link is not executed; however, if it is true the href will get executed. This eliminates your post back.

tqdm in Jupyter Notebook prints new progress bars repeatedly

To complete oscarbranson's answer: it's possible to automatically pick console or notebook versions of progress bar depending on where it's being run from:

from tqdm.autonotebook import tqdm

More info can be found here

How to override the path of PHP to use the MAMP path?

This is not an ideal solution as you have to manage two ini files however, I managed to work around this on windows by copying the php ini file in mamp from the conf folder to your active php version in the bin folder.

[MAMP INSTALL]\conf\[ACTIVE PHP VERSION]\php.ini

copy to

[MAMP INSTALL]\bin\php\[ACTIVE PHP VERSION]

Counting the number of elements in array

Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

But you can calculate count of elements in for loop. For example:

{% set count = 0 %}
{% for nc in notcount %}
    {% set count = count + 1 %}
{% endfor %}

{{ count }}

This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
    {% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}

{{ countNotEmpty }}

Useful links:

C#: Assign same value to multiple variables in single statement

Your example would be:

int num1 = 1;
int num2 = 1;

num1 = num2 = 5;

Mobile website "WhatsApp" button to send message to a specific number

WhatsApp is now providing a much simpler API https://wa.me/ This isn't introducing any new features, just a simpler way to execute things. There's no need to check for user agent while implementing this API as it will also work with native apps as well as the web interface of whatsapp (web.whatsapp.com) on desktop.

This can be used in multiple use cases

  • A Click to chat button : Use https://wa.me/whatsappphonenumber to open a chat dialog with the specified whatsapp user. Please note that the whatsappphonenumber should be a valid whatsapp number in international format without leading zeros, '+', '-' and spaces. e.g. 15551234567

    <a href="https://wa.me/15551234567">Whatsapp Me</a>

  • A Share this on whatsapp button : Use https://wa.me/?text=urlencodedtext to open a whatsapp contact selection dialog with a preset text. e.g.

    <a href="https://wa.me/?text=I%20found%20a%20great%20website.%20Check%20out%20this%20link%20https%3A%2F%2Fwww.example.com%2F">Share on WhatsApp</a>

  • A Contact me button with prefilled text : A combination of the above two, Might be useful if you want to get a prefilled custom message from users landing on a particular page. Use format https://wa.me/whatsappphonenumber/?text=urlencodedtext

    <a href="https://wa.me/15551234567?text=I%20am%20interested%20in%20your%20services.%20How%20to%20get%20started%3F">I am interested</a>

For official documentation visit https://faq.whatsapp.com/en/general/26000030

How do I install an R package from source?

From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection:

library(devtools)
install_github("twitter/AnomalyDetection")

does the trick.

Facebook Javascript SDK Problem: "FB is not defined"

Have you set the appId property to your current application ID?

How do I combine a background-image and CSS3 gradient on the same element?

If you have strange errors with downloading background images use W3C Link checker: https://validator.w3.org/checklink

Here are modern mixins that I use (credits: PSA: don't use gradient generators):

.buttonAkc
{
    .gradientBackground(@imageName: 'accept.png');
    background-repeat: no-repeat !important;
    background-position: center right, top left !important;
}

.buttonAkc:hover
{
    .gradientBackgroundHover('accept.png');
}

.gradientBackground(@startColor: #fdfdfd, @endColor: #d9d9db, @imageName)
{
    background-color: mix(@startColor, @endColor, 60%); // fallback
    background-image: url("@{img-folder}/@{imageName}?v=@{version}"); // fallback
    background: url("@{img-folder}/@{imageName}?v=@{version}") no-repeat scroll right center, -webkit-linear-gradient(top, @startColor 0%, @endColor 100%) no-repeat scroll left top; // Chrome 10-25, Safari 5.1-6
    background: url("@{img-folder}/@{imageName}?v=@{version}") no-repeat scroll right center, linear-gradient(to bottom, @startColor 0%, @endColor 100%) no-repeat scroll left top;
}

.gradientBackgroundHover(@imageName)
{
    .gradientBackground(#fdfdfd, #b5b6b9, @imageName);
}

How to call shell commands from Ruby

Some things to think about when choosing between these mechanisms are:

  1. Do you just want stdout or do you need stderr as well? Or even separated out?
  2. How big is your output? Do you want to hold the entire result in memory?
  3. Do you want to read some of your output while the subprocess is still running?
  4. Do you need result codes?
  5. Do you need a Ruby object that represents the process and lets you kill it on demand?

You may need anything from simple backticks (``), system(), and IO.popen to full-blown Kernel.fork/Kernel.exec with IO.pipe and IO.select.

You may also want to throw timeouts into the mix if a sub-process takes too long to execute.

Unfortunately, it very much depends.

More than one file was found with OS independent path 'META-INF/LICENSE'

Try to remove multidex from default config and check the build error log. If that log is some relatable with INotification class. Use this in android{}

configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
}

This helps me.

What are carriage return, linefeed, and form feed?

Have a look at Wikipedia:

Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A). These characters are based on printer commands: The line feed indicated that one line of paper should feed out of the printer, and a carriage return indicated that the printer carriage should return to the beginning of the current line.

Where is nodejs log file?

For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan

Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.

const appRoot = require('app-root-path');
const winston = require('winston');

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
} else {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
      new winston.transports.Console(options.console),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
}

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write(message) {
    logger.info(message);
  },
};

module.exports = logger;

After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log, " to the respective app.log created by you.

After this go to your index.js and include the following code in it.

const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));

winston.info('You have successfully started working with winston and morgan');

How to detect if a browser is Chrome using jQuery?

User Endless is right,

$.browser.chrome = (typeof window.chrome === "object"); 

code is best to detect Chrome browser using jQuery.

If you using IE and added GoogleFrame as plugin then

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

code will treat as Chrome browser because GoogleFrame plugin modifying the navigator property and adding chromeframe inside it.

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Ben is right. I also can't think of any way to do this. I'd suggest either the method Ben recommends, or the following to strip the Workbook name off.

Dim cell As Range
Dim address As String
Set cell = Worksheets(1).Cells.Range("A1")
address = cell.address(External:=True)
address = Right(address, Len(address) - InStr(1, address, "]"))

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

As Kaboing mentioned, MAXDOP(n) actually controls the number of CPU cores that are being used in the query processor.

On a completely idle system, SQL Server will attempt to pull the tables into memory as quickly as possible and join between them in memory. It could be that, in your case, it's best to do this with a single CPU. This might have the same effect as using OPTION (FORCE ORDER) which forces the query optimizer to use the order of joins that you have specified. IN some cases, I have seen OPTION (FORCE PLAN) reduce a query from 26 seconds to 1 second of execution time.

Books Online goes on to say that possible values for MAXDOP are:

0 - Uses the actual number of available CPUs depending on the current system workload. This is the default value and recommended setting.

1 - Suppresses parallel plan generation. The operation will be executed serially.

2-64 - Limits the number of processors to the specified value. Fewer processors may be used depending on the current workload. If a value larger than the number of available CPUs is specified, the actual number of available CPUs is used.

I'm not sure what the best usage of MAXDOP is, however I would take a guess and say that if you have a table with 8 partitions on it, you would want to specify MAXDOP(8) due to I/O limitations, but I could be wrong.

Here are a few quick links I found about MAXDOP:

Books Online: Degree of Parallelism

General guidelines to use to configure the MAXDOP option

Ruby objects and JSON serialization (without Rails)

To get the build in classes (like Array and Hash) to support as_json and to_json, you need to require 'json/add/core' (see the readme for details)

Change route params without reloading in Angular 2

As of RC6 you can do the following to change URL without change state and thereby keeping your route history

    import {OnInit} from '@angular/core';

    import {Location} from '@angular/common'; 
    // If you dont import this angular will import the wrong "Location"

    @Component({
        selector: 'example-component',
        templateUrl: 'xxx.html'
    })
    export class ExampleComponent implements OnInit {
        
        constructor( private location: Location )
        {}

        ngOnInit() {    
            this.location.replaceState("/some/newstate/");
        }
    }

How to change string into QString?

If compiled with STL compatibility, QString has a static method to convert a std::string to a QString:

std::string str = "abc";
QString qstr = QString::fromStdString(str);

AppSettings get value from .config file

Coming back to this one after a long time...

Given the demise of ConfigurationManager, for anyone still looking for an answer to this try (for example):

AppSettingsReader appsettingsreader = new AppSettingsReader();
string timeAsString = (string)(new AppSettingsReader().GetValue("Service.Instance.Trigger.Time", typeof(string)));

Requires System.Configuration of course.

(Editted the code to something that actually works and is simpler to read)

map vs. hash_map in C++

Some of the key differences are in the complexity requirements.

  • A map requires O(log(N)) time for inserts and finds operations, as it's implemented as a Red-Black Tree data structure.

  • An unordered_map requires an 'average' time of O(1) for inserts and finds, but is allowed to have a worst-case time of O(N). This is because it's implemented using Hash Table data structure.

So, usually, unordered_map will be faster, but depending on the keys and the hash function you store, can become much worse.

git commit error: pathspec 'commit' did not match any file(s) known to git

In my case, this error was due to special characters what I was considering double quotes as I copied the command from a web page.

error: command 'gcc' failed with exit status 1 while installing eventlet

For openSUSE 42.1 Leap Linux use this

sudo zypper install python3-devel

AppCompat v7 r21 returning error in values.xml?

In my case with Eclipse IDE, I had the same problem and the solution was:
1- Install the latest available API (SDK Platform & Google APIs)
2- Create the project with the following settings:

  • Compile With: use the latest API version available at the time
  • the other values can receive values according at your requirements (look at the meaning of each one in previous comments)

Finding the handle to a WPF window

If you want window handles for ALL of your application's Windows for some reason, you can use the Application.Windows property to get at all the Windows and then use WindowInteropHandler to get at their handles as you have already demonstrated.

Including external HTML file to another HTML file

Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.

<object data="html/stuff_to_include.html"> 
    Your browser doesn’t support the object tag. 
</object>

more info at http://www.w3schools.com/tags/tag_object.asp

Two color borders

This is very possible. It just takes a little CSS trickery!

_x000D_
_x000D_
div.border {_x000D_
  border: 1px solid #000;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
div.border:before {_x000D_
  position: absolute;_x000D_
  display: block;_x000D_
  content: '';_x000D_
  border: 1px solid red;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  box-sizing: border-box;_x000D_
  -moz-box-sizing: border-box;_x000D_
  -webkit-box-sizing: border-box;_x000D_
}
_x000D_
<div class="border">Hi I have two border colors<br />I am also Fluid</div>
_x000D_
_x000D_
_x000D_

Is that what you are looking for?

How to remove tab indent from several lines in IDLE?

By default, IDLE has it on Shift-Left Bracket. However, if you want, you can customise it to be Shift-Tab by clicking Options --> Configure IDLE --> Keys --> Use a Custom Key Set --> dedent-region --> Get New Keys for Selection

Then you can choose whatever combination you want. (Don't forget to click apply otherwise all the settings would not get affected.)

Adding a new SQL column with a default value

Simply add default 0 at the end of your ALTER TABLE <table> ADD COLUMN <column> <type> statement

How to get < span > value?

You need to change your code as below:-

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

After doing this you will get the tag value in alert.

Calculate row means on subset of columns

(Another solution using pivot_longer & pivot_wider from latest Tidyr update)

You should try using pivot_longer to get your data from wide to long form Read latest tidyR update on pivot_longer & pivot_wider (https://tidyr.tidyverse.org/articles/pivot.html)

library(tidyverse)
C1<-c(3,2,4,4,5)
C2<-c(3,7,3,4,5)
C3<-c(5,4,3,6,3)
DF<-data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)

Output here

  ID     mean
  <fct> <dbl>
1 A      3.67
2 B      4.33
3 C      3.33
4 D      4.67
5 E      4.33

What is default session timeout in ASP.NET?

It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.

See the HttpSessionState.Timeout property; default value is 20 minutes.

You can access this propery in ASP.NET via HttpContext:

this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere

How to find the last day of the month from date?

I have wrapped it in my date time helper class here https://github.com/normandqq/Date-Time-Helper using $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();

And it is done

Annotation-specified bean name conflicts with existing, non-compatible bean def

Refresh gradle project on Eclipse solved this problem for me

Difference between Spring MVC and Spring Boot

Without repeating the same thing in previous answers,
I'm writing this answer for the people who are looking to starting a new project and don't know which is the best framework to startup your project. If you are a beginner to this framework the best thing I prefer is Use spring boot(with STS /Spring Tool Suite). Because it helps a lot. Its do all configurations on its own. Additionally, use Hibernate with spring-boot as a database framework. With this combination, your application will be the best. I can guarantee that with my experiences.

Even this is one of the best frameworks for JEE(in present) this is gonna die in the near future. There are lightweight alternatives coming up. So keep updated with your experience don't stick to one particular framework. The best thing is being fluent in concepts, not in the frameworks.

Accessing dict_keys element by index in Python3

I wanted "key" & "value" pair of a first dictionary item. I used the following code.

 key, val = next(iter(my_dict.items()))

Reloading submodules in IPython

IPython comes with some automatic reloading magic:

%load_ext autoreload
%autoreload 2

It will reload all changed modules every time before executing a new line. The way this works is slightly different than dreload. Some caveats apply, type %autoreload? to see what can go wrong.


If you want to always enable this settings, modify your IPython configuration file ~/.ipython/profile_default/ipython_config.py[1] and appending:

c.InteractiveShellApp.extensions = ['autoreload']     
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

Credit to @Kos via a comment below.

[1] If you don't have the file ~/.ipython/profile_default/ipython_config.py, you need to call ipython profile create first. Or the file may be located at $IPYTHONDIR.

Is there any ASCII character for <br>?

<br> is an HTML element. There isn't any ASCII code for it.

But, for line break sometimes &#013; is used as the text code.

Or &lt;br&gt;

You can check the text code here.

How can I ssh directly to a particular directory?

In my very specific case, I just wanted to execute a command in a remote host, inside a specific directory from a Jenkins slave machine:

ssh myuser@mydomain
cd /home/myuser/somedir 
./commandThatMustBeRunInside_somedir
exit

But my machine couldn't perform the ssh (it couldn't allocate a pseudo-tty I suppose) and kept me giving the following error:

Pseudo-terminal will not be allocated because stdin is not a terminal

I could get around this issue passing "cd to dir + my command" as a parameter of the ssh command (to not have to allocate a Pseudo-terminal) and by passing the option -T to explicitly tell to the ssh command that I didn't need pseudo-terminal allocation.

ssh -T myuser@mydomain "cd /home/myuser/somedir; ./commandThatMustBeRunInside_somedir"

How to use refs in React with Typescript

Just to add a different approach - you can simply cast your ref, something like:

let myInputElement: Element = this.refs["myInput"] as Element

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

Elliot Beach is correct. Thanks Elliot.

Here is the code from my gist.

sudo apt-get remove docker docker-engine docker.io

sudo apt-get update

sudo apt-get install apt-transport-https ca-certificates curl software-properties-common

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

sudo apt-key fingerprint 0EBFCD88

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
xenial \
stable"

sudo apt-get update

sudo apt-get install docker-ce

sudo docker run hello-world

ERROR: Sonar server 'http://localhost:9000' can not be reached

When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.

How to write a test which expects an Error to be thrown in Jasmine?

As mentioned previously, a function needs to be passed to toThrow as it is the function you're describing in your test: "I expect this function to throw x"

expect(() => parser.parse(raw))
  .toThrow(new Error('Parsing is not possible'));

If using Jasmine-Matchers you can also use one of the following when they suit the situation;

// I just want to know that an error was
// thrown and nothing more about it
expect(() => parser.parse(raw))
  .toThrowAnyError();

or

// I just want to know that an error of 
// a given type was thrown and nothing more
expect(() => parser.parse(raw))
  .toThrowErrorOfType(TypeError);

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

You misspelled permission

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

ORA-12560: TNS:protocol adaptor error

In my case I didn't have an OracleService (OracleServiceORCL) in Windows Services.msc as described in Bharathi's answer.

I executed this command:

C:\> ORADIM -NEW -SID ORCL

and then the OracleService called OracleServiceORCL just showed up and got started in Services.msc. Really nice.


Source: https://forums.oracle.com/forums/message.jspa?messageID=4044655#4044655

Converting JavaScript object with numeric keys into array

It's actually very straight forward with jQuery's $.map

var arr = $.map(obj, function(el) { return el });

FIDDLE

and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map

var arr = Object.keys(obj).map(function(k) { return obj[k] });

FIDDLE

That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.

In ES2015 there's Object.values to the rescue, which makes this a breeze

var arr = Object.values(obj);

C# Convert List<string> to Dictionary<string, string>

Try this:

var res = list.ToDictionary(x => x, x => x);

The first lambda lets you pick the key, the second one picks the value.

You can play with it and make values differ from the keys, like this:

var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));

If your list contains duplicates, add Distinct() like this:

var res = list.Distinct().ToDictionary(x => x, x => x);

EDIT To comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are always going to be the same, HashSet<String> would provide a much better fit for your situation:

var res = new HashSet<string>(list);
if (res.Contains("string1")) ...

How can I select checkboxes using the Selenium Java WebDriver?

Maybe a good starting point:

isChecked  = driver.findElement((By.id("idOftheElement"))).getAttribute("name");
if(!isChecked.contains("chkOptions$1"))
{
    driver.FindElement(By.Id("idOfTheElement")).Click();
}

Run a task every x-minutes with Windows Task Scheduler

After you select the minimum repeat option (5 minutes or 10 minutes) you can highlight the number and write whatever number you want

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

Discard all and get clean copy of latest revision?

Those steps should be able to be shortened down to:

hg pull
hg update -r MY_BRANCH -C

The -C flag tells the update command to discard all local changes before updating.

However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge extension for that:

hg pull
hg update -r MY_BRANCH -C
hg purge

In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.

Interface vs Base class

In addition to those comments that mention the IPet/PetBase implementation, there are also cases where providing an accessor helper class can be very valuable.

The IPet/PetBase style assumes that you have multiple implementations thus increasing the value of PetBase since it simplifies implementation. However, if you have the reverse or a blend of the two where you have multiple clients, providing a class help assist in the usage of the interface can reduce cost by making it easier to use an interface.

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

The application was unable to start correctly (0xc000007b)

I have seen the error trying to run VC++ debug executable on a machine which did not have Visual C++ installed. Building a release version and using that fixed it.

Regex to match words of a certain length

^\w{0,10}$ # allows words of up to 10 characters.
^\w{5,}$   # allows words of more than 4 characters.
^\w{5,10}$ # allows words of between 5 and 10 characters.

Any way to replace characters on Swift String?

Swift 3 solution based on Ramis' answer:

extension String {
    func withReplacedCharacters(_ characters: String, by separator: String) -> String {
        let characterSet = CharacterSet(charactersIn: characters)
        return components(separatedBy: characterSet).joined(separator: separator)
    }
}

Tried to come up with an appropriate function name according to Swift 3 naming convention.

Can I change the height of an image in CSS :before/:after pseudo-elements?

You can change the height or width of the Before or After element like this:

.element:after {
  display: block;
  content: url('your-image.png');
  height: 50px; //add any value you need for height or width
  width: 50px;
}

Remove everything after a certain character

var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);

Sample here

I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).

Updated code to account for no '?':

var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);

Sample here

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I faced the same issue. I had missed the forms module import tag in the app.module.ts

import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [BrowserModule,
        FormsModule
    ],

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:

IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END 

Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.


If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.

IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE clockDate = '08/10/2012' AND userName = 'test'
END 

As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.

Python Matplotlib Y-Axis ticks on Right Side of Plot

Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:

import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()

It will show this:

enter image description here

Git add all subdirectories

You can also face problems if a subdirectory itself is a git repository - ie .has a .git directory - check with ls -a.

To remove go to the subdirectory and rm .git -rf.

VBA Date as integer

Public SUB test()
    Dim mdate As Date
    mdate = now()
    MsgBox (Round(CDbl(mdate), 0))
End SUB

How to use forEach in vueJs?

This is an example of forEach usage:

let arr = [];

this.myArray.forEach((value, index) => {
    arr.push(value);
    console.log(value);
    console.log(index);
});

In this case, "myArray" is an array on my data.

You can also loop through an array using filter, but this one should be used if you want to get a new list with filtered elements of your array.

Something like this:

const newArray = this.myArray.filter((value, index) => {
    console.log(value);
    console.log(index);
    if (value > 5) return true;
});

and the same can be written as:

const newArray = this.myArray.filter((value, index) => value > 5);

Both filter and forEach are javascript methods and will work just fine with VueJs. Also, it might be interesting taking a look at this:

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Creating a Menu in Python

It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:

def addstudent():
    print("Student Added.")

then called by writing addstudent().

I would recommend using a while loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked), then put the if statements after the while. Or you can do a while loop and continue the loop if a valid option is not selected.

Additionally, a dictionary is defined in the following way:

my_dict = {key:definition,...}

Does uninstalling a package with "pip" also remove the dependent packages?

You can install and use the pip-autoremove utility to remove a package plus unused dependencies.

# install pip-autoremove
pip install pip-autoremove
# remove "somepackage" plus its dependencies:
pip-autoremove somepackage -y

What is ANSI format?

Basically "ANSI" refers to the legacy codepage on Windows. See also an article by Raymond Chen on this topic:

The source of this comes from the fact that the Windows code page 1252 was originally based on an ANSI draft, which became ISO Standard 8859-1.

The first 127 characters are identical to ASCII in most code pages, the upper characters vary, though.

However, ANSI does not automatically mean CP1252 or Latin 1.

All confusion notwithstanding you should simply avoid such issues nowadays and use Unicode.

What causes a SIGSEGV

The initial source cause can also be an out of memory.

How to change RGB color to HSV?

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just calculations.

found via Google

Find all table names with column name?

You could do this:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;

Reference:

How to add icons to React Native app

If you're using expo just place an 1024 x 1024 png file in your project and add an icon property to your app.json i.e. "icon": "./src/assets/icon.png"

https://docs.expo.io/versions/latest/guides/app-icons

Where should I put <script> tags in HTML markup?

The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document body so they don't block rendering of the page.

But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:

There are some great slides by Steve Souders (client-side performance expert) about:

  • Different techniques to load external JavaScript files in parallel
  • their effect on loading time and page rendering
  • what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).

Xcode 4: create IPA file instead of .xcarchive

One who has tried all other answers and had no luck the please check this check box, hope it'll help (did the trick for me xcode 6.0.1)

enter image description here

Adding a background image to a <div> element

<div class="foo">Foo Bar</div>

and in your CSS file:

.foo {
    background-image: url("images/foo.png");
}

JSON find in JavaScript

General Solution

We use object-scan for a lot of data processing. It has some nice properties, especially traversing in delete safe order. Here is how one could implement find, delete and replace for your question.

_x000D_
_x000D_
// const objectScan = require('object-scan');

const tool = (() => {
  const scanner = objectScan(['[*]'], {
    abort: true,
    rtn: 'bool',
    filterFn: ({
      value, parent, property, context
    }) => {
      if (value.id === context.id) {
        context.fn({ value, parent, property });
        return true;
      }
      return false;
    }
  });
  return {
    add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
    del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
    mod: (data, id, prop, v = undefined) => scanner(data, {
      id,
      fn: ({ value }) => {
        if (value !== undefined) {
          value[prop] = v;
        } else {
          delete value[prop];
        }
      }
    })
  };
})();

// -------------------------------

const data = [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ];
const toAdd = { id: 'two', pId: 'foo2', cId: 'bar2' };

const exec = (fn) => {
  console.log('---------------');
  console.log(fn.toString());
  console.log(fn());
  console.log(data);
};

exec(() => tool.add(data, 'one', toAdd));
exec(() => tool.mod(data, 'one', 'pId', 'zzz'));
exec(() => tool.mod(data, 'one', 'other', 'test'));
exec(() => tool.mod(data, 'one', 'gone', 'delete me'));
exec(() => tool.mod(data, 'one', 'gone'));
exec(() => tool.del(data, 'three'));

// => ---------------
// => () => tool.add(data, 'one', toAdd)
// => true
// => [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'pId', 'zzz')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'other', 'test')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone', 'delete me')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: 'delete me' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.del(data, 'three')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.

I did it a different way, without using VBA, by using a table containing the query parameters.

E.g:

SELECT a_table.a_field 
FROM QueryParameters, a_table 
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min 
AND QueryParameters.a_field_max

Where QueryParameters is a table with two fields, a_field_min and a_field_max

It can even be used with GROUP BY, if you include the query parameter fields in the GROUP BY clause, and the FIRST operator on the parameter fields in the HAVING clause.

How to exit an application properly

Just Close() all active/existing forms and the application should exit.

How to include a Font Awesome icon in React's render()

In case you are looking to include the font awesome library without having to do module imports and npm installs, put this in the head section of your React index.html page:

public/index.html (in head section)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>

Then in your component (such as App.js) just use standard font awesome class convention. Just remember to use className instead of class:

<button className='btn'><i className='fa fa-home'></i></button>

how to get the 30 days before date from Todays Date

Try adding this to your where clause:

dateadd(day, -30, getdate())

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

I recently found this library that converts an Excel workbook file into a DataSet: Excel Data Reader

How can I export the schema of a database in PostgreSQL?

In Linux you can do like this

pg_dump -U postgres -s postgres > exportFile.dmp

Maybe it can work in Windows too, if not try the same with pg_dump.exe

pg_dump.exe -U postgres -s postgres > exportFile.dmp

Django DateField default options

Your mistake is using the datetime module instead of the date module. You meant to do this:

from datetime import date
date = models.DateField(_("Date"), default=date.today)

If you only want to capture the current date the proper way to handle this is to use the auto_now_add parameter:

date = models.DateField(_("Date"), auto_now_add=True)

However, the modelfield docs clearly state that auto_now_add and auto_now will always use the current date and are not a default value that you can override.

How to drop a table if it exists?

I use:

if exists (select * 
           from sys.tables 
           where name = 'tableName' 
           and schema_id = schema_id('dbo'))
begin
    drop table dbo.tableName
end

Running stages in parallel with Jenkins workflow / pipeline

I have just tested the following pipeline and it works

parallel firstBranch: {
    stage ('Starting Test') 
    {
        build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
    }
}, secondBranch: {
    stage ('Starting Test2') 
    {
        build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
    }
}

This Job named 'trigger-test' accepts one parameter named 'Environment'

Job 'test1' and 'test2' are simple jobs:

Example for 'test1'

  • One parameter named 'Environment'
  • Pipeline : echo "$env.Environment-TEST1"

On execution, I am able to see both stages running in the same time

Tkinter: How to use threads to preventing main event loop from "freezing"

The problem is that t.join() blocks the click event, the main thread does not get back to the event loop to process repaints. See Why ttk Progressbar appears after process in Tkinter or TTK progress bar blocked when sending email

console.log(result) returns [object Object]. How do I get result.name?

Use console.log(JSON.stringify(result)) to get the JSON in a string format.

EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty and access the property if it does exist:

var obj = {id : "007", name : "James Bond"};
console.log(obj);                    // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj));    //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
    console.log(obj.id);             //007
}

Cannot read property 'map' of undefined

I considered giving a comment under the answer by taggon to this very question, but well, i felt it owed more explanation for those interested in details.

Uncaught TypeError: Cannot read property 'value' of undefined is strictly a JavaScript error.
(Note that value can be anything, but for this question value is 'map')

It's critical to understand that point, just so you avoid endless debugging cycles.
This error is common especially if just starting out in JavaScript (and it's libraries/frameworks).
For React, this has a lot to do with understanding the component lifecycle methods.

// Follow this example to get the context
// Ignore any complexity, focus on how 'props' are passed down to children

import React, { useEffect } from 'react'

// Main component
const ShowList = () => {
  // Similar to componentDidMount and componentDidUpdate
  useEffect(() => {// dispatch call to fetch items, populate the redux-store})

  return <div><MyItems items={movies} /></div>
}

// other component
const MyItems = props =>
  <ul>
    {props.items.map((item, i) => <li key={i}>item</li>)}
  </ul>


/**
  The above code should work fine, except for one problem.
  When compiling <ShowList/>,
  React-DOM renders <MyItems> before useEffect (or componentDid...) is called.
  And since `items={movies}`, 'props.items' is 'undefined' at that point.
  Thus the error message 'Cannot read property map of undefined'
 */

As a way to tackle this problem, @taggon gave a solution (see first anwser or link).

Solution: Set an initial/default value.
In our example, we can avoid items being 'undefined' by declaring a default value of an empty array.

Why? This allows React-DOM to render an empty list initially.
And when the useEffect or componentDid... method is executed, the component is re-rendered with a populated list of items.

// Let's update our 'other' component
// destructure the `items` and initialize it as an array

const MyItems = ({items = []}) =>
  <ul>
    {items.map((item, i) => <li key={i}>item</li>)}
  </ul>

Why would one use nested classes in C++?

I don't use nested classes much, but I do use them now and then. Especially when I define some kind of data type, and I then want to define a STL functor designed for that data type.

For example, consider a generic Field class that has an ID number, a type code and a field name. If I want to search a vector of these Fields by either ID number or name, I might construct a functor to do so:

class Field
{
public:
  unsigned id_;
  string name_;
  unsigned type_;

  class match : public std::unary_function<bool, Field>
  {
  public:
    match(const string& name) : name_(name), has_name_(true) {};
    match(unsigned id) : id_(id), has_id_(true) {};
    bool operator()(const Field& rhs) const
    {
      bool ret = true;
      if( ret && has_id_ ) ret = id_ == rhs.id_;
      if( ret && has_name_ ) ret = name_ == rhs.name_;
      return ret;
    };
    private:
      unsigned id_;
      bool has_id_;
      string name_;
      bool has_name_;
  };
};

Then code that needs to search for these Fields can use the match scoped within the Field class itself:

vector<Field>::const_iterator it = find_if(fields.begin(), fields.end(), Field::match("FieldName"));

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

There are other options for you to benchmark:

1.) A window function will return the actual size directly (tested in MariaDB):

SELECT 
  `mytable`.*,
  COUNT(*) OVER() AS `total_count`
FROM `mytable`
ORDER BY `mycol`
LIMIT 10, 20

2.) Thinking out of the box, most of the time users don't need to know the EXACT size of the table, an approximate is often good enough.

SELECT `TABLE_ROWS` AS `rows_approx`
FROM `INFORMATION_SCHEMA`.`TABLES`
WHERE `TABLE_SCHEMA` = DATABASE()
  AND `TABLE_TYPE` = "BASE TABLE"
  AND `TABLE_NAME` = ?

Ways to circumvent the same-origin policy

The most recent way of overcoming the same-origin policy that I've found is http://anyorigin.com/

The site's made so that you just give it any url and it generates javascript/jquery code for you that lets you get the html/data, regardless of it's origin. In other words, it makes any url or webpage a JSONP request.

I've found it pretty useful :)

Here's some example javascript code from anyorigin:

$.getJSON('http://anyorigin.com/get?url=google.com&callback=?', function(data){
    $('#output').html(data.contents);
});

What is a loop invariant?

Loop invariant is a mathematical formula such as (x=y+1). In that example, x and y represent two variables in a loop. Considering the changing behavior of those variables throughout the execution of the code, it is almost impossible to test all possible to x and y values and see if they produce any bug. Lets say x is an integer. Integer can hold 32 bit space in the memory. If that number exceeds, buffer overflow occurs. So we need to be sure that throughout the execution of the code, it never exceeds that space. for that, we need to understand a general formula that shows the relationship between variables. After all, we just try to understand the behavior of the program.

Extracting specific columns in numpy array

Assuming you want to get columns 1 and 9 with that code snippet, it should be:

extractedData = data[:,[1,9]]

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

With VSTS the url is, When you copy git clone url from vsts you always get

https://orgname@dev.azure.com/org/project/_git/repo

Replace orgname@ with your alternate username that you would have created in VSTS -> profile -> Security.

final git url -

https://alternateusername@dev.azure.com/org/project/_git/repo

Eclipse keyboard shortcut to indent source code to the left?

On Mac (on french keyboard its) cmd + shift + F

How to remove trailing whitespaces with sed?

Thanks to codaddict for suggesting the -i option.

The following command solves the problem on Snow Leopard

sed -i '' -e's/[ \t]*$//' "$1"

Can you pass parameters to an AngularJS controller on creation?

It looks like the best solution for you is actually a directive. This allows you to still have your controller, but define custom properties for it.

Use this if you need access to variables in the wrapping scope:

angular.module('myModule').directive('user', function ($filter) {
  return {
    link: function (scope, element, attrs) {
      $scope.connection = $resource('api.com/user/' + attrs.userId);
    }
  };
});

<user user-id="{% id %}"></user>

Use this if you don't need access to variables in the wrapping scope:

angular.module('myModule').directive('user', function ($filter) {
  return {
    scope: {
      userId: '@'
    },
    link: function (scope, element, attrs) {
      $scope.connection = $resource('api.com/user/' + scope.userId);
    }
  };
});

<user user-id="{% id %}"></user>

Using Excel as front end to Access database (with VBA)

I'm sure you'll get a ton of "don't do this" answers, and I must say, there is good reason. This isn't an ideal solution....

That being said, I've gone down this road (and similar ones) before, mostly because the job specified it as a hard requirement and I couldn't talk around it.

Here are a few things to consider with this:

How easy is it to link to Access from Excel using ADO / DAO? Is it quite limited in terms of functionality or can I get creative?

It's fairly straitforward. You're more limited than you would be doing things using other tools, since VBA and Excel forms is a bit more limiting than most full programming languages, but there isn't anything that will be a show stopper. It works - sometimes its a bit ugly, but it does work. In my last company, I often had to do this - and occasionally was pulling data from Access and Oracle via VBA in Excel.

Do I pay a performance penalty (vs.using forms in Access as the UI)?

My experience is that there is definitely a perf. penalty in doing this. I never cared (in my use case, things were small enough that it was reasonable), but going Excel<->Access is a lot slower than just working in Access directly. Part of it depends on what you want to do....

In my case, the thing that seemed to be the absolute slowest (and most painful) was trying to fill in Excel spreadsheets based on Access data. This wasn't fun, and was often very slow. If you have to go down this road, make sure to do everything with Excel hidden/invisible, or the redrawing will absolutely kill you.

Assuming that the database will always be updated using ADO / DAO commands from within Excel VBA, does that mean I can have multiple Excel users using that one single Access database and not run into any concurrency issues etc.?

You're pretty much using Excel as a client - the same way you would use a WinForms application or any other tool. The ADO/DAO clients for Access are pretty good, so you probably won't run into any concurrency issues.

That being said, Access does NOT scale well. This works great if you have 2 or 3 (or even 10) users. If you are going to have 100, you'll probably run into problems. Also, I tended to find that Access needed regular maintenance in order to not have corruption issues. Regular backups of the Access DB are a must. Compacting the access database on a regular basis will help prevent database corruption, in my experience.

Any other things I should be aware of?

You're doing this the hard way. Using Excel to hit Access is going to be a lot more work than just using Access directly.

I'd recommend looking into the Access VBA API - most of it is the same as Excel, so you'll have a small learning curve. The parts that are different just make this easier. You'll also have all of the advantages of Access reporting and Forms, which are much more data-oriented than the ones in Excel. The reporting can be great for things like this, and having the Macros and Reports will make life easier in the long run. If the user's going to be using forms to manage everything, doing the forms in Access will be very, very similar to doing them in Excel, and will look nearly identical, but will make everything faster and smoother.

AWK: Access captured group from line pattern

You can simulate capturing in vanilla awk too, without extensions. Its not intuitive though:

step 1. use gensub to surround matches with some character that doesnt appear in your string. step 2. Use split against the character. step 3. Every other element in the splitted array is your capture group.

$ echo 'ab cb ad' | awk '{ split(gensub(/a./,SUBSEP"&"SUBSEP,"g",$0),cap,SUBSEP); print cap[2]"|" cap[4] ; }'
ab|ad

Regex pattern inside SQL Replace function?

You can use PATINDEX to find the first index of the pattern (string's) occurrence. Then use STUFF to stuff another string into the pattern(string) matched.

Loop through each row. Replace each illegal characters with what you want. In your case replace non numeric with blank. The inner loop is if you have more than one illegal character in a current cell that of the loop.

DECLARE @counter int

SET @counter = 0

WHILE(@counter < (SELECT MAX(ID_COLUMN) FROM Table))
BEGIN  

    WHILE 1 = 1
    BEGIN
        DECLARE @RetVal varchar(50)

        SET @RetVal =  (SELECT Column = STUFF(Column, PATINDEX('%[^0-9.]%', Column),1, '')
        FROM Table
        WHERE ID_COLUMN = @counter)

        IF(@RetVal IS NOT NULL)       
          UPDATE Table SET
          Column = @RetVal
          WHERE ID_COLUMN = @counter
        ELSE
            break
    END

    SET @counter = @counter + 1
END

Caution: This is slow though! Having a varchar column may impact. So using LTRIM RTRIM may help a bit. Regardless, it is slow.

Credit goes to this StackOverFlow answer.

EDIT Credit also goes to @srutzky

Edit (by @Tmdean) Instead of doing one row at a time, this answer can be adapted to a more set-based solution. It still iterates the max of the number of non-numeric characters in a single row, so it's not ideal, but I think it should be acceptable in most situations.

WHILE 1 = 1 BEGIN
    WITH q AS
        (SELECT ID_Column, PATINDEX('%[^0-9.]%', Column) AS n
        FROM Table)
    UPDATE Table
    SET Column = STUFF(Column, q.n, 1, '')
    FROM q
    WHERE Table.ID_Column = q.ID_Column AND q.n != 0;

    IF @@ROWCOUNT = 0 BREAK;
END;

You can also improve efficiency quite a lot if you maintain a bit column in the table that indicates whether the field has been scrubbed yet. (NULL represents "Unknown" in my example and should be the column default.)

DECLARE @done bit = 0;
WHILE @done = 0 BEGIN
    WITH q AS
        (SELECT ID_Column, PATINDEX('%[^0-9.]%', Column) AS n
        FROM Table
        WHERE COALESCE(Scrubbed_Column, 0) = 0)
    UPDATE Table
    SET Column = STUFF(Column, q.n, 1, ''),
        Scrubbed_Column = 0
    FROM q
    WHERE Table.ID_Column = q.ID_Column AND q.n != 0;

    IF @@ROWCOUNT = 0 SET @done = 1;

    -- if Scrubbed_Column is still NULL, then the PATINDEX
    -- must have given 0
    UPDATE table
    SET Scrubbed_Column = CASE
        WHEN Scrubbed_Column IS NULL THEN 1
        ELSE NULLIF(Scrubbed_Column, 0)
    END;
END;

If you don't want to change your schema, this is easy to adapt to store intermediate results in a table valued variable which gets applied to the actual table at the end.

Java - Convert integer to string

There are multiple ways:

  • String.valueOf(number) (my preference)
  • "" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above)
  • Integer.toString(number)

How to fix the "508 Resource Limit is reached" error in WordPress?

On my blog, the reason of this error is a plugin named Broken Link checker. This plugin has high resource usage from hosting, resulting in this error.

Check if a plugin on your installation is behaving similarly like this.

How to sort an array of objects with jquery or javascript

data.sort(function(a,b) 
{
   return a.val - b.val;
});

Simple way to query connected USB devices info in Python?

If you are working on windows, you can use pywin32 (old link: see update below).

I found an example here:

import win32com.client

wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
    print usb.DeviceID

Update Apr 2020:

'pywin32' release versions from 218 and up can be found here at github. Current version 227.

Call a Vue.js component method from outside the component

Here is a simple one

this.$children[indexOfComponent].childsMethodName();

Char array declaration and initialization in C

I think these are two really different cases. In the first case memory is allocated and initialized in compile-time. In the second - in runtime.

Collapse all methods in Visual Studio Code

  • Fold All:

    • Windows: Ctrl + K + 0
    • Mac: ? + K + 0
  • Unfold All:

    • Windows: Ctrl + K + J
    • Mac: ? + K + J

To see all available shortcuts in the editor:

  • Windows: Ctrl + K + S
  • Mac: ? + K + S

Screenshot of Visual Studio keyboard shortcuts

All shortcuts kept up to date by the Visual Studio Code team: Visual Studio Code Shortcuts

Laravel redirect back to original destination after login

Laravel now supports this feature out-of-the-box! (I believe since 5.5 or earlier).

Add a __construct() method to your Controller as shown below:

public function __construct()
{
    $this->middleware('auth');
}

After login, your users will then be redirected to the page they intended to visit initially.

You can also add Laravel's email verification feature as required by your application logic:

public function __construct()
{
    $this->middleware(['auth', 'verified']);
}

The documentation contains a very brief example:

It's also possible to choose which controller's methods the middleware applies to by using except or only options.

Example with except:

public function __construct()
{
    $this->middleware('auth', ['except' => ['index', 'show']]);
}

Example with only:

public function __construct()
{
    $this->middleware('auth', ['only' => ['index', 'show']]);
}

More information about except and only middleware options:

JSTL if tag for equal strings

I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:

This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

So in your case the JSTL code should look like the following, note the capital 'P':

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

How to get all key in JSON object (javascript)

ES6 of the day here;

const json_getAllKeys = data => (
  data.reduce((keys, obj) => (
    keys.concat(Object.keys(obj).filter(key => (
      keys.indexOf(key) === -1))
    )
  ), [])
)

And yes it can be written in very long one line;

const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])

EDIT: Returns all first order keys if the input is of type array of objects

How to change DatePicker dialog color for Android 5.0

Just to mention, you can also use the default a theme like android.R.style.Theme_DeviceDefault_Light_Dialog instead.

new DatePickerDialog(MainActivity.this, android.R.style.Theme_DeviceDefault_Light_Dialog, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    //DO SOMETHING
    }
}, 2015, 02, 26).show();

stale element reference: element is not attached to the page document

According to @Abhishek Singh's you need to understand the problem:

What is the line which gives exception ?? The reason for this is because the element to which you have referred is removed from the DOM structure

and you can not refer to it anymore (imagine what element's ID has changed).

Follow the code:

class TogglingPage {
  @FindBy(...)
  private WebElement btnTurnOff;

  @FindBy(...)
  private WebElement btnTurnOn;

  TogglingPage turnOff() {
    this.btnTurnOff.isDisplayed();  
    this.btnTurnOff.click();          // when clicked, button should swap into btnTurnOn
    this.btnTurnOn.isDisplayed();
    this.btnTurnOn.click();           // when clicked, button should swap into btnTurnOff
    this.btnTurnOff.isDisplayed();    // throws an exception
    return new TogglingPage();
  }
}

Now, let us wonder why?

  1. btnTurnOff was found by a driver - ok
  2. btnTurnOff was replaced by btnTurnOn - ok
  3. btnTurnOn was found by a driver. - ok
  4. btnTurnOn was replaced by btnTurnOff - ok
  5. we call this.btnTurnOff.isDisplayed(); on the element which does not exist anymore in Selenium sense - you can see it, it works perfectly, but it is a different instance of the same button.

Possible fix:

  TogglingPage turnOff() {
    this.btnTurnOff.isDisplayed();  
    this.btnTurnOff.click();

    TogglingPage newPage = new TogglingPage();
    newPage.btnTurnOn.isDisplayed();
    newPage.btnTurnOn.click();

    TogglingPage newerPage = new TogglingPage();
    newerPage.btnTurnOff.isDisplayed();    // ok
    return newerPage;
  }

Serialize an object to XML

To serialize an object, do:

 using (StreamWriter myWriter = new StreamWriter(path, false))
 {
     XmlSerializer mySerializer = new XmlSerializer(typeof(your_object_type));
     mySerializer.Serialize(myWriter, objectToSerialize);
 }

Also remember that for XmlSerializer to work, you need a parameterless constructor.

Spring Boot Remove Whitelabel Error Page

Spring boot doc 'was' wrong (they have since fixed it) :

To switch it off you can set error.whitelabel.enabled=false

should be

To switch it off you can set server.error.whitelabel.enabled=false

Setting device orientation in Swift iOS

More Swift-like version:

override func shouldAutorotate() -> Bool {
    switch UIDevice.currentDevice().orientation {
    case .Portrait, .PortraitUpsideDown, .Unknown:
        return true
    default:
        return false
    }
}

override func supportedInterfaceOrientations() -> Int {
    return Int(UIInterfaceOrientationMask.Portrait.rawValue) | Int(UIInterfaceOrientationMask.PortraitUpsideDown.rawValue)
}

UINavigationController from Vivek Parihar

extension UINavigationController {
    public override func shouldAutorotate() -> Bool {
        return visibleViewController.shouldAutorotate()
    }
}

How do I loop through rows with a data reader in C#?

Actually the Read method iterating over records in a result set. In your case - over table rows. So you still can use it.

How can I create a link to a local file on a locally-run web page?

I've a way and work like this:

<'a href="FOLDER_PATH" target="_explorer.exe">Link Text<'/a>

Javascript: How to check if a string is empty?

I check length.

if (str.length == 0) {
}

How to read response headers in angularjs?

Why not simply try this:

var promise = $http.get(url, {
    params: query
}).then(function(response) {
  console.log('Content-Range: ' + response.headers('Content-Range'));
  return response.data;
});

Especially if you want to return the promise so it could be a part of a promises chain.

What causes a java.lang.StackOverflowError

Stack Overflow exceptions can occur when a thread stack continues to grow in size until reaching the maximum limit.

Adjusting the Stack Sizes (Xss and Xmso) options...

I suggest you see this link: http://www-01.ibm.com/support/docview.wss?uid=swg21162896 There are many possible causes to a StackOverflowError, as you can see in the link....

List of tuples to dictionary

With dict comprehension:

h = {k:v for k,v in l}

Insert string at specified position

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

Possible heap pollution via varargs parameter

It's rather safe to add @SafeVarargs annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.

If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>) input instead of varargs (Type1<Type2>...).

As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

It is because you haven't qualified Cells(1, 1) with a worksheet object, and the same holds true for Cells(10, 2). For the code to work, it should look something like this:

Dim ws As Worksheet

Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

Alternately:

With Sheets("SheetName")
    Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range also, like so:

ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

or

With Sheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

How to call a function, PostgreSQL

For Postgresql you can use PERFORM. PERFORM is only valid within PL/PgSQL procedure language.

DO $$ BEGIN
    PERFORM "saveUser"(3, 'asd','asd','asd','asd','asd');
END $$;

The suggestion from the postgres team:

HINT: If you want to discard the results of a SELECT, use PERFORM instead.

How to create a new component in Angular 4 using CLI

There are mainly two ways to generate new component in Angular, using ng g c <component_name> , another way is that using ng generate component <component_name>. using one of these commands new component can be generated.

Autowiring two beans implementing same interface - how to set default bean to autowire?

What about @Primary?

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.

@Primary
public class HibernateDeviceDao implements DeviceDao

Or if you want your Jdbc version to be used by default:

<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">

@Primary is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.

The simplest way to comma-delimit a list?

You can also unconditionally add the delimiter string, and after the loop remove the extra delimiter at the end. Then an "if list is empty then return this string" at the beginning will allow you to avoid the check at the end (as you cannot remove characters from an empty list)

So the question really is:

"Given a loop and an if, what do you think is the clearest way to have these together?"

Is the sizeof(some pointer) always equal to four?

Technically speaking, the C standard only guarantees that sizeof(char) == 1, and the rest is up to the implementation. But on modern x86 architectures (e.g. Intel/AMD chips) it's fairly predictable.

You've probably heard processors described as being 16-bit, 32-bit, 64-bit, etc. This usually means that the processor uses N-bits for integers. Since pointers store memory addresses, and memory addresses are integers, this effectively tells you how many bits are going to be used for pointers. sizeof is usually measured in bytes, so code compiled for 32-bit processors will report the size of pointers to be 4 (32 bits / 8 bits per byte), and code for 64-bit processors will report the size of pointers to be 8 (64 bits / 8 bits per byte). This is where the limitation of 4GB of RAM for 32-bit processors comes from -- if each memory address corresponds to a byte, to address more memory you need integers larger than 32-bits.

Skip Git commit hooks

From man githooks:

pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

Truncate Two decimal places without rounding

It would be more useful to have a full function for real-world usage of truncating a decimal in C#. This could be converted to a Decimal extension method pretty easy if you wanted:

public decimal TruncateDecimal(decimal value, int precision)
{
    decimal step = (decimal)Math.Pow(10, precision);
    decimal tmp = Math.Truncate(step * value);
    return tmp / step;
}

If you need VB.NET try this:

Function TruncateDecimal(value As Decimal, precision As Integer) As Decimal
    Dim stepper As Decimal = Math.Pow(10, precision)
    Dim tmp As Decimal = Math.Truncate(stepper * value)
    Return tmp / stepper
End Function

Then use it like so:

decimal result = TruncateDecimal(0.275, 2);

or

Dim result As Decimal = TruncateDecimal(0.275, 2)

How to find a text inside SQL Server procedures / triggers?

I've used these in the past:

In this particular case, where you need to replace a specific string across stored procedures, the first link is probably more relevant.

A little off-topic, the Quick Find add-in is also useful for searching object names with SQL Server Management Studio. There's a modified version available with some improvements, and another newer version also available on Codeplex with some other useful add-ins as well.

How can I process each letter of text using Javascript?

You can simply iterate it as in an array:

for(var i in txt){
    console.log(txt[i]);
}

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

Open Graph data:

<meta property="og:title" content="Title of your website | website.com"/>
<meta property="og:type" content="Most popular business directory of Bangladesh"/>
<meta property="og:url" content="http://www.website.com/"/>
<meta property="og:image" content="http://www.moumaachi.com/images/dhaka-city.jpg"/>
<meta property="og:site_name" content="@website"/>
<meta property="fb:admins" content="Author"/>
<meta property="og:description" content="website.com is your online business directory of Country"/>

Date minus 1 year?

Use strtotime() function:

  $time = strtotime("-1 year", time());
  $date = date("Y-m-d", $time);

Error: class X is public should be declared in a file named X.java

The name of the public class within a file has to be the same as the name of that file.

So if your file declares class WeatherArray, it needs to be named WeatherArray.java

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How to convert an int value to string in Go?

Use the strconv package's Itoa function.

For example:

package main

import (
    "strconv"
    "fmt"
)

func main() {
    t := strconv.Itoa(123)
    fmt.Println(t)
}

You can concat strings simply by +'ing them, or by using the Join function of the strings package.

How do I get the type of a variable?

#include <typeinfo>

...
string s = typeid(YourClass).name()

asp.net mvc @Html.CheckBoxFor

Html.CheckBoxFor expects a Func<TModel, bool> as the first parameter. Therefore your lambda must return a bool, you are currently returning an instance of List<Checkboxes>:

model => model.EmploymentType

You need to iterate over the List<Checkboxes> to output each checkbox:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, 
              new { id = string.Format("employmentType_{0}", i) })
}

WCF - How to Increase Message Size Quota

I solve the problem ...as follows

    <bindings>
  <netTcpBinding>
    <binding name="ECMSBindingConfig" closeTimeout="00:10:00" openTimeout="00:10:00"
      sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
      maxReceivedMessageSize="2147483647" portSharingEnabled="true">
      <readerQuotas maxArrayLength="2147483647" maxNameTableCharCount="2147483647"
          maxStringContentLength="2147483647" maxDepth="2147483647"
          maxBytesPerRead="2147483647" />
      <security mode="None" />
    </binding>
  </netTcpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="ECMSServiceBehavior">
      <dataContractSerializer ignoreExtensionDataObject="true" maxItemsInObjectGraph="2147483647" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceTimeouts transactionTimeout="00:10:00" />
      <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="100"
        maxConcurrentInstances="100" />
    </behavior>
  </serviceBehaviors>
</behaviors>

Difference between static class and singleton pattern?

Main differences are:

  • Singleton has an instance/object while static class is a bunch of static methods
  • Singleton can be extended e.g. through an interface while static class can't be.
  • Singleton can be inherited which supports open/close principles in SOLID principles on the other hand static class can't be inherited and we need to make changes in itself.
  • Singleton object can be passed to methods while static class as it does not have instance can't be passed as parameters

Get page title with Selenium WebDriver using Java

You can do it easily by using JUnit or TestNG framework. Do the assertion as below:

String actualTitle = driver.getTitle();
String expectedTitle = "Title of Page";
assertEquals(expectedTitle,actualTitle);

OR,

assertTrue(driver.getTitle().contains("Title of Page"));

How to insert a newline in front of a pattern?

You can use perl one-liners much like you do with sed, with the advantage of full perl regular expression support (which is much more powerful than what you get with sed). There is also very little variation across *nix platforms - perl is generally perl. So you can stop worrying about how to make your particular system's version of sed do what you want.

In this case, you can do

perl -pe 's/(regex)/\n$1/'

-pe puts perl into a "execute and print" loop, much like sed's normal mode of operation.

' quotes everything else so the shell won't interfere

() surrounding the regex is a grouping operator. $1 on the right side of the substitution prints out whatever was matched inside these parens.

Finally, \n is a newline.

Regardless of whether you are using parentheses as a grouping operator, you have to escape any parentheses you are trying to match. So a regex to match the pattern you list above would be something like

\(\d\d\d\)\d\d\d-\d\d\d\d

\( or \) matches a literal paren, and \d matches a digit.

Better:

\(\d{3}\)\d{3}-\d{4}

I imagine you can figure out what the numbers in braces are doing.

Additionally, you can use delimiters other than / for your regex. So if you need to match / you won't need to escape it. Either of the below is equivalent to the regex at the beginning of my answer. In theory you can substitute any character for the standard /'s.

perl -pe 's#(regex)#\n$1#'
perl -pe 's{(regex)}{\n$1}'

A couple final thoughts.

using -ne instead of -pe acts similarly, but doesn't automatically print at the end. It can be handy if you want to print on your own. E.g., here's a grep-alike (m/foobar/ is a regex match):

perl -ne 'if (m/foobar/) {print}'

If you are finding dealing with newlines troublesome, and you want it to be magically handled for you, add -l. Not useful for the OP, who was working with newlines, though.

Bonus tip - if you have the pcre package installed, it comes with pcregrep, which uses full perl-compatible regexes.

Loop structure inside gnuplot?

Take a look also to the do { ... } command since gnuplot 4.6 as it is very powerful:

do for [t=0:50] {
  outfile = sprintf('animation/bessel%03.0f.png',t)
  set output outfile
  splot u*sin(v),u*cos(v),bessel(u,t/50.0) w pm3d ls 1
}

http://www.gnuplotting.org/gnuplot-4-6-do/

How to convert milliseconds into a readable date?

This is a solution. Later you can split by ":" and take the values of the array

 /**
 * Converts milliseconds to human readeable language separated by ":"
 * Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
 */
function dhm(t){
    var cd = 24 * 60 * 60 * 1000,
        ch = 60 * 60 * 1000,
        d = Math.floor(t / cd),
        h = '0' + Math.floor( (t - d * cd) / ch),
        m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return [d, h.substr(-2), m.substr(-2)].join(':');
}

//Example
var delay = 190980000;                   
var fullTime = dhm(delay);
console.log(fullTime);

Modifying a query string without reloading the page

Building off of Fabio's answer, I created two functions that will probably be useful for anyone stumbling upon this question. With these two functions, you can call insertParam() with a key and value as an argument. It will either add the URL parameter or, if a query param already exists with the same key, it will change that parameter to the new value:

//function to remove query params from a URL
function removeURLParameter(url, parameter) {
    //better to use l.search if you have a location/link object
    var urlparts= url.split('?');   
    if (urlparts.length>=2) {

        var prefix= encodeURIComponent(parameter)+'=';
        var pars= urlparts[1].split(/[&;]/g);

        //reverse iteration as may be destructive
        for (var i= pars.length; i-- > 0;) {    
            //idiom for string.startsWith
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
                pars.splice(i, 1);
            }
        }

        url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
        return url;
    } else {
        return url;
    }
}

//function to add/update query params
function insertParam(key, value) {
    if (history.pushState) {
        // var newurl = window.location.protocol + "//" + window.location.host + search.pathname + '?myNewUrlQuery=1';
        var currentUrlWithOutHash = window.location.origin + window.location.pathname + window.location.search;
        var hash = window.location.hash
        //remove any param for the same key
        var currentUrlWithOutHash = removeURLParameter(currentUrlWithOutHash, key);

        //figure out if we need to add the param with a ? or a &
        var queryStart;
        if(currentUrlWithOutHash.indexOf('?') !== -1){
            queryStart = '&';
        } else {
            queryStart = '?';
        }

        var newurl = currentUrlWithOutHash + queryStart + key + '=' + value + hash
        window.history.pushState({path:newurl},'',newurl);
    }
}

Relative path to absolute path in C#?

This worked for me.

//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat"; 
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);

How can I remove all text after a character in bash?

An example might have been useful, but if I understood you correctly, this would work:

echo "Hello: world" | cut -f1 -d":"

This will convert Hello: world into Hello.

How do I access my webcam in Python?

gstreamer can handle webcam input. If I remeber well, there are python bindings for it!

How to plot vectors in python using matplotlib

Thanks to everyone, each of your posts helped me a lot. rbierman code was pretty straight for my question, I have modified a bit and created a function to plot vectors from given arrays. I'd love to see any suggestions to improve it further.

import numpy as np
import matplotlib.pyplot as plt
def plotv(M):
    rows,cols = M.T.shape
    print(rows,cols)

    #Get absolute maxes for axis ranges to center origin
    #This is optional
    maxes = 1.1*np.amax(abs(M), axis = 0)
    colors = ['b','r','k']
    fig = plt.figure()
    fig.suptitle('Vectors', fontsize=10, fontweight='bold')

    ax = fig.add_subplot(111)
    fig.subplots_adjust(top=0.85)
    ax.set_title('Vector operations')

    ax.set_xlabel('x')
    ax.set_ylabel('y')

    for i,l in enumerate(range(0,cols)):
        # print(i)
        plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.2,head_length=0.1,zorder=3)

        ax.text(M[i,0],M[i,1], str(M[i]), style='italic',
            bbox={'facecolor':'red', 'alpha':0.5, 'pad':0.5})

    plt.plot(0,0,'ok') #<-- plot a black point at the origin
    # plt.axis('equal')  #<-- set the axes to the same scale
    plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
    plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits

    plt.grid(b=True, which='major') #<-- plot grid lines
    plt.show()

r = np.random.randint(4,size=[2,2])
print(r[0,:])
print(r[1,:])
r12 = np.add(r[0,:],r[1,:])
print(r12)
plotv(np.vstack((r,r12)))

Vector addition performed on random vectors

Converting a pointer into an integer

Use intptr_t and uintptr_t.

To ensure it is defined in a portable way, you can use code like this:

#if defined(__BORLANDC__)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
    typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
#else
    #include <stdint.h>
#endif

Just place that in some .h file and include wherever you need it.

Alternatively, you can download Microsoft’s version of the stdint.h file from here or use a portable one from here.

Sending mail from Python using SMTP

Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both.

Plot multiple lines (data series) each with unique color in R

If you would like a ggplot2 solution, you can do this if you can shape your data to this format (see example below)

# dummy data
set.seed(45)
df <- data.frame(x=rep(1:5, 9), val=sample(1:100, 45), 
                   variable=rep(paste0("category", 1:9), each=5))
# plot
ggplot(data = df, aes(x=x, y=val)) + geom_line(aes(colour=variable))

ggplot2_geom_line

Inserting HTML elements with JavaScript

Have a look at insertAdjacentHTML

var element = document.getElementById("one");
var newElement = '<div id="two">two</div>'
element.insertAdjacentHTML( 'afterend', newElement )
// new DOM structure: <div id="one">one</div><div id="two">two</div>

position is the position relative to the element you are inserting adjacent to:

'beforebegin' Before the element itself

'afterbegin' Just inside the element, before its first child

'beforeend' Just inside the element, after its last child

'afterend' After the element itself

How to check if a database exists in SQL Server?

From a Microsoft's script:

DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'

IF (EXISTS (SELECT name 
FROM master.dbo.sysdatabases 
WHERE ('[' + name + ']' = @dbname 
OR name = @dbname)))

-- code mine :)
PRINT 'db exists'

How to compare Boolean?

As long as checker is not null, you may use !checker as posted. This is possible since Java 5, because this Boolean variable will be autoboxed to the primivite boolean value.

getResources().getColor() is deprecated

You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).

ContextCompat.getColor(context, R.color.my_color)

As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.

You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:

compile 'com.android.support:support-v4:23.0.1'

Default background color of SVG root element

Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.

<svg style='stroke-width: 0px; background-color: blue;'> </svg>

I can't install intel HAXM

I probably tried all the solutions mentioned above but all in vain. To summarize, I did:

  • I enable the virtualization going to BIOS setting.

enter image description here

  • Uncheck Hyper-V option by going to Turn Windows features on or off.

enter image description here

Nothing worked for me. What worked for me: I noticed the issue "unable to run mksdcard sdk tool" when I try to download SDK platform.So after some research, I found some SDK tools such as mksdcard.exe require Microsoft Visual C++ runtime 2015-2019. So based on my system type,(for me it was x64) I downloaded the latest Microsoft Visual C++ Redistributable for Visual Studio 2019 from the link https://visualstudio.microsoft.com/downloads/. Detailed answer given here: Android Studio install failed - unable to run mksdcard sdk tool in Windows

enter image description here

enter image description here

After downloading and installing Visual C++ ,the error "unable to run mksdcard sdk tool" was fixed, also when I try to install HAXM after this, it was install successfully. Everything was fine. I was also able to create AVD now(which was also a problem when HAXM was not install).

jQuery: Uncheck other checkbox on one checked

I wanted to add an answer if the checkboxes are being generated in a loop. For example if your structure is like this (Assuming you are using server side constructs on your View, like a foreach loop):

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>
  </div>
</li>

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>
  </div>
</li>

Corresponding Jquery:

$(".list-group-item").each(function (i, li) {
  var currentli = $(li);
  $(currentli).find("#checkbox1").on('change', function () {
       $(currentli).find("#checkbox2").not(this).prop('checked',false);
  });

  $(currentli).find("#checkbox2").on('change', function () {
       $(currentli).find("#checkbox1").not(this).prop('checked', false);
  });
});

Working DEMO: https://jsfiddle.net/gr67qk20/

Java - How do I make a String array with values?

Another way to create an array with String apart from

String[] strings =  { "abc", "def", "hij", "xyz" };

is to use split. I find this more readable if there are lots of Strings.

String[] strings =  "abc,def,hij,xyz".split(",");

or the following is good if you are parsing lines of strings from another source.

String[] strings =  ("abc\n" +
                     "def\n" +
                     "hij\n" +
                     "xyz").split("\n");