Programs & Examples On #Windows 1252

Windows-1252 to UTF-8 encoding

How would you expect recode to know that a file is Windows-1252? In theory, I believe any file is a valid Windows-1252 file, as it maps every possible byte to a character.

Now there are certainly characteristics which would strongly suggest that it's UTF-8 - if it starts with the UTF-8 BOM, for example - but they wouldn't be definitive.

One option would be to detect whether it's actually a completely valid UTF-8 file first, I suppose... again, that would only be suggestive.

I'm not familiar with the recode tool itself, but you might want to see whether it's capable of recoding a file from and to the same encoding - if you do this with an invalid file (i.e. one which contains invalid UTF-8 byte sequences) it may well convert the invalid sequences into question marks or something similar. At that point you could detect that a file is valid UTF-8 by recoding it to UTF-8 and seeing whether the input and output are identical.

Alternatively, do this programmatically rather than using the recode utility - it would be quite straightforward in C#, for example.

Just to reiterate though: all of this is heuristic. If you really don't know the encoding of a file, nothing is going to tell you it with 100% accuracy.

How to make Google Fonts work in IE?

I tried all the options from above and they didn't work. Then I located the google font (Over the Rainbow) in my folder (new) and used IE conditional below and it worked perfect.

<!--[if IE]>
<style type="text/css">
    @font-face {
    font-family: "Over the Rainbow";
    src: url("../new/over.ttf");
    src: local("Over the Rainbow"), url("../new/over.ttf");
    }
</style>
<![endif]-->

I hope it will help

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

This is a local installation. You downloaded and built OpenSSL taking the default prefix, of you configured with ./config --prefix=/usr/local/ssl or ./config --openssldir=/usr/local/ssl.

You will use this if you use the OpenSSL in /usr/local/ssl/bin. That is, /usr/local/ssl/openssl.cnf will be used when you issue:

/usr/local/ssl/bin/openssl s_client -connect localhost:443 -tls1 -servername localhost

/usr/lib/ssl/openssl.cnf

This is where Ubuntu places openssl.cnf for the OpenSSL they provide.

You will use this if you use the OpenSSL in /usr/bin. That is, /usr/lib/ssl/openssl.cnf will be used when you issue:

openssl s_client -connect localhost:443 -tls1 -servername localhost

/etc/ssl/openssl.cnf

I don't know when this is used. The stuff in /etc/ssl is usually certificates and private keys, and it sometimes contains a copy of openssl.cnf. But I've never seen it used for anything.


Which is the main/correct one that I should use to make changes?

From the sounds of it, you should probably add the engine to /usr/lib/ssl/openssl.cnf. That ensures most "off the shelf" gear will use the new engine.

After you do that, add it to /usr/local/ssl/openssl.cnf also because copy/paste is easy.


Here's how to see which openssl.cnf directory is associated with a OpenSSL installation. The library and programs look for openssl.cnf in OPENSSLDIR. OPENSSLDIR is a configure option, and its set with --openssldir.

I'm on a MacBook with 3 different OpenSSL's (Apple's, MacPort's and the one I build):

# Apple    
$ /usr/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/System/Library/OpenSSL"

# MacPorts
$ /opt/local/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/opt/local/etc/openssl"

# My build of OpenSSL
$ openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/usr/local/ssl/darwin"

I have an Ubuntu system and I have installed openssl.

Just bike shedding, but be careful of Ubuntu's version of OpenSSL. It disables TLSv1.1 and TLSv1.2, so you will only have clients capable of older cipher suites; and you will not be able to use newer ciphers like AES/CTR (to replace RC4) and elliptic curve gear (like ECDHE_ECDSA_* and ECDHE_RSA_*). See Ubuntu 12.04 LTS: OpenSSL downlevel version is 1.0.0, and does not support TLS 1.2 in Launchpad.

EDIT: Ubuntu enabled TLS 1.1 and TLS 1.2 recently. See Comment 17 on the bug report.

Not equal string

With Equals() you can also use a Yoda condition:

if ( ! "-1".Equals(myString) )

How do I center a Bootstrap div with a 'spanX' class?

If anyone wants the true solution for centering BOTH images and text within a span using bootstrap row-fluid, here it is (how to implement this and explanation follows my example):

css

div.row-fluid [class*="span"] .center-in-span { 
   float: none; 
   margin: 0 auto; 
   text-align: center; 
   display: block; 
   width: auto; 
   height: auto;
}

html

<div class="row-fluid">
   <div class="span12">
      <img class="center-in-span" alt="MyExample" src="/path/to/example.jpg"/>
   </div>
</div>

<div class="row-fluid">
   <div class="span12">
      <p class="center-in-span">this is text</p>
   </div>
</div>

USAGE: To use this css to center an image within a span, simply apply the .center-in-span class to the img element, as shown above.

To use this css to center text within a span, simply apply the .center-in-span class to the p element, as shown above.

EXPLANATION: This css works because we are overriding specific bootstrap styling. The notable differences from the other answers that were posted are that the width and height are set to auto, so you don't have to used a fixed with (good for a dynamic webpage). also, the combination of setting the margin to auto, text-align:center and display:block, takes care of both images and paragraphs.

Let me know if this is thorough enough for easy implementation.

How to delete and recreate from scratch an existing EF Code First database

How about ..

static void Main(string[] args)
{
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ExampleContext>());  
    // C
    // o
    // d
    // i
    // n
    // g
}

I picked this up from Programming Entity Framework: Code First, Pg 28 First Edition.

How to read data from a zip file without having to unzip the entire file

In such case you will need to parse zip local header entries. Each file, stored in zip file, has preceding Local File Header entry, which (normally) contains enough information for decompression, Generally, you can make simple parsing of such entries in stream, select needed file, copy header + compressed file data to other file, and call unzip on that part (if you don't want to deal with the whole Zip decompression code or library).

Any way to clear python's IDLE window?

There does not appear to be a way to clear the IDLE 'shell' buffer.

How to create a listbox in HTML without allowing multiple selection?

Just use the size attribute:

<select name="sometext" size="5">
  <option>text1</option>
  <option>text2</option>
  <option>text3</option>
  <option>text4</option>
  <option>text5</option>
</select>

To clarify, adding the size attribute did not remove the multiple selection.

The single selection works because you removed the multiple="multiple" attribute.

Adding the size="5" attribute is still a good idea, it means that at least 5 lines must be displayed. See the full reference here

Matplotlib-Animation "No MovieWriters Available"

For fellow googlers using Anaconda, install the ffmpeg package:

conda install -c conda-forge ffmpeg

This works on Windows too.

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

Easiest way to copy a table from one database to another?

create table destination_customer like sakila.customer(Database_name.tablename), this will only copy the structure of the source table, for data also to get copied with the structure do this create table destination_customer as select * from sakila.customer

Animate change of view background color on Android

If you want color animation like this,

Enter image description here

this code will help you:

ValueAnimator anim = ValueAnimator.ofFloat(0, 1);   
anim.setDuration(2000);

float[] hsv;
int runColor;
int hue = 0;
hsv = new float[3]; // Transition color
hsv[1] = 1;
hsv[2] = 1;
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {

        hsv[0] = 360 * animation.getAnimatedFraction();

        runColor = Color.HSVToColor(hsv);
        yourView.setBackgroundColor(runColor);
    }
});

anim.setRepeatCount(Animation.INFINITE);

anim.start();

Is Unit Testing worth the effort?

thetalkingwalnut asks:

What are some good ways to convince the skeptical developers on the team of the value of Unit Testing?

Everyone here is going to pile on lots of reasons out of the blue why unit testing is good. However, I find that often the best way to convince someone of something is to listen to their argument and address it point by point. If you listen and help them verbalize their concerns, you can address each one and perhaps convert them to your point of view (or at the very least, leave them without a leg to stand on). Who knows? Perhaps they will convince you why unit tests aren't appropriate for your situation. Not likely, but possible. Perhaps if you post their arguments against unit tests, we can help identify the counterarguments.

It's important to listen to and understand both sides of the argument. If you try to adopt unit tests too zealously without regard to people's concerns, you'll end up with a religious war (and probably really worthless unit tests). If you adopt it slowly and start by applying it where you will see the most benefit for the least cost, you might be able to demonstrate the value of unit tests and have a better chance of convincing people. I realize this isn't as easy as it sounds - it usually requires some time and careful metrics to craft a convincing argument.

Unit tests are a tool, like any other, and should be applied in such a way that the benefits (catching bugs) outweigh the costs (the effort writing them). Don't use them if/where they don't make sense and remember that they are only part of your arsenal of tools (e.g. inspections, assertions, code analyzers, formal methods, etc). What I tell my developers is this:

  1. They can skip writing a test for a method if they have a good argument why it isn't necessary (e.g. too simple to be worth it or too difficult to be worth it) and how the method will be otherwise verified (e.g. inspection, assertions, formal methods, interactive/integration tests). They need to consider that some verifications like inspections and formal proofs are done at a point in time and then need to be repeated every time the production code changes, whereas unit tests and assertions can be used as regression tests (written once and executed repeatedly thereafter). Sometimes I agree with them, but more often I will debate about whether a method is really too simple or too difficult to unit test.

    • If a developer argues that a method seems too simple to fail, isn't it worth taking the 60 seconds necessary to write up a simple 5-line unit test for it? These 5 lines of code will run every night (you do nightly builds, right?) for the next year or more and will be worth the effort if even just once it happens to catch a problem that may have taken 15 minutes or longer to identify and debug. Besides, writing the easy unit tests drives up the count of unit tests, which makes the developer look good.

    • On the other hand, if a developer argues that a method seems too difficult to unit test (not worth the significant effort required), perhaps that is a good indication that the method needs to be divided up or refactored to test the easy parts. Usually, these are methods that rely on unusual resources like singletons, the current time, or external resources like a database result set. These methods usually need to be refactored into a method that gets the resource (e.g. calls getTime()) and a method that takes the resource as a argument (e.g. takes the timestamp as a parameter). I let them skip testing the method that retrieves the resource and they instead write a unit test for the method that now takes the resource as a argument. Usually, this makes writing the unit test much simpler and therefore worthwhile to write.

  2. The developer needs to draw a "line in the sand" in how comprehensive their unit tests should be. Later in development, whenever we find a bug, they should determine if more comprehensive unit tests would have caught the problem. If so and if such bugs crop up repeatedly, they need to move the "line" toward writing more comprehensive unit tests in the future (starting with adding or expanding the unit test for the current bug). They need to find the right balance.

Its important to realize the unit tests are not a silver bullet and there is such a thing as too much unit testing. At my workplace, whenever we do a lessons learned, I inevitably hear "we need to write more unit tests". Management nods in agreement because its been banged into their heads that "unit tests" == "good".

However, we need to understand the impact of "more unit tests". A developer can only write ~N lines of code a week and you need to figure out what percentage of that code should be unit test code vs production code. A lax workplace might have 10% of the code as unit tests and 90% of the code as production code, resulting in product with a lot of (albeit very buggy) features (think MS Word). On the other hand, a strict shop with 90% unit tests and 10% production code will have a rock solid product with very few features (think "vi"). You may never hear reports about the latter product crashing, but that likely has as much to do with the product not selling very well as much as it has to do with the quality of the code.

Worse yet, perhaps the only certainty in software development is that "change is inevitable". Assume the strict shop (90% unit tests/10% production code) creates a product that has exactly 2 features (assuming 5% of production code == 1 feature). If the customer comes along and changes 1 of the features, then that change trashes 50% of the code (45% of unit tests and 5% of the production code). The lax shop (10% unit tests/90% production code) has a product with 18 features, none of which work very well. Their customer completely revamps the requirements for 4 of their features. Even though the change is 4 times as large, only half as much of the code base gets trashed (~25% = ~4.4% unit tests + 20% of production code).

My point is that you have to communicate that you understand that balance between too little and too much unit testing - essentially that you've thought through both sides of the issue. If you can convince your peers and/or your management of that, you gain credibility and perhaps have a better chance of winning them over.

How to pause javascript code execution for 2 seconds

You can use setTimeout to do this

function myFunction() {
    // your code to run after the timeout
}

// stop for sometime if needed
setTimeout(myFunction, 5000);

There was no endpoint listening at (url) that could accept the message

I had this problem when I was trying to call a WCF service hosted in a new server from a windows application from my local. I was getting same error message and at end had this "No connection could be made because the target machine actively refused it 127.0.0.1:8888". I donot know whether I am wrong or correct but I feel whenever the server was getting request from my windows application it is routing to something else. So I did some reading and added below in Web.config of service host project. After that everything worked like a magic.

<system.net>
    <defaultProxy enabled="false">
    </defaultProxy>
</system.net>

How to add Class in <li> using wp_nav_menu() in Wordpress?

None of these responses really seem to answer the question. Here's something similar to what I'm utilizing on a site of mine by targeting a menu item by its title/name:

function add_class_to_menu_item($sorted_menu_objects, $args) {
    $theme_location = 'primary_menu';  // Name, ID, or Slug of the target menu location
    $target_menu_title = 'Link';  // Name/Title of the menu item you want to target
    $class_to_add = 'my_own_class';  // Class you want to add

    if ($args->theme_location == $theme_location) {
        foreach ($sorted_menu_objects as $key => $menu_object) {
            if ($menu_object->title == $target_menu_title) {
                $menu_object->classes[] = $class_to_add;
                break; // Optional.  Leave if you're only targeting one specific menu item
            }
        }
    }

    return $sorted_menu_objects;
}
add_filter('wp_nav_menu_objects', 'add_class_to_menu_item', 10, 2);

PostgreSQL Error: Relation already exists

You cannot create a table with a name that is identical to an existing table or view in the cluster. To modify an existing table, use ALTER TABLE (link), or to drop all data currently in the table and create an empty table with the desired schema, issue DROP TABLE before CREATE TABLE.

It could be that the sequence you are creating is the culprit. In PostgreSQL, sequences are implemented as a table with a particular set of columns. If you already have the sequence defined, you should probably skip creating it. Unfortunately, there's no equivalent in CREATE SEQUENCE to the IF NOT EXISTS construct available in CREATE TABLE. By the looks of it, you might be creating your schema unconditionally, anyways, so it's reasonable to use

DROP TABLE IF EXISTS csd_relationship;
DROP SEQUENCE IF EXISTS csd_relationship_csd_relationship_id_seq;

before the rest of your schema update; In case it isn't obvious, This will delete all of the data in the csd_relationship table, if there is any

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

Using $ docker inspect Incase the Image has no /bin/bash in the output, you can use command below: it worked for me perfectly

$ docker exec -it <container id> sh

How to start a Process as administrator mode in C#

You probably need to set your application as an x64 app.

The IIS Snap In only works in 64 bit and doesn't work in 32 bit, and a process spawned from a 32 bit app seems to work to be a 32 bit process and the same goes for 64 bit apps.

Look at: Start process as 64 bit

Date in mmm yyyy format in postgresql

SELECT TO_CHAR(NOW(), 'Mon YYYY');

Proper way to concatenate variable strings

Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):

{{ var1 + '-' + var2 + '-' + var3 }}

If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:

e.g. To concatenate our 3 vars, and get a sha512 hash:

{{ (var1 + var2 + var3) | hash('sha512') }}

Note: this works on Ansible 2.3. I haven't tested it on earlier versions.

Direct download from Google Drive using Google Drive API

If you just want to programmatically (as oppossed to giving the user a link to open in a browser) download a file through the Google Drive API, I would suggest using the downloadUrl of the file instead of the webContentLink, as documented here: https://developers.google.com/drive/web/manage-downloads

What are the undocumented features and limitations of the Windows FINDSTR command?

I'd like to report a bug regarding the section Source of data to search in the first answer when using en dash (–) or em dash (—) within the filename.

More specifically, if you are about to use the first option - filenames specified as arguments, the file won't be found. As soon as you use either option 2 - stdin via redirection or 3 - data stream from a pipe, findstr will find the file.

For example, this simple batch script:

echo off
chcp 1250 > nul
set INTEXTFILE1=filename with – dash.txt
set INTEXTFILE2=filename with — dash.txt

rem 3 way of findstr use with en dashed filename
echo.
echo Filename with en dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE1%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE1%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE1%" | findstr .
echo.
echo.
rem The same set of operations with em dashed filename
echo Filename with em dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE2%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE2%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE2%" | findstr .
echo.

pause

will print:

Filename with en dash:

  1. As argument
    FINDSTR: Cannot open filename with - dash.txt

  2. As stdin via redirection
    I am the file with an en dash.

  3. As datastream from a pipe
    I am the file with an en dash.

Filename with em dash:

  1. As argument
    FINDSTR: Cannot open filename with - dash.txt

  2. As stdin via redirection
    I am the file with an em dash.

  3. As datastream from a pipe
    I am the file with an em dash.

Hope it helps.

M.

How do I load an url in iframe with Jquery

$("#frame").click(function () { 
    this.src="http://www.google.com/";
});

Sometimes plain JavaScript is even cooler and faster than jQuery ;-)

How to create a simple proxy in C#?

The browser is connected to the proxy so the data that the proxy gets from the web server is just sent via the same connection that the browser initiated to the proxy.

Immutable vs Mutable types

A class is immutable if each object of that class has a fixed value upon instantiation that cannot SUBSEQUENTLY be changed

In another word change the entire value of that variable (name) or leave it alone.

Example:

my_string = "Hello world" 
my_string[0] = "h"
print my_string 

you expected this to work and print hello world but this will throw the following error:

Traceback (most recent call last):
File "test.py", line 4, in <module>
my_string[0] = "h"
TypeError: 'str' object does not support item assignment

The interpreter is saying : i can't change the first character of this string

you will have to change the whole string in order to make it works:

my_string = "Hello World" 
my_string = "hello world"
print my_string #hello world

check this table:

enter image description here

source

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

Mockito : how to verify method was called on an object created within a method?

Dependency Injection

If you inject the Bar instance, or a factory that is used for creating the Bar instance (or one of the other 483 ways of doing this), you'd have the access necessary to do perform the test.

Factory Example:

Given a Foo class written like this:

public class Foo {
  private BarFactory barFactory;

  public Foo(BarFactory factory) {
    this.barFactory = factory;
  }

  public void foo() {
    Bar bar = this.barFactory.createBar();
    bar.someMethod();
  }
}

in your test method you can inject a BarFactory like this:

@Test
public void testDoFoo() {
  Bar bar = mock(Bar.class);
  BarFactory myFactory = new BarFactory() {
    public Bar createBar() { return bar;}
  };

  Foo foo = new Foo(myFactory);
  foo.foo();

  verify(bar, times(1)).someMethod();
}

Bonus: This is an example of how TDD can drive the design of your code.

Numpy where function multiple conditions

The accepted answer explained the problem well enough. However, the more Numpythonic approach for applying multiple conditions is to use numpy logical functions. In this case, you can use np.logical_and:

np.where(np.logical_and(np.greater_equal(dists,r),np.greater_equal(dists,r + dr)))

How can I add comments in MySQL?

You can use single line comments:

-- this is a comment
# this is also a comment

Or a multiline comment:

/*
   multiline
   comment
*/

What does the KEY keyword mean?

KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

column_definition:
      data_type [NOT NULL | NULL] [DEFAULT default_value]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      ...

Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

How to find the files that are created in the last hour in unix

If the dir to search is srch_dir then either

$ find srch_dir -cmin -60 # change time

or

$ find srch_dir -mmin -60 # modification time

or

$ find srch_dir -amin -60 # access time

shows files created, modified or accessed in the last hour.

correction :ctime is for change node time (unsure though, please correct me )

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

How to modify WooCommerce cart, checkout pages (main theme portion)

WooCommerce has a number of options for modifying the cart, and checkout pages. Here are the three I'd recomend:

Use WooCommerce Conditional Tags

is_cart() and is_checkout() functions return true on their page. Example:

if ( is_cart() || is_checkout() ) {
    echo "This is the cart, or checkout page!";
}

Modify the template file

The main, cart template file is located at wp-content/themes/{current-theme}/woocommerce/cart/cart.php

The main, checkout template file is located at wp-content/themes/{current-theme}/woocommerce/checkout/form-checkout.php

To edit these, first copy them to your child theme.

Use wp-content/themes/{current-theme}/page-{slug}.php

page-{slug}.php is the second template that will be used, coming after manually assigned ones through the WP dashboard.

This is safer than my other solutions, because if you remove WooCommerce, but forget to remove this file, the code inside (that may rely on WooCommerce functions) won't break, because it's never called (unless of cause you have a page with slug {slug}).

For example:

  • wp-content/themes/{current-theme}/page-cart.php
  • wp-content/themes/{current-theme}/page-checkout.php

Convert all data frame character columns to factors

The easiest way would be to use the code given below. It would automate the whole process of converting all the variables as factors in a dataframe in R. it worked perfectly fine for me. food_cat here is the dataset which I am using. Change it to the one which you are working on.

    for(i in 1:ncol(food_cat)){

food_cat[,i] <- as.factor(food_cat[,i])

}

How do I delete an exported environment variable?

As mentioned in the above answers, unset GNUPLOT_DRIVER_DIR should work if you have used export to set the variable. If you have set it permanently in ~/.bashrc or ~/.zshrc then simply removing it from there will work.

How do I convert a Swift Array to a String?

In Swift 2.2 you may have to cast your array to NSArray to use componentsJoinedByString(",")

let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")

Linq: GroupBy, Sum and Count

I don't understand where the first "result with sample data" is coming from, but the problem in the console app is that you're using SelectMany to look at each item in each group.

I think you just want:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new ResultLine
            {
                ProductName = cl.First().Name,
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

The use of First() here to get the product name assumes that every product with the same product code has the same product name. As noted in comments, you could group by product name as well as product code, which will give the same results if the name is always the same for any given code, but apparently generates better SQL in EF.

I'd also suggest that you should change the Quantity and Price properties to be int and decimal types respectively - why use a string property for data which is clearly not textual?

$(document).on("click"... not working?

if this code does not work even under document ready, most probable you assigned a return false; somewhere in your js file to that button, if it is button try to change it to a ,span, anchor or div and test if it is working.

$(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
});

Tomcat 8 Maven Plugin for Java 8

Almost 2 years later....
This github project readme has a some clarity of configuration of the maven plugin and it seems, according to this apache github project, the plugin itself will materialise soon enough.

Android "hello world" pushnotification example

Update 2016:

GCM is being replaced with FCM

Update 2015:

Have a look at developers.android.com - Google replaced C2DM with GCM Demo Implementation / How To

Update 2014:

1) You need to check on the server what HTTP response you are getting from the Google servers. Make sure it is a 200 OK response, so you know the message was sent. If you get another response (302, etc) then the message is not being sent successfully.

2) You also need to check that the Registration ID you are using is correct. If you provide the wrong Registration ID (as a destination for the message - specifying the app, on a specific device) then the Google servers cannot successfully send it.

3) You also need to check that your app is successfully registering with the Google servers, to receive push notifications. If the registration fails, you will not receive messages.

First Answer 2014

Here is a good question you may should have a look at it: How to add a push notification in my own android app

Also here is a good blog with a really simple how to: http://blog.serverdensity.com/android-push-notifications-tutorial/

move column in pandas dataframe

I use Pokémon database as an example, the columns for my data base are

['Name', '#', 'Type 1', 'Type 2', 'Total', 'HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed', 'Generation', 'Legendary']

Here is the code:


import pandas as pd
    df = pd.read_html('https://gist.github.com/armgilles/194bcff35001e7eb53a2a8b441e8b2c6')[0] 
    cols = df.columns.to_list()
    cos_end= ["Name", "Total", "HP", "Defense"]

    for i, j in enumerate(cos_end, start=(len(cols)-len(cos_end))):
        cols.insert(i, cols.pop(cols.index(j)))
        print(cols)
        
    df = df.reindex(columns=cols)

    print(df)

How can I start pagenumbers, where the first section occurs in LaTex?

To suppress the page number on the first page, add \thispagestyle{empty} after the \maketitle command.

The second page of the document will then be numbered "2". If you want this page to be numbered "1", you can add \pagenumbering{arabic} after the \clearpage command, and this will reset the page number.

Here's a complete minimal example:

\documentclass[notitlepage]{article}

\title{My Report}
\author{My Name}

\begin{document}
\maketitle
\thispagestyle{empty}

\begin{abstract}
\ldots
\end{abstract}

\clearpage
\pagenumbering{arabic} 

\section{First Section}
\ldots

\end{document}

How can I rotate an HTML <div> 90 degrees?

We can add the following to a particular tag in CSS:

-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);

In case of half rotation change 90 to 45.

How to enable TLS 1.2 in Java 7

Add this parameter to JAVA_OPTS or to the command line in Maven: -Dhttps.protocols=TLSv1.2

How to access global variables

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

HTML / CSS How to add image icon to input type="button"?

This should do do what you want, assuming your button image is 16 by 16 pixels.

<input type="button" value="Add a new row" class="button-add" />
input.button-add {
    background-image: url(/images/buttons/add.png); /* 16px x 16px */
    background-color: transparent; /* make the button transparent */
    background-repeat: no-repeat;  /* make the background image appear only once */
    background-position: 0px 0px;  /* equivalent to 'top left' */
    border: none;           /* assuming we don't want any borders */
    cursor: pointer;        /* make the cursor like hovering over an <a> element */
    height: 16px;           /* make this the size of your image */
    padding-left: 16px;     /* make text start to the right of the image */
    vertical-align: middle; /* align the text vertically centered */
}

Example button:

example button

Update

If you happen to use Less, this mixin might come in handy.

.icon-button(@icon-url, @icon-size: 16px, @icon-inset: 10px, @border-color: #000, @background-color: transparent) {
    height: @icon-size * 2;
    padding-left: @icon-size + @icon-inset * 2;
    padding-right: @icon-inset;
    border: 1px solid @border-color;
    background: @background-color url(@icon-url) no-repeat @icon-inset center;
    cursor: pointer;
}

input.button-add {
    .icon-button("http://placehold.it/16x16", @background-color: #ff9900);
}

The above compiles into

input.button-add {
  height: 32px;
  padding-left: 36px;
  padding-right: 10px;
  border: 1px solid #000000;
  background: #ff9900 url("http://placehold.it/16x16") no-repeat 10px center;
  cursor: pointer;
}

JSFiddle

What "wmic bios get serialnumber" actually retrieves?

run cmd

Enter wmic baseboard get product,version,serialnumber

Press the enter key. The result you see under serial number column is your motherboard serial number

After installing with pip, "jupyter: command not found"

I compiled python3.7 from the source code, with the following command

./configure --prefix=/opt/python3.7.4 --with-ssl
make
make install

after pip3.7 install jupyter I found the executable is under /opt/python3.7.4/bin

check my answer here Missing sqlite3 after Python3 compile to get more detail comping python3.7 and pip under ubuntu14.04

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

In Windows 10 SQL Server 19 the solution is known.

Copy the following files:

  • libssl-1_1-x64.dll
  • libcrypto-1_1-x64.dll

from the folder

C:\Program Files\Microsoft SQL Server\MSSSQL15.MSSQLSERVER\PYTHON_SERVICES\Library\bin

to the folder

C:\Program Files\Microsoft SQL Server\MSSSQL15.MSSQLSERVER\PYTHON_SERVICES\DLLs

Then open a new DOS command shell prompt.

From https://docs.microsoft.com/en-us/sql/machine-learning/troubleshooting/known-issues-for-sql-server-machine-learning-services?view=sql-server-ver15#7-unable-to-install-python-packages-using-pip-after-installing-sql-server-2019-on-windows

Correct way to try/except using Python requests module?

Have a look at the Requests exception docs. In short:

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.

What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit).

You can either catch the base-class exception, which will handle all cases:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e:  # This is the correct syntax
    raise SystemExit(e)

Or you can catch them separately and do different things.

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
    # Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
    # Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
    # catastrophic error. bail.
    raise SystemExit(e)

As Christian pointed out:

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.

An example:

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

Will print:

404 Client Error: Not Found for url: http://www.google.com/nothere

How to parse freeform street/postal address out of text, and into components

No code? For shame!

Here is a simple JavaScript address parser. It's pretty awful for every single reason that Matt gives in his dissertation above (which I almost 100% agree with: addresses are complex types, and humans make mistakes; better to outsource and automate this - when you can afford to).

But rather than cry, I decided to try:

This code works OK for parsing most Esri results for findAddressCandidate and also with some other (reverse)geocoders that return single-line address where street/city/state are delimited by commas. You can extend if you want or write country-specific parsers. Or just use this as case study of how challenging this exercise can be or at how lousy I am at JavaScript. I admit I only spent about thirty mins on this (future iterations could add caches, zip validation, and state lookups as well as user location context), but it worked for my use case: End user sees form that parses geocode search response into 4 textboxes. If address parsing comes out wrong (which is rare unless source data was poor) it's no big deal - the user gets to verify and fix it! (But for automated solutions could either discard/ignore or flag as error so dev can either support the new format or fix source data.)

_x000D_
_x000D_
/* _x000D_
address assumptions:_x000D_
- US addresses only (probably want separate parser for different countries)_x000D_
- No country code expected._x000D_
- if last token is a number it is probably a postal code_x000D_
-- 5 digit number means more likely_x000D_
- if last token is a hyphenated string it might be a postal code_x000D_
-- if both sides are numeric, and in form #####-#### it is more likely_x000D_
- if city is supplied, state will also be supplied (city names not unique)_x000D_
- zip/postal code may be omitted even if has city & state_x000D_
- state may be two-char code or may be full state name._x000D_
- commas: _x000D_
-- last comma is usually city/state separator_x000D_
-- second-to-last comma is possibly street/city separator_x000D_
-- other commas are building-specific stuff that I don't care about right now._x000D_
- token count:_x000D_
-- because units, street names, and city names may contain spaces token count highly variable._x000D_
-- simplest address has at least two tokens: 714 OAK_x000D_
-- common simple address has at least four tokens: 714 S OAK ST_x000D_
-- common full (mailing) address has at least 5-7:_x000D_
--- 714 OAK, RUMTOWN, VA 59201_x000D_
--- 714 S OAK ST, RUMTOWN, VA 59201_x000D_
-- complex address may have a dozen or more:_x000D_
--- MAGICICIAN SUPPLY, LLC, UNIT 213A, MAGIC TOWN MALL, 13 MAGIC CIRCLE DRIVE, LAND OF MAGIC, MA 73122-3412_x000D_
*/_x000D_
_x000D_
var rawtext = $("textarea").val();_x000D_
var rawlist = rawtext.split("\n");_x000D_
_x000D_
function ParseAddressEsri(singleLineaddressString) {_x000D_
  var address = {_x000D_
    street: "",_x000D_
    city: "",_x000D_
    state: "",_x000D_
    postalCode: ""_x000D_
  };_x000D_
_x000D_
  // tokenize by space (retain commas in tokens)_x000D_
  var tokens = singleLineaddressString.split(/[\s]+/);_x000D_
  var tokenCount = tokens.length;_x000D_
  var lastToken = tokens.pop();_x000D_
  if (_x000D_
    // if numeric assume postal code (ignore length, for now)_x000D_
    !isNaN(lastToken) ||_x000D_
    // if hyphenated assume long zip code, ignore whether numeric, for now_x000D_
    lastToken.split("-").length - 1 === 1) {_x000D_
    address.postalCode = lastToken;_x000D_
    lastToken = tokens.pop();_x000D_
  }_x000D_
_x000D_
  if (lastToken && isNaN(lastToken)) {_x000D_
    if (address.postalCode.length && lastToken.length === 2) {_x000D_
      // assume state/province code ONLY if had postal code_x000D_
      // otherwise it could be a simple address like "714 S OAK ST"_x000D_
      // where "ST" for "street" looks like two-letter state code_x000D_
      // possibly this could be resolved with registry of known state codes, but meh. (and may collide anyway)_x000D_
      address.state = lastToken;_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
    if (address.state.length === 0) {_x000D_
      // check for special case: might have State name instead of State Code._x000D_
      var stateNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found separator, ignore stuff on left side_x000D_
          tokens.push(lastToken); // put it back_x000D_
          break;_x000D_
        } else {_x000D_
          stateNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.state = stateNameParts.join(' ');_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
  }_x000D_
_x000D_
  if (lastToken) {_x000D_
    // here is where it gets trickier:_x000D_
    if (address.state.length) {_x000D_
      // if there is a state, then assume there is also a city and street._x000D_
      // PROBLEM: city may be multiple words (spaces)_x000D_
      // but we can pretty safely assume next-from-last token is at least PART of the city name_x000D_
      // most cities are single-name. It would be very helpful if we knew more context, like_x000D_
      // the name of the city user is in. But ignore that for now._x000D_
      // ideally would have zip code service or lookup to give city name for the zip code._x000D_
      var cityNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // assumption / RULE: street and city must have comma delimiter_x000D_
      // addresses that do not follow this rule will be wrong only if city has space_x000D_
      // but don't care because Esri formats put comma before City_x000D_
      var streetNameParts = [];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found end of street address (may include building, etc. - don't care right now)_x000D_
          // add token back to end, but remove trailing comma (it did its job)_x000D_
          tokens.push(lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken);_x000D_
          streetNameParts = tokens;_x000D_
          break;_x000D_
        } else {_x000D_
          cityNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.city = cityNameParts.join(' ');_x000D_
      address.street = streetNameParts.join(' ');_x000D_
    } else {_x000D_
      // if there is NO state, then assume there is NO city also, just street! (easy)_x000D_
      // reasoning: city names are not very original (Portland, OR and Portland, ME) so if user wants city they need to store state also (but if you are only ever in Portlan, OR, you don't care about city/state)_x000D_
      // put last token back in list, then rejoin on space_x000D_
      tokens.push(lastToken);_x000D_
      address.street = tokens.join(' ');_x000D_
    }_x000D_
  }_x000D_
  // when parsing right-to-left hard to know if street only vs street + city/state_x000D_
  // hack fix for now is to shift stuff around._x000D_
  // assumption/requirement: will always have at least street part; you will never just get "city, state"  _x000D_
  // could possibly tweak this with options or more intelligent parsing&sniffing_x000D_
  if (!address.city && address.state) {_x000D_
    address.city = address.state;_x000D_
    address.state = '';_x000D_
  }_x000D_
  if (!address.street) {_x000D_
    address.street = address.city;_x000D_
    address.city = '';_x000D_
  }_x000D_
_x000D_
  return address;_x000D_
}_x000D_
_x000D_
// get list of objects with discrete address properties_x000D_
var addresses = rawlist_x000D_
  .filter(function(o) {_x000D_
    return o.length > 0_x000D_
  })_x000D_
  .map(ParseAddressEsri);_x000D_
$("#output").text(JSON.stringify(addresses));_x000D_
console.log(addresses);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
13212 E SPRAGUE AVE, FAIR VALLEY, MD 99201_x000D_
1005 N Gravenstein Highway, Sebastopol CA 95472_x000D_
A. P. Croll &amp; Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947_x000D_
11522 Shawnee Road, Greenwood, DE 19950_x000D_
144 Kings Highway, S.W. Dover, DE 19901_x000D_
Intergrated Const. Services 2 Penns Way Suite 405, New Castle, DE 19720_x000D_
Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958_x000D_
Nichols Excavation 2742 Pulaski Hwy, Newark, DE 19711_x000D_
2284 Bryn Zion Road, Smyrna, DE 19904_x000D_
VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21_x000D_
580 North Dupont Highway, Dover, DE 19901_x000D_
P.O. Box 778, Dover, DE 19903_x000D_
714 S OAK ST_x000D_
714 S OAK ST, RUM TOWN, VA, 99201_x000D_
3142 E SPRAGUE AVE, WHISKEY VALLEY, WA 99281_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
</textarea>_x000D_
<div id="output">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

I was getting this error. Turns out it only happened when I completely cleaned the RN caches (quite elaborate process) and then created a release build.

If I cleaned the caches, created a debug build and then a release build, everything worked. Bit worrying but works.

Note: My clean command is...

rm -r android/build ; rm -r android/app/src/release/res ; rm -r android/app/build/intermediates ; watchman watch-del-all ; rm -rf $TMPDIR/react-* ; npm start -- --reset-cache

Get user input from textarea

I think you should not use spaces between the [(ngModel)] the = and the str. Then you should use a button or something like this with a click function and in this function you can use the values of your inputfields.

<input id="str" [(ngModel)]="str"/>
<button (click)="sendValues()">Send</button>

and in your component file

str: string;
sendValues(): void {
//do sth with the str e.g. console.log(this.str);
}

Hope I can help you.

How can apply multiple background color to one div

Sorry for misunderstanding, from what I understood you want your DIV to have three different colors with different heights. This is the output of my code:

output,

If this is what you want try this code:

_x000D_
_x000D_
div {_x000D_
    height: 100px;_x000D_
    width:400px;_x000D_
    position: relative;_x000D_
}_x000D_
.c {_x000D_
    background: blue; /* Old browsers */_x000D_
}_x000D_
_x000D_
.c:after{_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width:20%;_x000D_
    left:0;_x000D_
    height:110%;_x000D_
    background: yellow;_x000D_
}_x000D_
.c:before{_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width:40%;_x000D_
    left:60%;_x000D_
    height:140%;_x000D_
    background: green;_x000D_
}
_x000D_
<div class="c"></div>
_x000D_
_x000D_
_x000D_

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

How to make Toolbar transparent?

https://stackoverflow.com/a/37672153/2914140 helped me.

I made this layout for an activity:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    >

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/transparent" <- Add transparent color in AppBarLayout.
        android:theme="@style/AppTheme.AppBarOverlay"
        >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize"
            android:theme="@style/ToolbarTheme"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:theme="@style/ToolbarTheme"
            />

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        <- Remove app:layout_behavior=...
        />

</android.support.design.widget.CoordinatorLayout>

If this doesn't work, in onCreate() of the activity write (where toolbar is @+id/toolbar):

toolbar.background.alpha = 0

If you want to set a semi-transparent color (like #30ff00ff), then set toolbar.setBackgroundColor(color). Or even set a background color of AppBarLayout.

In my case styles of AppBarLayout and Toolbar didn't play role.

Detect IF hovering over element with jQuery

You can filter your elment from all hovered elements. Problematic code:

element.filter(':hover')

Save code:

jQuery(':hover').filter(element)

To return boolean:

jQuery(':hover').filter(element).length===0

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

You haven't put the shared library in a location where the loader can find it. look inside the /usr/local/opencv and /usr/local/opencv2 folders and see if either of them contains any shared libraries (files beginning in lib and usually ending in .so). when you find them, create a file called /etc/ld.so.conf.d/opencv.conf and write to it the paths to the folders where the libraries are stored, one per line.

for example, if the libraries were stored under /usr/local/opencv/libopencv_core.so.2.4 then I would write this to my opencv.conf file:

/usr/local/opencv/

Then run

sudo ldconfig -v

If you can't find the libraries, try running

sudo updatedb && locate libopencv_core.so.2.4

in a shell. You don't need to run updatedb if you've rebooted since compiling OpenCV.

References:

About shared libraries on Linux: http://www.eyrie.org/~eagle/notes/rpath.html

About adding the OpenCV shared libraries: http://opencv.willowgarage.com/wiki/InstallGuide_Linux

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

Creating a simple configuration file and parser in C++

As others have pointed out, it will probably be less work to make use of an existing configuration-file parser library rather than re-invent the wheel.

For example, if you decide to use the Config4Cpp library (which I maintain), then your configuration file syntax will be slightly different (put double quotes around values and terminate assignment statements with a semicolon) as shown in the example below:

# File: someFile.cfg
url = "http://mysite.com";
file = "main.exe";
true_false = "true";

The following program parses the above configuration file, copies the desired values into variables and prints them:

#include <config4cpp/Configuration.h>
#include <iostream>
using namespace config4cpp;
using namespace std;

int main(int argc, char ** argv)
{
    Configuration *  cfg = Configuration::create();
    const char *     scope = "";
    const char *     configFile = "someFile.cfg";
    const char *     url;
    const char *     file;
    bool             true_false;

    try {
        cfg->parse(configFile);
        url        = cfg->lookupString(scope, "url");
        file       = cfg->lookupString(scope, "file");
        true_false = cfg->lookupBoolean(scope, "true_false");
    } catch(const ConfigurationException & ex) {
        cerr << ex.c_str() << endl;
        cfg->destroy();
        return 1;
    }
    cout << "url=" << url << "; file=" << file
         << "; true_false=" << true_false
         << endl;
    cfg->destroy();
    return 0;
}

The Config4Cpp website provides comprehensive documentation, but reading just Chapters 2 and 3 of the "Getting Started Guide" should be more than sufficient for your needs.

jQuery If DIV Doesn't Have Class "x"

When you are checking if an element has or does not have a class, make sure you didn't accidentally put a dot in the class name:

<div class="className"></div>

$('div').hasClass('className');
$('div').hasClass('.className'); #will not work!!!!

After a long time of staring at my code I realized I had done this. A little typo like this took me an hour to figure out what I had done wrong. Check your code!

Bootstrap4 adding scrollbar to div

Use the overflow-y: scroll property on the element that contains the elements.

The overflow-y property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.

Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:

<ul class="nav nav-pills nav-stacked" style="height: 250px; overflow-y: scroll;">
  <li class="nav-item">
    <a class="nav-link active" href="#">Active</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" href="#">Disabled</a>
  </li>
</ul>

When should I use "this" in a class?

There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.

Imagine this:

public class Hello {
    private String foo;

    // Some 10k lines of codes

    private String getStringFromSomewhere() {
        // ....
    }

    // More codes

    public class World {
        private String bar;

        // Another 10k lines of codes

        public void doSomething() {
            // More codes
            foo = "FOO";
            // More codes
            String s = getStringFromSomewhere();
            // More codes
            bar = s;
        }
    }
}

This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.

You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.

Compare it to this:

public void doSomething() {
    // More codes
    Hello.this.foo = "FOO";
    // More codes
    String s = Hello.this.getStringFromSomewhere();
    // More codes
    this.bar = s;
}
  1. You know foo is a variable declared in outer class Hello.
  2. You know getStringFromSomewhere() is a method declared in outer class as well.
  3. You know that bar belongs to World class, and s is a local variable declared in that method.

Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.

Find control by name from Windows Forms controls

Use Control.ControlCollection.Find.

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

EDIT for asker:

Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
    tbxs[0].Text = "Found!";
}

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Get GPS location via a service in Android

All these answers doesn't work from M - to - Android"O" - 8, Due to Dozer mode that restrict the service - whatever service or any background operation that requires discrete things in background would be no longer able to run.

So the approach would be listening to the system FusedLocationApiClient through BroadCastReciever that always listening the location and work even in Doze mode.

Posting the link would be pointless, please search FusedLocation with Broadcast receiver.

Thanks

How to set delay in vbscript

Work this end (XP).

Create a new file, call it test.vbs. Put this in it.

WScript.Sleep 1000
MsgBox "TEST"

Run it, notice the delay before the message box is shown.

Note, the number is in Milliseconds, so 1000 is 1 second.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

There are two uses for RAISE_APPLICATION_ERROR. The first is to replace generic Oracle exception messages with our own, more meaningful messages. The second is to create exception conditions of our own, when Oracle would not throw them.

The following procedure illustrates both usages. It enforces a business rule that new employees cannot be hired in the future. It also overrides two Oracle exceptions. One is DUP_VAL_ON_INDEX, which is thrown by a unique key on EMP(ENAME). The other is a a user-defined exception thrown when the foreign key between EMP(MGR) and EMP(EMPNO) is violated (because a manager must be an existing employee).

create or replace procedure new_emp
    ( p_name in emp.ename%type
      , p_sal in emp.sal%type
      , p_job in emp.job%type
      , p_dept in emp.deptno%type
      , p_mgr in emp.mgr%type 
      , p_hired in emp.hiredate%type := sysdate )
is
    invalid_manager exception;
    PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
    dummy varchar2(1);
begin
    -- check hiredate is valid
    if trunc(p_hired) > trunc(sysdate) 
    then
        raise_application_error
            (-20000
             , 'NEW_EMP::hiredate cannot be in the future'); 
    end if;

    insert into emp
        ( ename
          , sal
          , job
          , deptno
          , mgr 
          , hiredate )
    values      
        ( p_name
          , p_sal
          , p_job
          , p_dept
          , p_mgr 
          , trunc(p_hired) );
exception
    when dup_val_on_index then
        raise_application_error
            (-20001
             , 'NEW_EMP::employee called '||p_name||' already exists'
             , true); 
    when invalid_manager then
        raise_application_error
            (-20002
             , 'NEW_EMP::'||p_mgr ||' is not a valid manager'); 

end;
/

How it looks:

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1); END;

*
ERROR at line 1:
ORA-20000: NEW_EMP::hiredate cannot be in the future
ORA-06512: at "APC.NEW_EMP", line 16
ORA-06512: at line 1

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate); END;

*
ERROR at line 1:
ORA-20002: NEW_EMP::8888 is not a valid manager
ORA-06512: at "APC.NEW_EMP", line 42
ORA-06512: at line 1


SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)

PL/SQL procedure successfully completed.

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate); END;

*
ERROR at line 1:
ORA-20001: NEW_EMP::employee called DUGGAN already exists
ORA-06512: at "APC.NEW_EMP", line 37
ORA-00001: unique constraint (APC.EMP_UK) violated
ORA-06512: at line 1

Note the different output from the two calls to RAISE_APPLICATION_ERROR in the EXCEPTIONS block. Setting the optional third argument to TRUE means RAISE_APPLICATION_ERROR includes the triggering exception in the stack, which can be useful for diagnosis.

There is more useful information in the PL/SQL User's Guide.

how to stop a loop arduino

Matti Virkkunen said it right, there's no "decent" way of stopping the loop. Nonetheless, by looking at your code and making several assumptions, I imagine you're trying to output a signal with a given frequency, but you want to be able to stop it.

If that's the case, there are several solutions:

  1. If you want to generate the signal with the input of a button you could do the following

    int speakerOut = A0;
    int buttonPin = 13;
    
    void setup() {
        pinMode(speakerOut, OUTPUT);
        pinMode(buttonPin, INPUT_PULLUP);
    }
    
    int a = 0;
    
    void loop() {
        if(digitalRead(buttonPin) == LOW) {
            a ++;
            Serial.println(a);
            analogWrite(speakerOut, NULL);
    
            if(a > 50 && a < 300) {
                analogWrite(speakerOut, 200);
            }
    
            if(a <= 49) {
                analogWrite(speakerOut, NULL);
            }
    
            if(a >= 300 && a <= 2499) {
                analogWrite(speakerOut, NULL);
            }
        }
    }
    

    In this case we're using a button pin as an INPUT_PULLUP. You can read the Arduino reference for more information about this topic, but in a nutshell this configuration sets an internal pullup resistor, this way you can just have your button connected to ground, with no need of external resistors. Note: This will invert the levels of the button, LOW will be pressed and HIGH will be released.

  2. The other option would be using one of the built-ins hardware timers to get a function called periodically with interruptions. I won't go in depth be here's a great description of what it is and how to use it.

PHP ternary operator vs null coalescing operator

The major difference is that

  1. Ternary Operator expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE but on the other hand Null Coalescing Operator expression (expr1) ?? (expr2) evaluates to expr1 if expr1 is not NULL

  2. Ternary Operator expr1 ?: expr3 emit a notice if the left-hand side value (expr1) does not exist but on the other hand Null Coalescing Operator (expr1) ?? (expr2) In particular, does not emit a notice if the left-hand side value (expr1) does not exist, just like isset().

  3. TernaryOperator is left associative

    ((true ? 'true' : false) ? 't' : 'f');
    

    Null Coalescing Operator is right associative

    ($a ?? ($b ?? $c));
    

Now lets explain the difference between by example :

Ternary Operator (?:)

$x='';
$value=($x)?:'default';
var_dump($value);

// The above is identical to this if/else statement
if($x){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Null Coalescing Operator (??)

$value=($x)??'default';
var_dump($value);

// The above is identical to this if/else statement
if(isset($x)){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Here is the table that explain the difference and similarity between '??' and ?:

enter image description here

Special Note : null coalescing operator and ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; and return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued.

What is the correct XPath for choosing attributes that contain "foo"?

Have you tried something like:

//a[contains(@prop, "Foo")]

I've never used the contains function before but suspect that it should work as advertised...

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

Highlight all occurrence of a selected word?

First ensure that hlsearch is enabled by issuing the following command

:set hlsearch

You can also add this to your .vimrc file as set

set hlsearch

now when you use the quick search mechanism in command mode or a regular search command, all results will be highlighted. To move forward between results, press 'n' to move backwards press 'N'

In normal mode, to perform a quick search for the word under the cursor and to jump to the next occurrence in one command press '*', you can also search for the word under the cursor and move to the previous occurrence by pressing '#'

In normal mode, quick search can also be invoked with the

/searchterm<Enter>

to remove highlights on ocuurences use, I have bound this to a shortcut in my .vimrc

:nohl

Is there a way to @Autowire a bean that requires constructor arguments?

I like Zakaria's answer, but if you're in a project where your team doesn't want to use that approach, and you're stuck trying to construct something with a String, integer, float, or primative type from a property file into the constructor, then you can use Spring's @Value annotation on the parameter in the constructor.

For example, I had an issue where I was trying to pull a string property into my constructor for a class annotated with @Service. My approach works for @Service, but I think this approach should work with any spring java class, if it has an annotation (such as @Service, @Component, etc.) which indicate that Spring will be the one constructing instances of the class.

Let's say in some yaml file (or whatever configuration you're using), you have something like this:

some:
    custom:
        envProperty: "property-for-dev-environment"

and you've got a constructor:

@Service // I think this should work for @Component, or any annotation saying Spring is the one calling the constructor.
class MyClass {
...
    MyClass(String property){
    ...
    }
...
}

This won't run as Spring won't be able to find the string envProperty. So, this is one way you can get that value:

class MyDynamoTable
import org.springframework.beans.factory.annotation.Value;
...
    MyDynamoTable(@Value("${some.custom.envProperty}) String property){
    ...
    }
...

In the above constructor, Spring will call the class and know to use the String "property-for-dev-environment" pulled from my yaml configuration when calling it.

NOTE: this I believe @Value annotation is for strings, intergers, and I believe primative types. If you're trying to pass custom classes (beans), then approaches in answers defined above work.

Check if Variable is Empty - Angular 2

if( myVariable ) 
{ 
    //mayVariable is not : 
    //null 
    //undefined 
    //NaN 
    //empty string ("") 
    //0 
    //false 
}

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

1) create a Global function (best in a module so that you only need to declare once)

Imports System.Runtime.InteropServices                 ' required imports
Public intInputBoxCancel as integer                    ' public variable

Public Function StrPtr(ByVal obj As Object) As Integer
    Dim Handle As GCHandle = GCHandle.Alloc(obj, GCHandleType.Pinned)
    Dim intReturn As Integer = Handle.AddrOfPinnedObject.ToInt32
    Handle.Free()
    Return intReturn
End Function

2) in the form load event put this (to make the variable intInputBoxCancel = cancel event)

intInputBoxCancel = StrPtr(String.Empty)    

3) now, you can use anywhere in your form (or project if StrPtr is declared global in module)

dim ans as string = inputbox("prompt")         ' default data up to you
if StrPtr(ans) = intInputBoxCancel then
   ' cancel was clicked
else
   ' ok was clicked (blank input box will still be shown here)
endif

How to save Excel Workbook to Desktop regardless of user?

I think this is the most reliable way to get the desktop path which isn't always the same as the username.

MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")

JDBC ODBC Driver Connection

As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have

  • an implementation of ODBC itself, and
  • an appropriate ODBC driver for the target database (ACE/Jet, a.k.a. "Access")

So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).

There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see

Manipulating an Access database from Java without ODBC

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

Convert one date format into another in PHP

Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.

class dateTranslator {

 public static function translate($date, $lang) {
      $divider = '';

      if (empty($date)){
           return null;   
      }
      if (strpos($date, '-') !== false) {
           $divider = '-';
      } else if (strpos($date, '/') !== false) {
           $divider = '/';
      }
      //spanish format DD/MM/YYYY hh:mm
      if (strcmp($lang, 'es') == 0) {

           $type = explode($divider, $date)[0];
           if (strlen($type) == 4) {
                $date = self::reverseDate($date,$divider);
           } 
           if (strcmp($divider, '-') == 0) {
                $date = str_replace("-", "/", $date);
           }
      //english format YYYY-MM-DD hh:mm
      } else {

           $type = explode($divider, $date)[0];
           if (strlen($type) == 2) {

                $date = self::reverseDate($date,$divider);
           } 
           if (strcmp($divider, '/') == 0) {
                $date = str_replace("/", "-", $date);

           }   
      }
      return $date;
 }

 public static function reverseDate($date) {
      $date2 = explode(' ', $date);
      if (count($date2) == 2) {
           $date = implode("-", array_reverse(preg_split("/\D/", $date2[0]))) . ' ' . $date2[1];
      } else {
           $date = implode("-", array_reverse(preg_split("/\D/", $date)));
      }

      return $date;
 }

USE

dateTranslator::translate($date, 'en')

Display last git commit comment

I just found out a workaround with shell by retrieving the previous command.

Press Ctrl-R to bring up reverse search command:

reverse-i-search

Then start typing git commit -m, this will add this as search command, and this brings the previous git commit with its message:

reverse-i-search`git commit -m`: git commit -m "message"

Enter. That's it!

(tested in Ubuntu shell)

FFmpeg: How to split video efficiently?

Here's a useful script, it helps you split automatically: A script for splitting videos using ffmpeg

#!/bin/bash
 
# Written by Alexis Bezverkhyy <[email protected]> in 2011
# This is free and unencumbered software released into the public domain.
# For more information, please refer to <http://unlicense.org/>
 
function usage {
        echo "Usage : ffsplit.sh input.file chunk-duration [output-filename-format]"
        echo -e "\t - input file may be any kind of file reconginzed by ffmpeg"
        echo -e "\t - chunk duration must be in seconds"
        echo -e "\t - output filename format must be printf-like, for example myvideo-part-%04d.avi"
        echo -e "\t - if no output filename format is given, it will be computed\
 automatically from input filename"
}
 
IN_FILE="$1"
OUT_FILE_FORMAT="$3"
typeset -i CHUNK_LEN
CHUNK_LEN="$2"
 
DURATION_HMS=$(ffmpeg -i "$IN_FILE" 2>&1 | grep Duration | cut -f 4 -d ' ')
DURATION_H=$(echo "$DURATION_HMS" | cut -d ':' -f 1)
DURATION_M=$(echo "$DURATION_HMS" | cut -d ':' -f 2)
DURATION_S=$(echo "$DURATION_HMS" | cut -d ':' -f 3 | cut -d '.' -f 1)
let "DURATION = ( DURATION_H * 60 + DURATION_M ) * 60 + DURATION_S"
 
if [ "$DURATION" = '0' ] ; then
        echo "Invalid input video"
        usage
        exit 1
fi
 
if [ "$CHUNK_LEN" = "0" ] ; then
        echo "Invalid chunk size"
        usage
        exit 2
fi
 
if [ -z "$OUT_FILE_FORMAT" ] ; then
        FILE_EXT=$(echo "$IN_FILE" | sed 's/^.*\.\([a-zA-Z0-9]\+\)$/\1/')
        FILE_NAME=$(echo "$IN_FILE" | sed 's/^\(.*\)\.[a-zA-Z0-9]\+$/\1/')
        OUT_FILE_FORMAT="${FILE_NAME}-%03d.${FILE_EXT}"
        echo "Using default output file format : $OUT_FILE_FORMAT"
fi
 
N='1'
OFFSET='0'
let 'N_FILES = DURATION / CHUNK_LEN + 1'
 
while [ "$OFFSET" -lt "$DURATION" ] ; do
        OUT_FILE=$(printf "$OUT_FILE_FORMAT" "$N")
        echo "writing $OUT_FILE ($N/$N_FILES)..."
        ffmpeg -i "$IN_FILE" -vcodec copy -acodec copy -ss "$OFFSET" -t "$CHUNK_LEN" "$OUT_FILE"
        let "N = N + 1"
        let "OFFSET = OFFSET + CHUNK_LEN"
done

Running npm command within Visual Studio Code

I installed npm after Visual studio code, closed all visual studio instances and opened again and it started working.

Executing Javascript code "on the spot" in Chrome?

I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.

right align an image using CSS HTML

To make the image move right:

float: right;

To make the text not wrapped:

clear: right;

For best practice, put the css code in your stylesheets file. Once you add more code, it will look messy and hard to edit.

How to compute the sum and average of elements in an array?

You can also use lodash, _.sum(array) and _.mean(array) in Math part (also have other convenient stuff).

_.sum([4, 2, 8, 6]);
// => 20
_.mean([4, 2, 8, 6]);
// => 5

How to detect if a string contains special characters?

Assuming SQL Server:

e.g. if you class special characters as anything NOT alphanumeric:

DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'

IF (@MyString LIKE '%[^a-zA-Z0-9]%')
    PRINT 'Contains "special" characters'
ELSE
    PRINT 'Does not contain "special" characters'

Just add to other characters you don't class as special, inside the square brackets

Select a row from html table and send values onclick of a button

check http://jsfiddle.net/Z22NU/12/

function fnselect(){

    alert($("tr.selected td:first" ).html());
}

How to read and write INI file with Python3?

There are some problems I found when used configparser such as - I got an error when I tryed to get value from param:

destination=\my-server\backup$%USERNAME%

It was because parser can't get this value with special character '%'. And then I wrote a parser for reading ini files based on 're' module:

import re

# read from ini file.
def ini_read(ini_file, key):
    value = None
    with open(ini_file, 'r') as f:
        for line in f:
            match = re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I)
            if match:
                value = match.group()
                value = re.sub(r'^ *' + key + ' *= *', '', value)
                break
    return value


# read value for a key 'destination' from 'c:/myconfig.ini'
my_value_1 = ini_read('c:/myconfig.ini', 'destination')

# read value for a key 'create_destination_folder' from 'c:/myconfig.ini'
my_value_2 = ini_read('c:/myconfig.ini', 'create_destination_folder')


# write to an ini file.
def ini_write(ini_file, key, value, add_new=False):
    line_number = 0
    match_found = False
    with open(ini_file, 'r') as f:
        lines = f.read().splitlines()
    for line in lines:
        if re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I):
            match_found = True
            break
        line_number += 1
    if match_found:
        lines[line_number] = key + ' = ' + value
        with open(ini_file, 'w') as f:
            for line in lines:
                f.write(line + '\n')
        return True
    elif add_new:
        with open(ini_file, 'a') as f:
            f.write(key + ' = ' + value)
        return True
    return False


# change a value for a key 'destination'.
ini_write('my_config.ini', 'destination', '//server/backups$/%USERNAME%')

# change a value for a key 'create_destination_folder'
ini_write('my_config.ini', 'create_destination_folder', 'True')

# to add a new key, we need to use 'add_new=True' option.
ini_write('my_config.ini', 'extra_new_param', 'True', True)

Ascending and Descending Number Order in java

You could take the ascending array and output in reverse order, so replace the second for statement with:

for(int i = arr.length - 1; i >= 0; i--) {
    ...
}

If you have Apache's commons-lang on the classpath, it has a method ArrayUtils.reverse(int[]) that you can use.

By the way, you probably don't want to sort it in every cycle of the for loop.

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Change the database.php file from

$db['default']['dbdriver'] = 'mysql';

to

$db['default']['dbdriver'] = 'mysqli';

How do I download code using SVN/Tortoise from Google Code?

  • Download the svn binaries
  • unpack them somewhere and add the bin folder to your PATH environment variable
  • open a command line console (cmd.exe)
  • enter than "svn checkout ...." command there
    • make sure to first cd to the place where you want to download (i.e checkout) the projects' code.

Event when window.location.href changes

popstate event:

The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)

So, listening to popstate event and sending a popstate event when using history.pushState() should be enough to take action on href change:

window.addEventListener('popstate', listener);

const pushUrl = (href) => {
  history.pushState({}, '', href);
  window.dispatchEvent(new Event('popstate'));
};

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

How do I check if an integer is even or odd?

As some people have posted, there are numerous ways to do this. According to this website, the fastest way is the modulus operator:

if (x % 2 == 0)
               total += 1; //even number
        else
               total -= 1; //odd number

However, here is some other code that was bench marked by the author which ran slower than the common modulus operation above:

if ((x & 1) == 0)
               total += 1; //even number
        else
               total -= 1; //odd number

System.Math.DivRem((long)x, (long)2, out outvalue);
        if ( outvalue == 0)
               total += 1; //even number
        else
               total -= 1; //odd number

if (((x / 2) * 2) == x)
               total += 1; //even number
        else
               total -= 1; //odd number

if (((x >> 1) << 1) == x)
               total += 1; //even number
        else
               total -= 1; //odd number

        while (index > 1)
               index -= 2;
        if (index == 0)
               total += 1; //even number
        else
               total -= 1; //odd number

tempstr = x.ToString();
        index = tempstr.Length - 1;
        //this assumes base 10
        if (tempstr[index] == '0' || tempstr[index] == '2' || tempstr[index] == '4' || tempstr[index] == '6' || tempstr[index] == '8')
               total += 1; //even number
        else
               total -= 1; //odd number

How many people even knew of the Math.System.DivRem method or why would they use it??

Get a Div Value in JQuery

your div looks like this:

<div id="someId">Some Value</div>

With jquery:

   <script type="text/javascript">
     $(function(){
         var text = $('#someId').html(); 
         //or
         var text = $('#someId').text();
       };
  </script> 

How to get current date & time in MySQL?

Even though there are many accepted answers, I think this way is also possible:

Create your 'servers' table as following :

CREATE TABLE `servers`
(
      id int(11) NOT NULL PRIMARY KEY auto_increment,
      server_name varchar(45) NOT NULL,
      online_status varchar(45) NOT NULL,
      _exchange varchar(45) NOT NULL, 
      disk_space varchar(45) NOT NULL,
      network_shares varchar(45) NOT NULL,
      date_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
);

And your INSERT statement should be :

INSERT INTO servers (server_name, online_status, _exchange, disk_space, network_shares)
VALUES('m1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE');

My Environment:

Core i3 Windows Laptop with 4GB RAM, and I did the above example on MySQL Workbench 6.2 (Version 6.2.5.0 Build 397 64 Bits)

How to empty the message in a text area with jquery?

$('#message').html('');

You can use this method too. Because everything between the open and close tag of textarea is html code.

Android Device not recognized by adb

It may sound silly but in my case the USB cable was too long (even if good quality). It worked with my tablet but not with the phone. To check this, if you run on Linux run lsusb to make sure that your device is at least officially connect to the usb port.

How to return an array from an AJAX call?

Use JSON to transfer data types (arrays and objects) between client and server.

In PHP:

In JavaScript:

PHP:

echo json_encode($id_numbers);

JavaScript:

id_numbers = JSON.parse(msg);

As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.

id_numbers = new Array();
$.ajax({
    url:"Example.php",
    type:"POST",
    success:function(msg){
        id_numbers = msg;
    },
    dataType:"json"
});

'No JUnit tests found' in Eclipse

The solution was, after making a backup of the src/test folder, removing it from the filesystem, then creating it again.

That's after I did the "Remove from build path" hint and it screwed the folders when opening the project in STS 4.

MongoDB "root" user

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

Something like this:

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

] } )

Update for 2.6+

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

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

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

Update for 3.0+

Use db.createUser as db.addUser was removed.

Update for 3.0.7+

root no longer has the limitations stated above.

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

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

How to set a value for a span using jQuery

The solution that work for me is the following:

$("#spanId").text("text to show");

Facebook how to check if user has liked page and show content?

There is an article here that describes your problem

http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/

    <fb:visible-to-connection>
       Fans will see this content.
       <fb:else>
           Non-fans will see this content.
       </fb:else>
    </fb:visible-to-connection>

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

Your http is being blocked by a firewall from F5 Networks called Application Security Manager (ASM). It produces messages like:

Please consult with your administrator.
Your support ID is: xxxxxxxxxxxx

So your application is passing some data that for some reason ASM detects as a threat. Give the support id to you network engineer to learn the specific reason.

What does the NS prefix mean?

The original code for the Cocoa frameworks came from the NeXTSTEP libraries Foundation and AppKit (those names are still used by Apple's Cocoa frameworks), and the NextStep engineers chose to prefix their symbols with NS.

Because Objective-C is an extension of C and thus doesn't have namespaces like in C++, symbols must be prefixed with a unique prefix so that they don't collide. This is particularly important for symbols defined in a framework.

If you are writing an application, such that your code is only likely ever to use your symbols, you don't have to worry about this. But if you're writing a framework or library for others' use, you should also prefix your symbols with a unique prefix. CocoaDev has a page where many developers in the Cocoa community have listed their "chosen" prefixes. You may also find this SO discussion helpful.

Valid values for android:fontFamily and what they map to?

Available fonts (as of Oreo)

Preview of all fonts

The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.

For code sleuths: fonts.xml is the definitive and ever-expanding list of Android fonts.


Using these fonts

Set the android:fontFamily and android:textStyle attributes, e.g.

<!-- Roboto Bold -->
<TextView
    android:fontFamily="sans-serif"
    android:textStyle="bold" />

to the desired values from this table:

Font                     | android:fontFamily          | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin              | sans-serif-thin             |
Roboto Light             | sans-serif-light            |
Roboto Regular           | sans-serif                  |
Roboto Bold              | sans-serif                  | bold
Roboto Medium            | sans-serif-medium           |
Roboto Black             | sans-serif-black            |
Roboto Condensed Light   | sans-serif-condensed-light  |
Roboto Condensed Regular | sans-serif-condensed        |
Roboto Condensed Medium  | sans-serif-condensed-medium |
Roboto Condensed Bold    | sans-serif-condensed        | bold
Noto Serif               | serif                       |
Noto Serif Bold          | serif                       | bold
Droid Sans Mono          | monospace                   |
Cutive Mono              | serif-monospace             |
Coming Soon              | casual                      |
Dancing Script           | cursive                     |
Dancing Script Bold      | cursive                     | bold
Carrois Gothic SC        | sans-serif-smallcaps        |

(Noto Sans is a fallback font; you can't specify it directly)

Note: this table is derived from fonts.xml. Each font's family name and style is listed in fonts.xml, e.g.

<family name="serif-monospace">
    <font weight="400" style="normal">CutiveMono.ttf</font>
</family>

serif-monospace is thus the font family, and normal is the style.


Compatibility

Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:

  • Ice Cream Sandwich: Roboto regular, bold, italic, and bold italic
  • Jelly Bean: Roboto light, light italic, condensed, condensed bold, condensed italic, and condensed bold italic
  • Jelly Bean MR1: Roboto thin and thin italic
  • Lollipop:
    • Roboto medium, medium italic, black, and black italic
    • Noto Serif regular, bold, italic, bold italic
    • Cutive Mono
    • Coming Soon
    • Dancing Script
    • Carrois Gothic SC
    • Noto Sans
  • Oreo MR1: Roboto condensed medium

Check if a PHP cookie exists and if not set its value

Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

Source

GROUP BY and COUNT in PostgreSQL

I think you just need COUNT(DISTINCT post_id) FROM votes.

See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.

EDIT: Corrected my careless mistake per Erwin's comment.

Use StringFormat to add a string to a WPF XAML binding

Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:

<TextBlock>
  <Run Text="Temperature is "/>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>  
</TextBlock>

<!-- displays: 0°C (32°F)-->
<TextBlock>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>
  <Run Text=" ("/>
  <Run Text="{Binding Fahrenheit}"/>
  <Run Text="°F)"/>
</TextBlock>

How to use breakpoints in Eclipse

Put breakpoints - double click on the margin. Run > Debug > Yes (if dialog appears), then use commands from Run menu or shortcuts - F5, F6, F7, F8.

Hashing a dictionary?

Answers from this thread with the highest upvotes didn't work for me as their hashing functions give different results on different machines due to PYTHOPYTHONHASHSEED.

I adjusted all the hints from this thread and came up with a solution that works for me.

import collections
import hashlib
import json


def simplify_object(o):
    if isinstance(o, dict):
        ordered_dict = collections.OrderedDict(sorted(o.items()))
        for k, v in ordered_dict.items():
            v = simplify_object(v)
            ordered_dict[str(k)] = v
        o = ordered_dict
    elif isinstance(o, (list, tuple, set)):
        o = [simplify_object(el) for el in o]
    else:
        o = str(o).strip()
    return o


def make_hash(o):
    o = simplify_object(o)
    bytes_val = json.dumps(o, sort_keys=True, ensure_ascii=True, default=str)
    hash_val = hashlib.sha1(bytes_val.encode()).hexdigest()
    return hash_val

How to Set Active Tab in jQuery Ui

just trigger a click, it's work for me:

$("#tabX").trigger("click");

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

For Vb.Net Framework 4.0, U can use:

Alert("your message here", Boolean)

The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.

How to save data in an android app

In onCreate:

SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);

    String mySetting = sharedPref.getString("mySetting", null);

In onDestroy or equivalent:

SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("mySetting", "Hello Android");
    editor.commit();

Java 8 method references: provide a Supplier capable of supplying a parameterized result

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.

Best TCP port number range for internal applications

Short answer: use an unassigned user port

Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.

The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.

You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.

The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.

The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.

Android - Back button in the title bar

For kotlin :

   override fun onOptionsItemSelected(item: MenuItem): Boolean {
        onBackPressed();
        return true;
    }

Copy filtered data to another sheet using VBA

Best way of doing it

Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.

  Sub selectVisibleRange()

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
    Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")

    DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
    DuplicateRecords.Cells(1, 1).PasteSpecial


    End Sub

How to install Anaconda on RaspBerry Pi 3 Model B

Installing Miniconda on Raspberry Pi and adding Python 3.5 / 3.6

Skip the first section if you have already installed Miniconda successfully.

Installation of Miniconda on Raspberry Pi

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh

Accept the license agreement with yes

When asked, change the install location: /home/pi/miniconda3

Do you wish the installer to prepend the Miniconda3 install location to PATH in your /root/.bashrc ? yes

Now add the install path to the PATH variable:

sudo nano /home/pi/.bashrc

Go to the end of the file .bashrc and add the following line:

export PATH="/home/pi/miniconda3/bin:$PATH"

Save the file and exit.

To test if the installation was successful, open a new terminal and enter

conda

If you see a list with commands you are ready to go.

But how can you use Python versions greater than 3.4 ?


Adding Python 3.5 / 3.6 to Miniconda on Raspberry Pi

After the installation of Miniconda I could not yet install Python versions higher than Python 3.4, but i needed Python 3.5. Here is the solution which worked for me on my Raspberry Pi 4:

First i added the Berryconda package manager by jjhelmus (kind of an up-to-date version of the armv7l version of Miniconda):

conda config --add channels rpi

Only now I was able to install Python 3.5 or 3.6 without the need for compiling it myself:

conda install python=3.5
conda install python=3.6

Afterwards I was able to create environments with the added Python version, e.g. with Python 3.5:

conda create --name py35 python=3.5

The new environment "py35" can now be activated:

source activate py35

Using Python 3.7 on Raspberry Pi

Currently Jonathan Helmus, who is the developer of berryconda, is working on adding Python 3.7 support, if you want to see if there is an update or if you want to support him, have a look at this pull request. (update 20200623) berryconda is now inactive, This project is no longer active, no recipe will be updated and no packages will be added to the rpi channel. If you need to run Python 3.7 on your Pi right now, you can do so without Miniconda. Check if you are running the latest version of Raspbian OS called Buster. Buster ships with Python 3.7 preinstalled (source), so simply run your program with the following command:

Python3.7 app-that-needs-python37.py

I hope this solution will work for you too!

How to change screen resolution of Raspberry Pi

Default Rpi resolution is : 1366x768 if i'm not mistaken.

You can change it though.

You will find all the information about it in this link.

http://elinux.org/RPiconfig

Search "hdmi mode" on that page.

Hope it helps.

What are best practices for REST nested resources?

I've tried both design strategies - nested and non-nested endpoints. I've found that:

  1. if the nested resource has a primary key and you don't have its parent primary key, the nested structure requires you to get it, even though the system doesn't actually require it.

  2. nested endpoints typically require redundant endpoints. In other words, you will more often than not, need the additional /employees endpoint so you can get a list of employees across departments. If you have /employees, what exactly does /companies/departments/employees buy you?

  3. nesting endpoints don't evolve as nicely. E.g. you might not need to search for employees now but you might later and if you have a nested structure, you have no choice but to add another endpoint. With a non-nested design, you just add more parameters, which is simpler.

  4. sometimes a resource could have multiple types of parents. Resulting in multiple endpoints all returning the same resource.

  5. redundant endpoints makes the docs harder to write and also makes the api harder to learn.

In short, the non-nested design seems to allow a more flexible and simpler endpoint schema.

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

Regular expression [Any number]

You can use the following function to find the biggest [number] in any string.

It returns the value of the biggest [number] as an Integer.

var biggestNumber = function(str) {
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;

    while ((match = pattern.exec(str)) !== null) {
        if (match.index === pattern.lastIndex) {
            pattern.lastIndex++;
        }
        match[1] = parseInt(match[1]);
        if(biggest < match[1]) {
            biggest = match[1];
        }
    }
    return biggest;
}

DEMO

The following demo calculates the biggest number in your textarea every time you click the button.

It allows you to play around with the textarea and re-test the function with a different text.

_x000D_
_x000D_
var biggestNumber = function(str) {_x000D_
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;_x000D_
_x000D_
    while ((match = pattern.exec(str)) !== null) {_x000D_
        if (match.index === pattern.lastIndex) {_x000D_
            pattern.lastIndex++;_x000D_
        }_x000D_
        match[1] = parseInt(match[1]);_x000D_
        if(biggest < match[1]) {_x000D_
            biggest = match[1];_x000D_
        }_x000D_
    }_x000D_
    return biggest;_x000D_
}_x000D_
_x000D_
document.getElementById("myButton").addEventListener("click", function() {_x000D_
    alert(biggestNumber(document.getElementById("myTextArea").value));_x000D_
});
_x000D_
<div>_x000D_
    <textarea rows="6" cols="50" id="myTextArea">_x000D_
this is a test [1] also this [2] is a test_x000D_
and again [18] this is a test. _x000D_
items[14].items[29].firstname too is a test!_x000D_
items[4].firstname too is a test!_x000D_
    </textarea>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
   <button id="myButton">Try me</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

How to automatically reload a page after a given period of inactivity

I have built a complete javascript solution as well that does not require jquery. Might be able to turn it into a plugin. I use it for fluid auto-refreshing, but it looks like it could help you here.

JSFiddle AutoRefresh

// Refresh Rate is how often you want to refresh the page 
// bassed off the user inactivity. 
var refresh_rate = 200; //<-- In seconds, change to your needs
var last_user_action = 0;
var has_focus = false;
var lost_focus_count = 0;
// If the user loses focus on the browser to many times 
// we want to refresh anyway even if they are typing. 
// This is so we don't get the browser locked into 
// a state where the refresh never happens.    
var focus_margin = 10; 

// Reset the Timer on users last action
function reset() {
    last_user_action = 0;
    console.log("Reset");
}

function windowHasFocus() {
    has_focus = true;
}

function windowLostFocus() {
    has_focus = false;
    lost_focus_count++;
    console.log(lost_focus_count + " <~ Lost Focus");
}

// Count Down that executes ever second
setInterval(function () {
    last_user_action++;
    refreshCheck();
}, 1000);

// The code that checks if the window needs to reload
function refreshCheck() {
    var focus = window.onfocus;
    if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
        window.location.reload(); // If this is called no reset is needed
        reset(); // We want to reset just to make sure the location reload is not called.
    }

}
window.addEventListener("focus", windowHasFocus, false);
window.addEventListener("blur", windowLostFocus, false);
window.addEventListener("click", reset, false);
window.addEventListener("mousemove", reset, false);
window.addEventListener("keypress", reset, false);
window.addEventListener("scroll", reset, false);
document.addEventListener("touchMove", reset, false);
document.addEventListener("touchEnd", reset, false);

PyTorch: How to get the shape of a Tensor as a list of int

For PyTorch v1.0 and possibly above:

>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])

# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>

# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>

You can cast any torch.Size object to a native Python list:

>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>

In PyTorch v0.3 and 0.4:

Simply list(var.size()), e.g.:

>>> import torch
>>> from torch.autograd import Variable
>>> from torch import IntTensor
>>> var = Variable(IntTensor([[1,0],[0,1]]))

>>> var
Variable containing:
 1  0
 0  1
[torch.IntTensor of size 2x2]

>>> var.size()
torch.Size([2, 2])

>>> list(var.size())
[2, 2]

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

For me it was happening in VS2017 and VS2019. It stopped happening after I selected the option "Suppressed JIT optimization on module load".

enter image description here

php random x digit number

you people really likes to complicate things :)

the real problem is that the OP wants to, probably, add that to the end of some really big number. if not, there is no need I can think of for that to be required. as left zeros in any number is just, well, left zeroes.

so, just append the larger portion of that number as a math sum, not string.

e.g.

$x = "102384129" . complex_3_digit_random_string();

simply becomes

$x = 102384129000 + rand(0, 999);

done.

Calling javascript function in iframe

Use:

document.getElementById("resultFrame").contentWindow.Reset();

to access the Reset function in the iframe

document.getElementById("resultFrame") will get the iframe in your code, and contentWindow will get the window object in the iframe. Once you have the child window, you can refer to javascript in that context.

Also see HERE in particular the answer from bobince.

How to inject Javascript in WebBrowser control?

You can always use a "DocumentStream" or "DocumentText" property. For working with HTML documents I recommend a HTML Agility Pack.

How SQL query result insert in temp table?

You can use select ... into ... to create and populate a temp table and then query the temp table to return the result.

select *
into #TempTable
from YourTable

select *
from #TempTable

How to declare a global variable in React?

Maybe it's using a sledge-hammer to crack a nut, but using environment variables (with Dotenv https://www.npmjs.com/package/dotenv) you can also provide values throughout your React app. And that without any overhead code where they are used.

I came here because I found that some of the variables defined in my env files where static throughout the different envs, so I searched for a way to move them out of the env files. But honestly I don't like any of the alternatives I found here. I don't want to set up and use a context everytime I need those values.

I am not experienced when it comes to environments, so please, if there is a downside to this approach, let me know.

Failed to create provisioning profile

Change Deployment Target to newer version and then solved

Oracle DateTime in Where Clause?

Yes: TIME_CREATED contains a date and a time. Use TRUNC to strip the time:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')

UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED if it exists. An alternative approach without this problem is this:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy') 
      AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1

Codeigniter's `where` and `or_where`

$this->db->where('(a = 1 or a = 2)');

Missing MVC template in Visual Studio 2015

Visual studio 2015 does not show MVC project template if you select .Net 4.0 or below. Select .Net 4.5 or above, and you will be able to see MVC project.

This is what showed when you select .NET Framework 4:

enter image description here

and this when you select .NET Framework 4.5:

enter image description here

However, make sure you have installed web developers tools. To do so, go to Add / remove programs -> Visual 2015 -> Modify --> Web developer tools : Check and proceed with the installation.

How to replace multiple substrings of a string?

You can use the pandas library and the replace function which supports both exact matches as well as regex replacements. For example:

df = pd.DataFrame({'text': ['Billy is going to visit Rome in November', 'I was born in 10/10/2010', 'I will be there at 20:00']})

to_replace=['Billy','Rome','January|February|March|April|May|June|July|August|September|October|November|December', '\d{2}:\d{2}', '\d{2}/\d{2}/\d{4}']
replace_with=['name','city','month','time', 'date']

print(df.text.replace(to_replace, replace_with, regex=True))

And the modified text is:

0    name is going to visit city in month
1                      I was born in date
2                 I will be there at time

You can find an example here. Notice that the replacements on the text are done with the order they appear in the lists

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Simply adding it to the root folder works after a fashion, but I've found that if I need to change the favicon, it can take days to update... even a cache refresh doesn't do the trick.

Getting time span between two times in C#?

Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]

If tsStart > tsFinish Then

                            ' Take Hours difference and adjust accordingly
                            tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)

                            ' Add Minutes to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))


                            ' Add Seonds to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))

How to change content on hover

This exact example is present on mozilla developers page:

::after

As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);, and store it in data-descr="ADD" attribute of your HTML tag (which is nice because you can e.g translate it)

CSS content can only be usef with :after and :before pseudo-elements, so you can try to proceed with something like this:

.item a p.new-label span:after{
  position: relative;
  content: 'NEW'
}
.item:hover a p.new-label span:after {
  content: 'ADD';
}

The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.

Run / Open VSCode from Mac Terminal

For Mac users:

One thing that made the accepted answer not work for me is that I didn't drag the vs code package into the applications folder

So you need to drag it to the applications folder then you run the command inside vs code (shown below) as per the official document

  • Launch VS Code.
  • Open the Command Palette (??P) and type 'shell command' to find the Shell Command: Install 'code' command in PATH command.

Filter Excel pivot table using VBA

In Excel 2007 onwards, you can use the much simpler code using a more precise reference:

dim pvt as PivotTable
dim pvtField as PivotField

set pvt = ActiveSheet.PivotTables("PivotTable2")
set pvtField = pvt.PivotFields("SavedFamilyCode")

pvtField.PivotFilters.Add xlCaptionEquals, Value1:= "K123223"

Vagrant ssh authentication failure

Problem I was getting the ssh authentication errors, on a box I provisioned. The original was working ok.

The problem for me was I was missing a private key in .vagrant/machines/default/virtualbox/private_key. I copied the private key from the same relative location from the original box and Viola!

How to find out the server IP address (using JavaScript) that the browser is connected to?

Fairly certain this cannot be done. However you could use your preferred server-side language to print the server's IP to the client, and then use it however you like. For example, in PHP:

<script type="text/javascript">
    var ip = "<?php echo $_SERVER['SERVER_ADDR']; ?>";
    alert(ip);
</script>

This depends on your server's security setup though - some may block this.

How do I capture response of form.submit

First of all we will need serializeObject();

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

then you make a basic post and get response

$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) {
if(data){
//do true 
}
else
{
//do false
}

});

Ternary operators in JavaScript without an "else"

First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

This means several things:

  • use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
  • only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
  • each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)

In short - the 'correct' use of a ternary expression is

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

 condition && (x = true);

This is still an expression and might therefore not pass validation, so an even better approach would be

 void(condition && x = true);

The last one will pass validation.

But then again, if the expected value is a boolean, just use the result of the condition expression itself

var x = (condition); // var x = (foo == "bar");

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

Right pad a string with variable number of spaces

Based on KMier's answer, addresses the comment that this method poses a problem when the field to be padded is not a field, but the outcome of a (possibly complicated) function; the entire function has to be repeated.

Also, this allows for padding a field to the maximum length of its contents.

WITH
cte AS (
  SELECT 'foo' AS value_to_be_padded
  UNION SELECT 'foobar'
),
cte_max AS (
  SELECT MAX(LEN(value_to_be_padded)) AS max_len
)
SELECT
  CONCAT(SPACE(max_len - LEN(value_to_be_padded)), value_to_be_padded AS left_padded,
  CONCAT(value_to_be_padded, SPACE(max_len - LEN(value_to_be_padded)) AS right_padded;

How can I find out the current route in Rails?

Should you also need the parameters:

current_fullpath = request.env['ORIGINAL_FULLPATH']
# If you are browsing http://example.com/my/test/path?param_n=N 
# then current_fullpath will point to "/my/test/path?param_n=N"

And remember you can always call <%= debug request.env %> in a view to see all the available options.

TypeError: $(...).DataTable is not a function

if some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict(true) from the second version will return the globally scoped jQuery variables to those of the first version.

Sometimes it could be issue with older version (or not stable) of JQuery files

Solution use $.noConflict();

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.js" type="text/javascript"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
    $('#myTable').DataTable();
});
// Code that uses other library's $ can follow here.
</script>

Find nearest latitude/longitude with an SQL query

In extreme cases this approach fails, but for performance, I've skipped the trigonometry and simply calculated the diagonal squared.

Where should I put the CSS and Javascript code in an HTML webpage?

Regarding <link /> and <style />, you don't have a choice, they must be in the <head /> section (see one and two).

Regarding <script /> it can appear both in <head /> and <body /> (see three), usually it is best practice to put them in the <head /> since they are not really "content" (where "content" is what the user sees on screen), they are more something which "works on" the "content".

W3C's HTML4 specification FTW!

How many times does each value appear in a column?

The quickest way would be with a pivot table. Make sure your column of data has a header row, highlight the data and the header, from the insert ribbon select pivot table and then drag your header from the pivot table fields list to the row labels and to the values boxes.

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

How do these new categories relate to the existing rvalue and lvalue categories?

A C++03 lvalue is still a C++11 lvalue, whereas a C++03 rvalue is called a prvalue in C++11.

Hive Alter table change Column Name

alter table table_name change old_col_name new_col_name new_col_type;

Here is the example

hive> alter table test change userVisit userVisit2 STRING;      
    OK
    Time taken: 0.26 seconds
    hive> describe test;                                      
    OK
    uservisit2              string                                      
    category                string                                      
    uuid                    string                                      
    Time taken: 0.213 seconds, Fetched: 3 row(s)

Inheritance with base class constructor with parameters

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

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

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

use this code solve the problem:

string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "Uploadfile\\" + fileName;
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, (int)fs.Length);
fs.Close();
Response.ContentType = "application/x-unknown/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName;+ "\"");
try
{
    if (bt != null)
    {
        System.IO.MemoryStream stream1 = new System.IO.MemoryStream(bt, true);
        stream1.Write(bt, 0, bt.Length);
        Response.BinaryWrite(bt);
        //Response.OutputStream.Write(bt, 0, (int)stream1.Length);
        Response.Flush();
        // Response.End();
    }
}
catch (Exception ex)
{
    Response.Write(ex.Message);
    throw ex;
}
finally
{
    Response.End();
}

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

Omitting the second expression when using the if-else shorthand

This is also an option:

x==2 && dosomething();

dosomething() will only be called if x==2 is evaluated to true. This is called Short-circuiting.

It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:

if(x==2) dosomething();

You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)

How to make picturebox transparent?

One fast solution is set image property for image1 and set backgroundimage property to imag2, the only inconvenience is that you have the two images inside the picture box, but you can change background properties to tile, streched, etc. Make sure that backcolor be transparent. Hope this helps

Error "initializer element is not constant" when trying to initialize variable with const

gcc 7.4.0 can not compile codes as below:

#include <stdio.h>
const char * const str1 = "str1";
const char * str2 = str1;
int main() {
    printf("%s - %s\n", str1, str2);
    return 0;
}

constchar.c:3:21: error: initializer element is not constant const char * str2 = str1;

In fact, a "const char *" string is not a compile-time constant, so it can't be an initializer. But a "const char * const" string is a compile-time constant, it should be able to be an initializer. I think this is a small drawback of CLang.

A function name is of course a compile-time constant.So this code works:

void func(void)
{
    printf("func\n");
}
typedef void (*func_type)(void);
func_type f = func;
int main() {
    f();
    return 0;
}

How to use .htaccess in WAMP Server?

click: WAMP icon->Apache->Apache modules->chose rewrite_module

and do restart for all services.

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

I just found the case to get SHA-1 in Android Studio:

  1. Click on your package and choose New -> Google -> Google Maps Activity
  2. Android Studio redirects you to google_maps_api.xml

And you will see all you need to get google_maps_key.

Image

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

Just get column names from hive table

you could also do show columns in $table or see Hive, how do I retrieve all the database's tables columns for access to hive metadata

How do I use namespaces with TypeScript external modules?

Candy Cup Analogy

Version 1: A cup for every candy

Let's say you wrote some code like this:

Mod1.ts

export namespace A {
    export class Twix { ... }
}

Mod2.ts

export namespace A {
    export class PeanutButterCup { ... }
}

Mod3.ts

export namespace A {
     export class KitKat { ... }
}

You've created this setup: enter image description here

Each module (sheet of paper) gets its own cup named A. This is useless - you're not actually organizing your candy here, you're just adding an additional step (taking it out of the cup) between you and the treats.


Version 2: One cup in the global scope

If you weren't using modules, you might write code like this (note the lack of export declarations):

global1.ts

namespace A {
    export class Twix { ... }
}

global2.ts

namespace A {
    export class PeanutButterCup { ... }
}

global3.ts

namespace A {
     export class KitKat { ... }
}

This code creates a merged namespace A in the global scope:

enter image description here

This setup is useful, but doesn't apply in the case of modules (because modules don't pollute the global scope).


Version 3: Going cupless

Going back to the original example, the cups A, A, and A aren't doing you any favors. Instead, you could write the code as:

Mod1.ts

export class Twix { ... }

Mod2.ts

export class PeanutButterCup { ... }

Mod3.ts

export class KitKat { ... }

to create a picture that looks like this:

enter image description here

Much better!

Now, if you're still thinking about how much you really want to use namespace with your modules, read on...


These Aren't the Concepts You're Looking For

We need to go back to the origins of why namespaces exist in the first place and examine whether those reasons make sense for external modules.

Organization: Namespaces are handy for grouping together logically-related objects and types. For example, in C#, you're going to find all the collection types in System.Collections. By organizing our types into hierarchical namespaces, we provide a good "discovery" experience for users of those types.

Name Conflicts: Namespaces are important to avoid naming collisions. For example, you might have My.Application.Customer.AddForm and My.Application.Order.AddForm -- two types with the same name, but a different namespace. In a language where all identifiers exist in the same root scope and all assemblies load all types, it's critical to have everything be in a namespace.

Do those reasons make sense in external modules?

Organization: External modules are already present in a file system, necessarily. We have to resolve them by path and filename, so there's a logical organization scheme for us to use. We can have a /collections/generic/ folder with a list module in it.

Name Conflicts: This doesn't apply at all in external modules. Within a module, there's no plausible reason to have two objects with the same name. From the consumption side, the consumer of any given module gets to pick the name that they will use to refer to the module, so accidental naming conflicts are impossible.


Even if you don't believe that those reasons are adequately addressed by how modules work, the "solution" of trying to use namespaces in external modules doesn't even work.

Boxes in Boxes in Boxes

A story:

Your friend Bob calls you up. "I have a great new organization scheme in my house", he says, "come check it out!". Neat, let's go see what Bob has come up with.

You start in the kitchen and open up the pantry. There are 60 different boxes, each labelled "Pantry". You pick a box at random and open it. Inside is a single box labelled "Grains". You open up the "Grains" box and find a single box labelled "Pasta". You open the "Pasta" box and find a single box labelled "Penne". You open this box and find, as you expect, a bag of penne pasta.

Slightly confused, you pick up an adjacent box, also labelled "Pantry". Inside is a single box, again labelled "Grains". You open up the "Grains" box and, again, find a single box labelled "Pasta". You open the "Pasta" box and find a single box, this one is labelled "Rigatoni". You open this box and find... a bag of rigatoni pasta.

"It's great!" says Bob. "Everything is in a namespace!".

"But Bob..." you reply. "Your organization scheme is useless. You have to open up a bunch of boxes to get to anything, and it's not actually any more convenient to find anything than if you had just put everything in one box instead of three. In fact, since your pantry is already sorted shelf-by-shelf, you don't need the boxes at all. Why not just set the pasta on the shelf and pick it up when you need it?"

"You don't understand -- I need to make sure that no one else puts something that doesn't belong in the 'Pantry' namespace. And I've safely organized all my pasta into the Pantry.Grains.Pasta namespace so I can easily find it"

Bob is a very confused man.

Modules are Their Own Box

You've probably had something similar happen in real life: You order a few things on Amazon, and each item shows up in its own box, with a smaller box inside, with your item wrapped in its own packaging. Even if the interior boxes are similar, the shipments are not usefully "combined".

Going with the box analogy, the key observation is that external modules are their own box. It might be a very complex item with lots of functionality, but any given external module is its own box.


Guidance for External Modules

Now that we've figured out that we don't need to use 'namespaces', how should we organize our modules? Some guiding principles and examples follow.

Export as close to top-level as possible

  • If you're only exporting a single class or function, use export default:

MyClass.ts

export default class SomeType {
  constructor() { ... }
}

MyFunc.ts

function getThing() { return 'thing'; }
export default getThing;

Consumption

import t from './MyClass';
import f from './MyFunc';
var x = new t();
console.log(f());

This is optimal for consumers. They can name your type whatever they want (t in this case) and don't have to do any extraneous dotting to find your objects.

  • If you're exporting multiple objects, put them all at top-level:

MyThings.ts

export class SomeType { ... }
export function someFunc() { ... }

Consumption

import * as m from './MyThings';
var x = new m.SomeType();
var y = m.someFunc();
  • If you're exporting a large number of things, only then should you use the module/namespace keyword:

MyLargeModule.ts

export namespace Animals {
  export class Dog { ... }
  export class Cat { ... }
}
export namespace Plants {
  export class Tree { ... }
}

Consumption

import { Animals, Plants} from './MyLargeModule';
var x = new Animals.Dog();

Red Flags

All of the following are red flags for module structuring. Double-check that you're not trying to namespace your external modules if any of these apply to your files:

  • A file whose only top-level declaration is export module Foo { ... } (remove Foo and move everything 'up' a level)
  • A file that has a single export class or export function that isn't export default
  • Multiple files that have the same export module Foo { at top-level (don't think that these are going to combine into one Foo!)

Append String in Swift

let firstname = "paresh"
let lastname = "hirpara"
let itsme = "\(firstname) \(lastname)"

Is there shorthand for returning a default value if None in Python?

You could use the or operator:

return x or "default"

Note that this also returns "default" if x is any falsy value, including an empty list, 0, empty string, or even datetime.time(0) (midnight).

equivalent to push() or pop() for arrays?

In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

Ant build failed: "Target "build..xml" does not exist"

I'm probably late but this worked for me:


  1. Open your build.xml file located in your project's directory.
  2. Copy and Paste the following code in the main project tag : <target name="build" />

MongoDB/Mongoose querying at a specific date?

...5+ years later, I strongly suggest using date-fns instead

import endOfDayfrom 'date-fns/endOfDay'
import startOfDay from 'date-fns/startOfDay'

MyModel.find({
  createdAt: {
    $gte: startOfDay(new Date()),
    $lte: endOfDay(new Date())
  }
})

For those of us using Moment.js

const moment = require('moment')

const today = moment().startOf('day')

MyModel.find({
  createdAt: {
    $gte: today.toDate(),
    $lte: moment(today).endOf('day').toDate()
  }
})

Important: all moments are mutable!

tomorrow = today.add(1, 'days') does not work since it also mutates today. Calling moment(today) solves that problem by implicitly cloning today.

Message Queue vs. Web Services?

When you use a web service you have a client and a server:

  1. If the server fails the client must take responsibility to handle the error.
  2. When the server is working again the client is responsible of resending it.
  3. If the server gives a response to the call and the client fails the operation is lost.
  4. You don't have contention, that is: if million of clients call a web service on one server in a second, most probably your server will go down.
  5. You can expect an immediate response from the server, but you can handle asynchronous calls too.

When you use a message queue like RabbitMQ, Beanstalkd, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:

  1. If the server fails, the queue persist the message (optionally, even if the machine shutdown).
  2. When the server is working again, it receives the pending message.
  3. If the server gives a response to the call and the client fails, if the client didn't acknowledge the response the message is persisted.
  4. You have contention, you can decide how many requests are handled by the server (call it worker instead).
  5. You don't expect an immediate synchronous response, but you can implement/simulate synchronous calls.

Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.

Copy data from one existing row to another existing row in SQL?

Maybe I read the problem wrong, but I believe you already have inserted the course 11 records and simply need to update those that meet the criteria you listed with course 6's data.

If this is the case, you'll want to use an UPDATE...FROM statement:

UPDATE MyTable
SET
    complete = 1,
    complete_date = newdata.complete_date,
    post_score = newdata.post_score
FROM
    (
    SELECT
        userID,
        complete_date,
        post_score
    FROM MyTable
    WHERE
        courseID = 6
        AND complete = 1
        AND complete_date > '8/1/2008'
    ) newdata
WHERE
    CourseID = 11
    AND userID = newdata.userID

See this related SO question for more info

How to add a new line in textarea element?

just use <br>
ex:

<textarea>
blablablabla <br> kakakakakak <br> fafafafafaf 
</textarea>

result:
blablablabla
kakakakakak
fafafafafaf

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

git rm - fatal: pathspec did not match any files

I had a duplicate directory (~web/web) and it removed the nested duplicate when I ran rm -rf web while inside the first web folder.

Should Gemfile.lock be included in .gitignore?

Assuming you're not writing a rubygem, Gemfile.lock should be in your repository. It's used as a snapshot of all your required gems and their dependencies. This way bundler doesn't have to recalculate all the gem dependencies each time you deploy, etc.

From cowboycoded's comment below:

If you are working on a gem, then DO NOT check in your Gemfile.lock. If you are working on a Rails app, then DO check in your Gemfile.lock.

Here's a nice article explaining what the lock file is.

convert float into varchar in SQL server without scientific notation

STR function works nice. I had float coming back after doing some calculations and needed to change to VARCHAR, but was getting scientific notation randonly as well. I made this transformation after all the calcs

 ltrim(rtrim(str(someField)))

How does Java import work?

Java's import statement is pure syntactical sugar. import is only evaluated at compile time to indicate to the compiler where to find the names in the code.

You may live without any import statement when you always specify the full qualified name of classes. Like this line needs no import statement at all:

javax.swing.JButton but = new  javax.swing.JButton();

The import statement will make your code more readable like this:

import javax.swing.*;

JButton but = new JButton();

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

I had faced the similar error when supporting one application. It was about the generated classes for a SOAP Webservice.

The issue was caused due to the missing classes. When javax.xml.bind.Marshaller was trying to marshal the jaxb object it was not finding all dependent classes which were generated by using wsdl and xsd. after adding the jar with all the classes at the class path the issue was resolved.

My Application Could not open ServletContext resource

The file name u used spring-dispatcher-servlet.xml
kindly check in web.xml
servlet name as spring-dispatcher at both tag  <servlet> and <servlet-mapping>
in your case it should be

<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class></servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>

Authenticating in PHP using LDAP through Active Directory

Importing a whole library seems inefficient when all you need is essentially two lines of code...

$ldap = ldap_connect("ldap.example.com");
if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) {
  // log them in!
} else {
  // error message
}

Regex pattern inside SQL Replace function?

If you are doing this just for a parameter coming into a Stored Procedure, you can use the following:

declare @badIndex int
set @badIndex = PatIndex('%[^0-9]%', @Param)
while @badIndex > 0
    set @Param = Replace(@Param, Substring(@Param, @badIndex, 1), '')
    set @badIndex = PatIndex('%[^0-9]%', @Param)

How to Get the HTTP Post data in C#?

This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.

string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++) 
{
   Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}

How big can a MySQL database get before performance starts to degrade

2GB and about 15M records is a very small database - I've run much bigger ones on a pentium III(!) and everything has still run pretty fast.. If yours is slow it is a database/application design problem, not a mysql one.

VBA: Selecting range by variables

you are turning them into an address but Cells(#,#) uses integer inputs not address inputs so just use lastRow = ActiveSheet.UsedRange.Rows.count and lastColumn = ActiveSheet.UsedRange.Columns.Count

In C can a long printf statement be broken up into multiple lines?

The de-facto standard way to split up complex functions in C is per argument:

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
       sp->name, 
       sp->args, 
       sp->value, 
       sp->arraysize);

Or if you will:

const char format_str[] = "name: %s\targs: %s\tvalue %d\tarraysize %d\n";
...
printf(format_str, 
       sp->name, 
       sp->args, 
       sp->value, 
       sp->arraysize);

You shouldn't split up the string, nor should you use \ to break a C line. Such code quickly turns completely unreadable/unmaintainable.

Change size of text in text input tag?

In your CSS stylesheet, try adding:

input[type="text"] {
    font-size:25px;
}

See this jsFiddle example

$('body').on('click', '.anything', function(){})

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

$(document).on('click','body *',function(){
    //  $(this) = your current element that clicked.
    // additional code
});

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

If your debugged process contains multiple appdomains and the assembly is loaded into both, and one of them is loading an old copy (usually something dynamically loaded like a plugin) the breakpoint can appear solid, but the thread that should hit the breakpoint is in the appdomain with the old assembly, and never hits. You can see what assemblies are loaded and their path in the module window.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

I tried several answers and the only thing what finally did the job was this configuration for the compiler plugin in the pom:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <fork>true</fork>
        <meminitial>128m</meminitial>
        <maxmem>512m</maxmem>
        <source>1.6</source>
        <target>1.6</target>
        <!-- prevent PermGen space out of memory exception -->
        <!-- <argLine>-Xmx512m -XX:MaxPermSize=512m</argLine> -->
    </configuration>
</plugin>

hope this one helps.

How to create a number picker dialog?

Consider using a Spinner instead of a Number Picker in a Dialog. It's not exactly what was asked for, but it's much easier to implement, more contextual UI design, and should fulfill most use cases. The equivalent code for a Spinner is:

Spinner picker = new Spinner(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, yourStringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
picker.setAdapter(adapter);

How do I make a matrix from a list of vectors in R?

Not straightforward, but it works:

> t(sapply(a, unlist))
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

Take the content of a list and append it to another list

To recap on the previous answers. If you have a list with [0,1,2] and another one with [3,4,5] and you want to merge them, so it becomes [0,1,2,3,4,5], you can either use chaining or extending and should know the differences to use it wisely for your needs.

Extending a list

Using the list classes extend method, you can do a copy of the elements from one list onto another. However this will cause extra memory usage, which should be fine in most cases, but might cause problems if you want to be memory efficient.

a = [0,1,2]
b = [3,4,5]
a.extend(b)
>>[0,1,2,3,4,5]

enter image description here

Chaining a list

Contrary you can use itertools.chain to wire many lists, which will return a so called iterator that can be used to iterate over the lists. This is more memory efficient as it is not copying elements over but just pointing to the next list.

import itertools
a = [0,1,2]
b = [3,4,5]
c = itertools.chain(a, b)

enter image description here

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

How to draw a line with matplotlib?

This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2)

x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence.

x2 and y2 are the same for the other line.

import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()

enter image description here

I suggest you spend some time reading / studying the basic tutorials found on the very rich matplotlib website to familiarize yourself with the library.

What if I don't want line segments?

There are no direct ways to have lines extend to infinity... matplotlib will either resize/rescale the plot so that the furthest point will be on the boundary and the other inside, drawing line segments in effect; or you must choose points outside of the boundary of the surface you want to set visible, and set limits for the x and y axis.

As follows:

import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 10]
x2, y2 = [-1, 10], [3, -1]
plt.xlim(0, 8), plt.ylim(-2, 8)
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()

enter image description here

Installing specific laravel version with composer create-project

If you want to use a stable version of your preferred Laravel version of choice, use:

composer create-project --prefer-dist laravel/laravel project-name "5.5.*"

That will pick out the most recent or best update of version 5.5.* (5.5.28)

What is <scope> under <dependency> in pom.xml for?

Six Dependency scopes:

  • compile: default scope, classpath is available for both src/main and src/test
  • test: classpath is available for src/test
  • provided: like complie but provided by JDK or a container at runtime
  • runtime: not required for compilation only require at runtime
  • system: provided locally provide classpath
  • import: can only import other POMs into the <dependencyManagement/>, only available in Maven 2.0.9 or later (like java import )

Insert data using Entity Framework model

It should be:

context.TableName.AddObject(TableEntityInstance);

Where:

  1. TableName: the name of the table in the database.
  2. TableEntityInstance: an instance of the table entity class.

If your table is Orders, then:

Order order = new Order();
context.Orders.AddObject(order);

For example:

 var id = Guid.NewGuid();

 // insert
 using (var db = new EfContext("name=EfSample"))
 {
    var customers = db.Set<Customer>();
    customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );

    db.SaveChanges();
 }

Here is a live example:

public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
  var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();

  var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();

  if (current != null)
  {
    current.Screen = imageBytes;
    current.Refreshed = DateTime.Now;

    this.ObjectContext.SaveChanges();
  }
  else
  {
    Screenshot screenshot = new Screenshot();

    screenshot.ID = Guid.NewGuid();
    screenshot.Interval = 1000;
    screenshot.IsTurnedOn = true;
    screenshot.PlayerID = player.ID;
    screenshot.Refreshed = DateTime.Now;
    screenshot.Screen = imageBytes;

    this.ObjectContext.Screenshots.AddObject(screenshot);
    this.ObjectContext.SaveChanges();
  }
}

Run all SQL files in a directory

You can create a single script that calls all the others.

Put the following into a batch file:

@echo off
echo.>"%~dp0all.sql"
for %%i in ("%~dp0"*.sql) do echo @"%%~fi" >> "%~dp0all.sql"

When you run that batch file it will create a new script named all.sql in the same directory where the batch file is located. It will look for all files with the extension .sql in the same directory where the batch file is located.

You can then run all scripts by using sqlplus user/pwd @all.sql (or extend the batch file to call sqlplus after creating the all.sql script)