Programs & Examples On #Coldfusionbuilder

ColdFusion® Builder™ is a professional IDE from Adobe® for quickly and easily building ColdFusion applications.

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.

Nested ifelse statement

You can create the vector idnat2 without if and ifelse.

The function replace can be used to replace all occurrences of "colony" with "overseas":

idnat2 <- replace(idbp, idbp == "colony", "overseas")

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

df = df.replace({np.nan: None})

Credit goes to this guy here on this Github issue.

Windows batch: formatted date into variable

Due to date and time format is location specific info, retrieving them from %date% and %time% variables will need extra effort to parse the string with format transform into consideration. A good idea is to use some API to retrieve the data structure and parse as you wish. WMIC is a good choice. Below example use Win32_LocalTime. You can also use Win32_CurrentTime or Win32_UTCTime.

@echo off  
SETLOCAL ENABLEDELAYEDEXPANSION  
for /f %%x in ('wmic path Win32_LocalTime get /format:list ^| findstr "="') do set %%x  
set yyyy=0000%Year%  
set mmmm=0000%Month%  
set dd=00%Day%  
set hh=00%Hour%  
set mm=00%Minute%  
set ss=00%Second%  
set ts=!yyyy:~-4!-!mmmm:~-2!-!dd:~-2!_!hh:~-2!:!mm:~-2!:!ss:~-2!  
echo %ts%  
ENDLOCAL  

Result:
2018-04-25_10:03:11

Killing a process using Java

AFAIU java.lang.Process is the process created by java itself (like Runtime.exec('firefox'))

You can use system-dependant commands like

 Runtime rt = Runtime.getRuntime();
  if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) 
     rt.exec("taskkill " +....);
   else
     rt.exec("kill -9 " +....);

How do I add a newline to a windows-forms TextBox?

TextBox2.Text = "Line 1" & Environment.NewLine & "Line 2"

or

TextBox2.Text = "Line 1"
TextBox2.Text += Environment.NewLine
TextBox2.Text += "Line 2"

This, is how it is done.

IllegalArgumentException or NullPointerException for a null parameter?

According to your scenario, IllegalArgumentException is the best pick, because null is not a valid value for your property.

A top-like utility for monitoring CUDA activity on a GPU

If you just want to find the process which is running on gpu, you can simply using the following command:

lsof /dev/nvidia*

For me nvidia-smi and watch -n 1 nvidia-smi are enough in most cases. Sometimes nvidia-smi shows no process but the gpu memory is used up so i need to use the above command to find the processes.

Implementing IDisposable correctly

Idisposable is implement whenever you want a deterministic (confirmed) garbage collection.

class Users : IDisposable
    {
        ~Users()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
            // This method will remove current object from garbage collector's queue 
            // and stop calling finilize method twice 
        }    

        public void Dispose(bool disposer)
        {
            if (disposer)
            {
                // dispose the managed objects
            }
            // dispose the unmanaged objects
        }
    }

When creating and using the Users class use "using" block to avoid explicitly calling dispose method:

using (Users _user = new Users())
            {
                // do user related work
            }

end of the using block created Users object will be disposed by implicit invoke of dispose method.

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

Choose newline character in Notepad++

on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF) or Unix(LF)

How to set connection timeout with OkHttp

For okhttp3 this has changed a bit.

Now you set up the times using the builder, and not setters, like this:

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build();

More info can be found in their wiki: https://github.com/square/okhttp/blob/b3dcb9b1871325248fba917458658628c44ce8a3/docs/recipes.md#timeouts-kt-java

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

How do I split a string, breaking at a particular character?

This isn't as good as the destructuring answer, but seeing as this question was asked 12 years ago, I decided to give it an answer that also would have worked 12 years ago.

function Record(s) {
    var keys = ["name", "address", "address2", "city", "state", "zip"], values = s.split("~"), i
    for (i = 0; i<keys.length; i++) {
        this[keys[i]] = values[i]
    }
}

var record = new Record('john smith~123 Street~Apt 4~New York~NY~12345')

record.name // contains john smith
record.address // contains 123 Street
record.address2 // contains Apt 4
record.city // contains New York
record.state // contains NY
record.zip // contains zip

How to vertically align <li> elements in <ul>?

Here's a good one:

Set line-height equal to whatever the height is; works like a charm!

E.g:

li {
    height: 30px;
    line-height: 30px;
}

no default constructor exists for class

Because you have this:

Blowfish(BlowfishAlgorithm algorithm);

It's not a default constructor. The default constructor is one which takes no parameters. i.e.

Blowfish();

How to divide flask app into multiple py files?

I would like to recommend flask-empty at GitHub.

It provides an easy way to understand Blueprints, multiple views and extensions.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

This code worked for me

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserDetail>()
            .HasRequired(d => d.User)
            .WithOptional(u => u.UserDetail)
            .WillCascadeOnDelete(true);
    }

The migration code was:

public override void Up()
    {
        AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
    }

And it worked fine. When I first used

modelBuilder.Entity<User>()
    .HasOptional(a => a.UserDetail)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);

The migration code was:

AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true); 

but it does not match any of the two overloads available (in EntityFramework 6)

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

The following is my solution. Test it if it works for you:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/classes/lib</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
        </execution>
    </executions>
</plugin>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <!-- <classpathPrefix>lib</classpathPrefix> -->
                <!-- <mainClass>test.org.Cliente</mainClass> -->
            </manifest>
            <manifestEntries>
                <Class-Path>lib/</Class-Path>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

The first plugin puts all dependencies in the target/classes/lib folder, and the second one includes the library folder in the final JAR file, and configures the Manifest.mf file.

But then you will need to add custom classloading code to load the JAR files.

Or, to avoid custom classloading, you can use "${project.build.directory}/lib, but in this case, you don't have dependencies inside the final JAR file, which defeats the purpose.

It's been two years since the question was asked. The problem of nested JAR files persists nevertheless. I hope it helps somebody.

Get final URL after curl is redirected

You could use grep. doesn't wget tell you where it's redirecting too? Just grep that out.

How to determine if binary tree is balanced?

This is being made way more complicated than it actually is.

The algorithm is as follows:

  1. Let A = depth of the highest-level node
  2. Let B = depth of the lowest-level node

  3. If abs(A-B) <= 1, then the tree is balanced

What is process.env.PORT in Node.js?

  • if you run node index.js ,Node will use 3000

  • If you run PORT=4444 node index.js, Node will use process.env.PORT which equals to 4444 in this example. Run with sudo for ports below 1024.

How to request Location Permission at runtime

check this code from MainActivity

 // Check location permission is granted - if it is, start
// the service, otherwise request the permission
fun checkOrAskLocationPermission(callback: () -> Unit) {
    // Check GPS is enabled
    val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "Please enable location services", Toast.LENGTH_SHORT).show()
        buildAlertMessageNoGps(this)
        return
    }

    // Check location permission is granted - if it is, start
    // the service, otherwise request the permission
    val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
    if (permission == PackageManager.PERMISSION_GRANTED) {
        callback.invoke()
    } else {
        // callback will be inside the activity's onRequestPermissionsResult(
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            PERMISSIONS_REQUEST
        )
    }
}

plus

   override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == PERMISSIONS_REQUEST) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
              // Permission ok. Do work.
         }
    }
}

plus

 fun buildAlertMessageNoGps(context: Context) {
    val builder = AlertDialog.Builder(context);
    builder.setMessage("Your GPS is disabled. Do you want to enable it?")
        .setCancelable(false)
        .setPositiveButton("Yes") { _, _ -> context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) }
        .setNegativeButton("No") { dialog, _ -> dialog.cancel(); }
    val alert = builder.create();
    alert.show();
}

usage

checkOrAskLocationPermission() {
            // Permission ok. Do work.
        }

Item frequency count in Python

defaultdict to the rescue!

from collections import defaultdict

words = "apple banana apple strawberry banana lemon"

d = defaultdict(int)
for word in words.split():
    d[word] += 1

This runs in O(n).

How can I check the syntax of Python script without executing it?

Thanks to the above answers @Rosh Oxymoron. I improved the script to scan all files in a dir that are python files. So for us lazy folks just give it the directory and it will scan all the files in that directory that are python.

import sys
import glob, os

os.chdir(sys.argv[1])
for file in glob.glob("*.py"):
    source = open(file, 'r').read() + '\n'
    compile(source, file, 'exec')

Save this as checker.py and run python checker.py ~/YOURDirectoryTOCHECK

mysql SELECT IF statement with OR

Presumably this would work:

IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment

Blur effect on a div element

Try using this library: https://github.com/jakiestfu/Blur.js-II

That should do it for ya.

Don't understand why UnboundLocalError occurs (closure)

The reason of why your code throws an UnboundLocalError is already well explained in other answers.

But it seems to me that you're trying to build something that works like itertools.count().

So why don't you try it out, and see if it suits your case:

>>> from itertools import count
>>> counter = count(0)
>>> counter
count(0)
>>> next(counter)
0
>>> counter
count(1)
>>> next(counter)
1
>>> counter
count(2)

How do I show the schema of a table in a MySQL database?

describe [db_name.]table_name;

for formatted output, or

show create table [db_name.]table_name;

for the SQL statement that can be used to create a table.

C++ terminate called without an active exception

First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.

As follows, calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.

Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable.

Could not find default endpoint element

Do not put service client declaration line as class field, instead of this, create instance at each method that used in. So problem will be fixed. If you create service client instance as class field, then design time error occurs !

CSS: Creating textured backgrounds

Use an image editor to cut out a portion of the background, then apply CSS's background-repeat property to make the small image fill the area where it is used.

In some cases, background-repeat creates seams where the image repeats. A solution is to use an image editor as follows: starting with the background image, copy the image, flip (mirror, not rotate) the copy left-to-right, and paste it to the right edge of the original, overlapping 1 pixel. Crop to remove 1 pixel from the right edge of the combined image. Now repeat for the vertical: copy the combined image, flip the copy top-to-bottom, paste it to the bottom of the combined, overlapping one pixel. Crop to remove 1 pixel from the bottom. The resulting image should be seam-free.

Editing in the Chrome debugger

This is what you are looking for:

1.- Navigate to the Source tab and open the javascript file

2.- Edit the file, right-click it and a menu will appear: click Save and save it locally.

In order to view the diff or revert your changes, right-click and select the option Local Modifications... from the menu. You will see your changes diff with respect to the original file if you expand the timestamp shown.

More detailed info here: http://www.sitepoint.com/edit-source-files-in-chrome/

Execute ssh with password authentication via windows command prompt

PuTTY's plink has a command-line argument for a password. Some other suggestions have been made in the answers to this question: using Expect (which is available for Windows), or writing a launcher in Python with Paramiko.

How do you properly determine the current script directory?

Just use os.path.dirname(os.path.abspath(__file__)) and examine very carefully whether there is a real need for the case where exec is used. It could be a sign of troubled design if you are not able to use your script as a module.

Keep in mind Zen of Python #8, and if you believe there is a good argument for a use-case where it must work for exec, then please let us know some more details about the background of the problem.

json_encode() escaping forward slashes

is there a way to disable it?

Yes, you only need to use the JSON_UNESCAPED_SLASHES flag.

!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)

json_encode($str, JSON_UNESCAPED_SLASHES);

If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).

Example Demo

<?php
/*
 * Escaping the reverse-solidus character ("/", slash) is optional in JSON.
 *
 * This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
 *
 * @link http://stackoverflow.com/a/10210433/367456
 */    

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";

Example Output:

"http:\/\/www.example.com\/"
"http://www.example.com/"

How to add a second x-axis in matplotlib

I'm forced to post this as an answer instead of a comment due to low reputation. I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:

ax2.lines = []

instead of using:

ax2.cla()

When in use also cleared my plot from ax1.

Warning about SSL connection when connecting to MySQL database

An alternative method would be:

Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "milos23);
properties.setProperty("useSSL", "false");

try (Connection conn = DriverManager.getConnection(connectionUrl, properties)) {
...
} catch (SQLException e) {
...
}

PHP split alternative?

Yes, I would use explode or you could use:

preg_split

Which is the advised method with PHP 6. preg_split Documentation

Multiple REPLACE function in Oracle

In case all your source and replacement strings are just one character long, you can simply use the TRANSLATE function:

  SELECT translate('THIS IS UPPERCASE', 'THISUP', 'thisup') 
  FROM DUAL

See the Oracle documentation for details.

Event listener for when element becomes visible?

var targetNode = document.getElementById('elementId');
var observer = new MutationObserver(function(){
    if(targetNode.style.display != 'none'){
        // doSomething
    }
});
observer.observe(targetNode, { attributes: true, childList: true });

I might be a little late, but you could just use the MutationObserver to observe any changes on the desired element. If any change occurs, you'll just have to check if the element is displayed.

Simple logical operators in Bash

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

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

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

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

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

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

Selecting multiple columns with linq query and lambda expression

using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;

as Name = Fname + " " + LName;

See my below code which is working as expected; hope this is useful;

Myentity objMyEntity = new Myentity
{
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact
}

no need to declare the 'contact'

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.

HTML

<li>
    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>
</li>

Controller

@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";
}

Spring URI Template Documentation

Get selected value of a dropdown's item using jQuery

If you have more than one dropdown try:

HTML:

<select id="dropdown1" onchange="myFunction(this)">
    <option value='...'>Option1
    <option value='...'>Option2
</select>
<select id="dropdown2" onchange="myFunction(this)">
    <option value='...'>Option1
    <option value='...'>Option2
</select>

JavaScript:

    function myFunction(sel) {
        var selected = sel.value;
    }

Convert string[] to int[] in one line of code using LINQ

Given an array you can use the Array.ConvertAll method:

int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));

Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:

int[] myInts = Array.ConvertAll(arr, int.Parse);

A LINQ solution is similar, except you would need the extra ToArray call to get an array:

int[] myInts = arr.Select(int.Parse).ToArray();

Extract a substring from a string in Ruby using a regular expression

A simpler scan would be:

String1.scan(/<(\S+)>/).last

How to change btn color in Bootstrap

The easiest way to see which properties you need to override is to take a look at Bootstrap's source code, specifically the .button-variant mixin defined in mixins/buttons.less. You still need to override quite a lot of properties to get rid of all of the .btn-primary styling (e.g. :focus, disabled, usage in dropdowns etc).

A better way might be to:

  1. Create your own customized version of Bootstrap using Bootstrap's online customization tool
  2. Manually create your own color class, e.g. .btn-whatever
  3. Use a LESS compiler and use the .button-variant mixin to create your own color class, e.g. .btn-whatever

Copy data into another table

CREATE TABLE `table2` LIKE `table1`;
INSERT INTO `table2` SELECT * FROM `table1`;

the first query will create the structure from table1 to table2 and second query will put the data from table1 to table2

Set scroll position

Also worth noting window.scrollBy(dx,dy) (ref)

Revert to Eclipse default settings

Try switching between different Themes option available in General->Appearance->Colors and Fonts.

I earlier used Dark theme in Juno. Then reverted to Windows 7 classic theme but was left with Black background. And that led me to this question. Having not found any solution I finally tried with Windows XP Olive and to my amazement black background was restored to default.

enter image description here

MATLAB, Filling in the area between two sets of data, lines in one figure

Personally, I find it both elegant and convenient to wrap the fill function. To fill between two equally sized row vectors Y1 and Y2 that share the support X (and color C):

fill_between_lines = @(X,Y1,Y2,C) fill( [X fliplr(X)],  [Y1 fliplr(Y2)], C );

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

In my case, the error message was implying that I was working in a headless console. So plt.show() could not work. What worked was calling plt.savefig:

import matplotlib.pyplot as plt

plt.plot([1,2,3], [5,7,4])
plt.savefig("mygraph.png")

I found the answer on a github repository.

PHP convert string to hex and hex to string

function hexToStr($hex){
    // Remove spaces if the hex string has spaces
    $hex = str_replace(' ', '', $hex);
    return hex2bin($hex);
}
// Test it 
$hex    = "53 44 43 30 30 32 30 30 30 31 37 33";
echo hexToStr($hex); // SDC002000173

/**
 * Test Hex To string with PHP UNIT
 * @param  string $value
 * @return 
 */
public function testHexToString()
{
    $string = 'SDC002000173';
    $hex    = "53 44 43 30 30 32 30 30 30 31 37 33";
    $result = hexToStr($hex);

    $this->assertEquals($result,$string);
}

regular expression for anything but an empty string

We can also use space in a char class, in an expression similar to one of these:

(?!^[ ]*$)^\S+$
(?!^[ ]*$)^\S{1,}$
(?!^[ ]{0,}$)^\S{1,}$
(?!^[ ]{0,1}$)^\S{1,}$

depending on the language/flavor that we might use.

RegEx Demo

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?!^[ ]*$)^\S+$";
        string input = @"

            abcd
            ABCD1234
            #$%^&*()_+={}
            abc def
            ABC 123
            ";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

C# Demo


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Retain precision with double in Java

Use java.math.BigDecimal

Doubles are binary fractions internally, so they sometimes cannot represent decimal fractions to the exact decimal.

How to stop BackgroundWorker correctly

MY example . DoWork is below:

    DoLengthyWork();

    //this is never executed
    if(bgWorker.CancellationPending)
    {
        MessageBox.Show("Up to here? ...");
        e.Cancel = true;
    }

inside DoLenghtyWork :

public void DoLenghtyWork()
{
    OtherStuff();
    for(int i=0 ; i<10000000; i++) 
    {  int j = i/3; }
}

inside OtherStuff() :

public void OtherStuff()
{
    for(int i=0 ; i<10000000; i++) 
    {  int j = i/3; }
}

What you want to do is modify both DoLenghtyWork and OtherStuff() so that they become:

public void DoLenghtyWork()
{
    if(!bgWorker.CancellationPending)
    {              
        OtherStuff();
        for(int i=0 ; i<10000000; i++) 
        {  
             int j = i/3; 
        }
    }
}

public void OtherStuff()
{
    if(!bgWorker.CancellationPending)
    {  
        for(int i=0 ; i<10000000; i++) 
        {  
            int j = i/3; 
        }
    }
}

Android: ScrollView force to bottom

When the view is not loaded yet, you cannot scroll. You can do it 'later' with a post or sleep call as above, but this is not very elegant.

It is better to plan the scroll and do it on the next onLayout(). Example code here:

https://stackoverflow.com/a/10209457/1310343

How to change a DIV padding without affecting the width/height ?

To achieve a consistent result cross browser, you would usually add another div inside the div and give that no explicit width, and a margin. The margin will simulate padding for the outer div.

"Could not load type [Namespace].Global" causing me grief

I had to delete (duplicate) files from disk that were not included in the project. Looks like the duplicates were caused by a failed rename. The file names were different, but same code.

After deleting all the oof.* files I was able to scan.

  • foo.aspx
  • foo.aspx.cs
  • foo.aspx.designer.cs
  • oof.aspx
  • oof.aspx.cs
  • oof.aspx.designer.cs

How to check if IsNumeric

You could write an extension method:

public static class Extension
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

JPanel Padding in Java

Set an EmptyBorder around your JPanel.
Example:

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

How do I drop a MongoDB database from the command line?

one liner remote remove all collections from mongo database

note must use --host, (-h is help for mongo command), and -d is not an option, select the db and command after password.

mongo --host <mongo_host>:<mongo_port> -u <db_user> -p <db_pass> <your_db> --eval "db.dropDatabase()"

Split large string in n-size chunks in JavaScript

What about this small piece of code:

function splitME(str, size) {
    let subStr = new RegExp('.{1,' + size + '}', 'g');
    return str.match(subStr);
};

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

SQL Query for Student mark functionality

Select S.StudentName 
From Student S 
where S.StudentID IN 
    (Select StudentID from (
        ( Select Max(MarkRate)as MarkRate,SubjectID From  Mark Group by SubjectID)) MaxMarks, Mark
 where MaxMarks.SubjectID= Mark.SubjectID AND MaxMarks.MarkRate=Mark.MarkRate)

How do I join two lines in vi?

Another way of joining two lines without placing cursor to that line is:

:6,6s#\n##

Here 6 is the line number to which another line will be join. To display the line number, use :set nu.

If we are on the cursor where the next line should be joined, then:

:s#\n##

In both cases we don't need g like :s#\n##g, because on one line only one \n exist.

Finding length of char array

sizeof returns the size of the type of the variable in bytes. So in your case it's returning the size of your char[7] which is 7 * sizeof(char). Since sizeof(char) = 1, the result is 7.

Expanding this to another example:

int intArr[5];
printf("sizeof(intArr)=%u", sizeof(intArr));

would yield 5 * sizeof(int), so you'd get the result "20" (At least on a regular 32bit platform. On others sizeof(int) might differ)

To return to your problem:

It seems like, that what you want to know is the length of the string which is contained inside your array and not the total array size.

By definition C-Strings have to be terminated with a trailing '\0' (0-Byte). So to get the appropriate length of the string contained within your array, you have to first terminate the string, so that you can tell when it's finished. Otherwise there would be now way to know.

All standard functions build upon this definition, so if you call strlen to retrieve the str ing len gth, it will iterate through the given array until it finds the first 0-byte, which in your case would be the very first element.

Another thing you might need to know that only because you don't fill the remaining elements of your char[7] with a value, they actually do contain random undefined values.

Hope that helped.

How do I get a Date without time in Java?

Well, as far as I know there is no easier way to achieve this if you only use the standard JDK.

You can, of course, put that logic in method2 into a static function in a helper class, like done here in the toBeginningOfTheDay-method

Then you can shorten the second method to:

Calendar cal = Calendar.getInstance();
Calendars.toBeginningOfTheDay(cal);
dateWithoutTime = cal.getTime();

Or, if you really need the current day in this format so often, then you can just wrap it up in another static helper method, thereby making it a one-liner.

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

Make can tell you what it knows and what it will do. Suppose you have an "install" target, which executes commands like:

cp <filelist> <destdir>/

In your generic rules, add:

uninstall :; MAKEFLAGS= ${MAKE} -j1 -spinf $(word 1,${MAKEFILE_LIST}) install \
              | awk '/^cp /{dest=$NF; for (i=NF; --i>0;) {print dest"/"$i}}' \
              | xargs rm -f

A similar trick can do a generic make clean.

AngularJS multiple filter with custom filter function

Hope below answer in this link will help, Multiple Value Filter

And take a look into the fiddle with example

arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

fiddle

C# Ignore certificate errors?

To further expand on BIGNUM's post - Ideally you want a solution that will simulate the conditions you will see in production and modifying your code won't do that and could be dangerous if you forget to take the code out before you deploy it.

You will need a self-signed certificate of some sort. If you know what you're doing you can use the binary BIGNUM posted, but if not you can go hunting for the certificate. If you're using IIS Express you will have one of these already, you'll just have to find it. Open Firefox or whatever browser you like and go to your dev website. You should be able to view the certificate information from the URL bar and depending on your browser you should be able to export the certificate to a file.

Next, open MMC.exe, and add the Certificate snap-in. Import your certificate file into the Trusted Root Certificate Authorities store and that's all you should need. It's important to make sure it goes into that store and not some other store like 'Personal'. If you're unfamiliar with MMC or certificates, there are numerous websites with information how to do this.

Now, your computer as a whole will implicitly trust any certificates that it has generated itself and you won't need to add code to handle this specially. When you move to production it will continue to work provided you have a proper valid certificate installed there. Don't do this on a production server - that would be bad and it won't work for any other clients other than those on the server itself.

IPhone/IPad: How to get screen width programmatically?

Here is a Swift way to get screen sizes, this also takes current interface orientation into account:

var screenWidth: CGFloat {
    if UIInterfaceOrientationIsPortrait(screenOrientation) {
        return UIScreen.mainScreen().bounds.size.width
    } else {
        return UIScreen.mainScreen().bounds.size.height
    }
}
var screenHeight: CGFloat {
    if UIInterfaceOrientationIsPortrait(screenOrientation) {
        return UIScreen.mainScreen().bounds.size.height
    } else {
        return UIScreen.mainScreen().bounds.size.width
    }
}
var screenOrientation: UIInterfaceOrientation {
    return UIApplication.sharedApplication().statusBarOrientation
}

These are included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions

Get item in the list in Scala?

Why parentheses?

Here is the quote from the book programming in scala.

Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So greetStrings(i) gets transformed into greetStrings.apply(i). Thus accessing an element of an array in Scala is simply a method call like any other. This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an apply method call. Of course this will compile only if that type of object actually defines an apply method. So it's not a special case; it's a general rule.

Here are a few examples how to pull certain element (first elem in this case) using functional programming style.

  // Create a multdimension Array 
  scala> val a = Array.ofDim[String](2, 3)
  a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
  scala> a(0) = Array("1","2","3")
  scala> a(1) = Array("4", "5", "6")
  scala> a
  Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))

  // 1. paratheses
  scala> a.map(_(0))
  Array[String] = Array(1, 4)
  // 2. apply
  scala> a.map(_.apply(0))
  Array[String] = Array(1, 4)
  // 3. function literal
  scala> a.map(a => a(0))
  Array[String] = Array(1, 4)
  // 4. lift
  scala> a.map(_.lift(0))
  Array[Option[String]] = Array(Some(1), Some(4))
  // 5. head or last 
  scala> a.map(_.head)
  Array[String] = Array(1, 4)

How to download folder from putty using ssh client

You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.

Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html

Loading basic HTML in Node.js

I think this would be a better option as it shows the URL running the server:

var http = require('http'),
    fs = require('fs');

const hostname = '<your_machine_IP>';
const port = 3000;

const html=fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    }
        http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(port, hostname, () => {
            console.log(`Server running at http://${hostname}:${port}/`);
        })
}); 

How do I resolve a path relative to an ASP.NET MVC 4 application root?

I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:

HostingEnvironment.MapPath("~/Data/data.html")

How to change css property using javascript

Consider the following example: If you want to change a single CSS property(say, color to 'blue'), then the below statement works fine.

document.getElementById("ele_id").style.color="blue";

But, for changing multiple properies the more robust way is using Object.assign() or, object spread operator {...};

See below:

const ele=document.getElementById("ele_id");
const custom_style={
    display: "block",
    color: "red"
}

//Object.assign():
Object.assign(ele.style,custum_style);

Spread operator works similarly, just the syntax is a little different.

force client disconnect from server with socket.io and nodejs

use :

socket.Disconnect() //ok

do not use :

socket.disconnect()

Using jquery to get element's position relative to viewport

Here is a function that calculates the current position of an element within the viewport:

/**
 * Calculates the position of a given element within the viewport
 *
 * @param {string} obj jQuery object of the dom element to be monitored
 * @return {array} An array containing both X and Y positions as a number
 * ranging from 0 (under/right of viewport) to 1 (above/left of viewport)
 */
function visibility(obj) {
    var winw = jQuery(window).width(), winh = jQuery(window).height(),
        elw = obj.width(), elh = obj.height(),
        o = obj[0].getBoundingClientRect(),
        x1 = o.left - winw, x2 = o.left + elw,
        y1 = o.top - winh, y2 = o.top + elh;

    return [
        Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),
        Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))
    ];
}

The return values are calculated like this:

Usage:

visibility($('#example'));  // returns [0.3742887830933581, 0.6103752759381899]

Demo:

_x000D_
_x000D_
function visibility(obj) {var winw = jQuery(window).width(),winh = jQuery(window).height(),elw = obj.width(),_x000D_
    elh = obj.height(), o = obj[0].getBoundingClientRect(),x1 = o.left - winw, x2 = o.left + elw, y1 = o.top - winh, y2 = o.top + elh; return [Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))];_x000D_
}_x000D_
setInterval(function() {_x000D_
  res = visibility($('#block'));_x000D_
  $('#x').text(Math.round(res[0] * 100) + '%');_x000D_
  $('#y').text(Math.round(res[1] * 100) + '%');_x000D_
}, 100);
_x000D_
#block { width: 100px; height: 100px; border: 1px solid red; background: yellow; top: 50%; left: 50%; position: relative;_x000D_
} #container { background: #EFF0F1; height: 950px; width: 1800px; margin-top: -40%; margin-left: -40%; overflow: scroll; position: relative;_x000D_
} #res { position: fixed; top: 0; z-index: 2; font-family: Verdana; background: #c0c0c0; line-height: .1em; padding: 0 .5em; font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="res">_x000D_
  <p>X: <span id="x"></span></p>_x000D_
  <p>Y: <span id="y"></span></p>_x000D_
</div>_x000D_
<div id="container"><div id="block"></div></div>
_x000D_
_x000D_
_x000D_

How do I redirect output to a variable in shell?

If a pipeline is too complicated to wrap in $(...), consider writing a function. Any local variables available at the time of definition will be accessible.

function getHash {
  genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5
}
hash=$(getHash)

http://www.gnu.org/software/bash/manual/bashref.html#Shell-Functions

Is there Selected Tab Changed Event in the standard WPF Tab Control

That is the correct event. Maybe it's not wired up correctly?

<TabControl SelectionChanged="TabControl_SelectionChanged">
    <TabItem Header="One"/>
    <TabItem Header="2"/>
    <TabItem Header="Three"/>
</TabControl>

in the codebehind....

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    int i = 34;
}

if I set a breakpoint on the i = 34 line, it ONLY breaks when i change tabs, even when the tabs have child elements and one of them is selected.

lambda expression for exists within list

If listOfIds is a list, this will work, but, List.Contains() is a linear search, so this isn't terribly efficient.

You're better off storing the ids you want to look up into a container that is suited for searching, like Set.

List<int> listOfIds = new List(GetListOfIds());
lists.Where(r=>listOfIds.Contains(r.Id));

ALTER TABLE DROP COLUMN failed because one or more objects access this column

The @SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int DEFAULT NULL;

But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.

So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int NULL,
  CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;

You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.

Best way to check if a character array is empty

This will work to find if a character array is empty. It probably is also the fastest.

if(text[0] == '\0') {}

This will also be fast if the text array is empty. If it contains characters it needs to count all the characters in it first.

if(strlen(text) == 0) {}

How to actually search all files in Visual Studio

So the answer seems to be to NOT use the Solution Explorer search box.

Rather, open any file in the solution, then use the control-f search pop-up to search all files by:

  1. selecting "Find All" from the "--> Find Next / <-- Find Previous" selector
  2. selecting "Current Project" or "Entire Solution" from the selector that normally says just "Current Document".

Laravel Eloquent - distinct() and count() not working properly together

Anyone else come across this post, and not finding the other suggestions to work?

Depending on the specific query, a different approach may be needed. In my case, I needed either count the results of a GROUP BY, e.g.

SELECT COUNT(*) FROM (SELECT * FROM a GROUP BY b)

or use COUNT(DISTINCT b):

SELECT COUNT(DISTINCT b) FROM a

After some puzzling around, I realised there was no built-in Laravel function for either of these. So the simplest solution was to use use DB::raw with the count method.

$count = $builder->count(DB::raw('DISTINCT b'));

Remember, don't use groupBy before calling count. You can apply groupBy later, if you need it for getting rows.

How do I do a HTTP GET in Java?

Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:

GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();

and here is a more complete example.

A table name as a variable

Change your last statement to this:

EXEC('SELECT * FROM ' + @tablename)

This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.

--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE @table_name varchar(max)
SET @table_name =
    (SELECT 'TEST_'
            + DATENAME(YEAR,GETDATE())
            + UPPER(DATENAME(MONTH,GETDATE())) )

--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
          FROM sysobjects
          WHERE name = @table_name AND xtype = 'U')

BEGIN
    EXEC('drop table ' +  @table_name)
END

--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + @table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')

What is the best way to call a script from another script?

I prefer runpy:

#!/usr/bin/env python
# coding: utf-8

import runpy

runpy.run_path(path_name='script-01.py')
runpy.run_path(path_name='script-02.py')
runpy.run_path(path_name='script-03.py')

Border around each cell in a range

The following can be called with any range as parameter:

Option Explicit

Sub SetRangeBorder(poRng As Range)
    If Not poRng Is Nothing Then
        poRng.Borders(xlDiagonalDown).LineStyle = xlNone
        poRng.Borders(xlDiagonalUp).LineStyle = xlNone
        poRng.Borders(xlEdgeLeft).LineStyle = xlContinuous
        poRng.Borders(xlEdgeTop).LineStyle = xlContinuous
        poRng.Borders(xlEdgeBottom).LineStyle = xlContinuous
        poRng.Borders(xlEdgeRight).LineStyle = xlContinuous
        poRng.Borders(xlInsideVertical).LineStyle = xlContinuous
        poRng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
    End If
End Sub

Examples:

Call SetRangeBorder(Range("C11"))
Call SetRangeBorder(Range("A" & result))
Call SetRangeBorder(DT.Cells(I, 6))
Call SetRangeBorder(Range("A3:I" & endRow))

Setting an image for a UIButton in code

In case of Swift User

// case of normal image
let image1 = UIImage(named: "your_image_file_name_without_extension")!
button1.setImage(image1, forState: UIControlState.Normal) 

// in case you don't want image to change when "clicked", you can leave code below
// case of when button is clicked
let image2 = UIImage(named: "image_clicked")!
button1.setImage(image2, forState: UIControlState.Highlight) 

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

base 64 encode and decode a string in angular (2+)

Use the btoa() function to encode:

_x000D_
_x000D_
console.log(btoa("password")); // cGFzc3dvcmQ=
_x000D_
_x000D_
_x000D_

To decode, you can use the atob() function:

_x000D_
_x000D_
console.log(atob("cGFzc3dvcmQ=")); // password
_x000D_
_x000D_
_x000D_

What is attr_accessor in Ruby?

It is just a method that defines getter and setter methods for instance variables. An example implementation would be:

def self.attr_accessor(*names)
  names.each do |name|
    define_method(name) {instance_variable_get("@#{name}")} # This is the getter
    define_method("#{name}=") {|arg| instance_variable_set("@#{name}", arg)} # This is the setter
  end
end

How to Update Date and Time of Raspberry Pi With out Internet

Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)

server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst

3. If you want to make sure that date and time update at startup run this python script in rpi,

import os

try:
    client = ntplib.NTPClient()
    response = client.request('xxx.xxx.xxx.xxx', version=4)
    print "===================================="
    print "Offset : "+str(response.offset)
    print "Version : "+str(response.version)
    print "Date Time : "+str(ctime(response.tx_time))
    print "Leap : "+str(ntplib.leap_to_text(response.leap))
    print "Root Delay : "+str(response.root_delay)
    print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
    os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
    print "===================================="
except:
    os.system("sudo date")
    print "NTP Server Down Date Time NOT Set At The Startup"
    pass

I found more info in raspberry pi forum.

C# - What does the Assert() method do? Is it still useful?

First of all Assert() method is available for Trace and Debug classes.
Debug.Assert() is executing only in Debug mode.
Trace.Assert() is executing in Debug and Release mode.

Here is an example:

        int i = 1 + 3;
        // Debug.Assert method in Debug mode fails, since i == 4
        Debug.Assert(i == 3);
        Debug.WriteLine(i == 3, "i is equal to 3");

        // Trace.Assert method in Release mode is not failing.
        Trace.Assert(i == 4);
        Trace.WriteLine(i == 4, "i is equla to 4");

        Console.WriteLine("Press a key to continue...");
        Console.ReadLine();

Run this code in Debug mode and then in Release mode.

enter image description here

You will notice that during Debug mode your code Debug.Assert statement fails, you get a message box showing the current stack trace of the application. This is not happening in Release mode since Trace.Assert() condition is true (i == 4).

WriteLine() method simply gives you an option of logging the information to Visual Studio output. enter image description here

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

What static analysis tools are available for C#?

Optimyth Software has just launched a static analysis service in the cloud www.checkinginthecloud.com. Just securely upload your code run the analysis and get the results. No hassles.

It supports several languages including C# more info can be found at wwww.optimyth.com

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

I have just faced this problem, and the solution is that the property "mail.smtp.user" should be your email (not username).

The example for gmail user:

properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

With thymeleaf you may add:

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>

React / JSX Dynamic Component Name

There is an official documentation about how to handle such situations is available here: https://facebook.github.io/react/docs/jsx-in-depth.html#choosing-the-type-at-runtime

Basically it says:

Wrong:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
    photo: PhotoStory,
    video: VideoStory
};

function Story(props) {
    // Wrong! JSX type can't be an expression.
    return <components[props.storyType] story={props.story} />;
}

Correct:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
    photo: PhotoStory,
    video: VideoStory
};

function Story(props) {
    // Correct! JSX type can be a capitalized variable.
    const SpecificStory = components[props.storyType];
    return <SpecificStory story={props.story} />;
}

Losing Session State

Had a problem on IIS 8 when retrieving Content via Ajax. The issue was that MaximumWorkerProcesses was set to 2 and Javascript opened 17 concurrent requests. That was more than the AppPool could handle and a new pool (without auth-data) was opened.

Solution was to Change MaximumWorkerProcesses to 0 in IIS -> Server -> Application Pools -> [myPool] -> Advanced Settings -> Process Model -> MaximumWorkerProcesses.

jQuery map vs. each

The each method is meant to be an immutable iterator, where as the map method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.

Another important thing to note is that the each function returns the original array while the map function returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.

For example:

var items = [1,2,3,4];

$.each(items, function() {
  alert('this is ' + this);
});

var newItems = $.map(items, function(i) {
  return i + 1;
});
// newItems is [2,3,4,5]

You can also use the map function to remove an item from an array. For example:

var items = [0,1,2,3,4,5,6,7,8,9];

var itemsLessThanEqualFive = $.map(items, function(i) {
  // removes all items > 5
  if (i > 5) 
    return null;
  return i;
});
// itemsLessThanEqualFive = [0,1,2,3,4,5]

You'll also note that the this is not mapped in the map function. You will have to supply the first parameter in the callback (eg we used i above). Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful.

map(arr, function(elem, index) {});
// versus 
each(arr, function(index, elem) {});

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

Sort Array of object by object field in Angular 6

Not tested but should work

 products.sort((a,b)=>a.title.rendered > b.title.rendered)

Merge DLL into EXE?

I answered a similar question for VB.NET. It shouldn't however be too hard to convert. You embedd the DLL's into your Ressource folder and on the first usage, the AppDomain.CurrentDomain.AssemblyResolve event gets fired.

If you want to reference it during development, just add a normal DLL reference to your project.

Embedd a DLL into a project

TypeError: $ is not a function WordPress

Other than noConflict, this is helpful too:

(function( $ ) {
    // Variables and DOM Caching using $.
    var body = $('body');
    console.log(body);
})( jQuery );

react button onClick redirect page

I was also having the trouble to route to a different view using navlink.

My implementation was as follows and works perfectly;

<NavLink tag='li'>
  <div
    onClick={() =>
      this.props.history.push('/admin/my- settings')
    }
  >
    <DropdownItem className='nav-item'>
      Settings
    </DropdownItem>
  </div>
</NavLink>

Wrap it with a div, assign the onClick handler to the div. Use the history object to push a new view.

iPhone viewWillAppear not firing

ViewWillAppear is an override method of UIViewController class so adding a subView will not call viewWillAppear, but when you present, push , pop, show , setFront Or popToRootViewController from a viewController then viewWillAppear for presented viewController will get called.

Pass correct "this" context to setTimeout callback?

There are ready-made shortcuts (syntactic sugar) to the function wrapper @CMS answered with. (Below assuming that the context you want is this.tip.)


ECMAScript 2015 (all common browsers and smartphones, Node.js 5.0.0+)

For virtually all javascript development (in 2020) you can use fat arrow functions, which are part of the ECMAScript 2015 (Harmony/ES6/ES2015) specification.

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value [...].

(param1, param2, ...rest) => { statements }

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(() => { this.tip.destroy(); }, 1000);
}

ECMAScript 5 (older browsers and smartphones, Node.js) and Prototype.js

If you target browser compatible with ECMA-262, 5th edition (ECMAScript 5) or Node.js, which (in 2020) means all common browsers as well as older browsers, you could use Function.prototype.bind. You can optionally pass any function arguments to create partial functions.

fun.bind(thisArg[, arg1[, arg2[, ...]]])

Again, in your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(this.tip.destroy.bind(this.tip), 1000);
}

The same functionality has also been implemented in Prototype (any other libraries?).

Function.prototype.bind can be implemented like this if you want custom backwards compatibility (but please observe the notes).


jQuery

If you are already using jQuery 1.4+, there's a ready-made function for explicitly setting the this context of a function.

jQuery.proxy(): Takes a function and returns a new one that will always have a particular context.

$.proxy(function, context[, additionalArguments])

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout($.proxy(this.tip.destroy, this.tip), 1000);
}

Underscore.js, lodash

It's available in Underscore.js, as well as lodash, as _.bind(...)1,2

bind Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, bind arguments to the function to pre-fill them, also known as partial application.

_.bind(function, object, [*arguments])

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(_.bind(this.tip.destroy, this.tip), 1000);
}

What is the difference between compare() and compareTo()?

Comparable interface contains a method called compareTo(obj) which takes only one argument and it compares itself with another instance or objects of the same class.

Comparator interface contains a method called compare(obj1,obj2) which takes two arguments and it compares the value of two objects from the same or different classes.

Adding new line of data to TextBox

If you use WinForms:

Use the AppendText(myTxt) method on the TextBox instead (.net 3.5+):

    private void button1_Click(object sender, EventArgs e)
    {
        string sent = chatBox.Text;

        displayBox.AppendText(sent);
        displayBox.AppendText(Environment.NewLine);

    }

Text in itself has typically a low memory footprint (you can say a lot within f.ex. 10kb which is "nothing"). The TextBox does not render all text that is in the buffer, only the visible part so you don't need to worry too much about lag. The slower operations are inserting text. Appending text is relatively fast.

If you need a more complex handling of the content you can use StringBuilder combined with the textbox. This will give you a very efficient way of handling text.

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

Wavy shape with css

Here's another way to do it :) The concept is to create a clip-path polygon with the wave as one side.

This approach is fairly flexible. You can change the position (left, right, top or bottom) in which the wave appears, change the wave function to any function(t) which maps to [0,1]). The polygon can also be used for shape-outside, which lets text flow around the wave when in 'left' or 'right' orientation.

At the end, an example you can uncomment which demonstrates animating the wave.

_x000D_
_x000D_
 _x000D_
_x000D_
function PolyCalc(f /*a function(t)  from [0, infinity) => [0, 1]*/, _x000D_
                  s, /*a slice function(y, i) from y [0,1] => [0, 1], with slice index, i, in [0, n]*/_x000D_
         w /*window size in seconds*/,_x000D_
                  n /*sample size*/,_x000D_
                  o /*orientation => left/right/top/bottom - the 'flat edge' of the polygon*/ _x000D_
                  ) _x000D_
{_x000D_
 this.polyStart = "polygon(";_x000D_
  this.polyLeft = this.polyStart + "0% 0%, "; //starts in the top left corner_x000D_
  this.polyRight = this.polyStart + "100% 0%, "; //starts in the top right corner_x000D_
  this.polyTop = this.polyStart + "0% 0%, "; // starts in the top left corner_x000D_
  this.polyBottom = this.polyStart + "0% 100%, ";//starts in the bottom left corner_x000D_
  _x000D_
  var self = this;_x000D_
  self.mapFunc = s;_x000D_
  this.func = f;_x000D_
  this.window = w;_x000D_
  this.count = n;_x000D_
  var dt = w/n;  _x000D_
_x000D_
  switch(o) {_x000D_
    case "top":_x000D_
      this.poly = this.polyTop; break;_x000D_
    case "bottom":_x000D_
      this.poly = this.polyBottom; break;_x000D_
   case "right":_x000D_
     this.poly = this.polyRight; break;_x000D_
   case "left":_x000D_
   default:_x000D_
    this.poly = this.polyLeft; break;_x000D_
    }_x000D_
    _x000D_
  this.CalcPolygon = function(t) {_x000D_
   var p = this.poly;_x000D_
    for (i = 0; i < this.count; i++) {_x000D_
      x = 100 * i/(this.count-1.0);_x000D_
      y = this.func(t + i*dt);_x000D_
      if (typeof self.mapFunc !== 'undefined')_x000D_
       y=self.mapFunc(y, i);_x000D_
      y*=100;_x000D_
      switch(o) {_x000D_
        case "top": _x000D_
          p += x + "% " + y + "%, "; break;_x000D_
        case "bottom":_x000D_
          p += x + "% " + (100-y) + "%, "; break;_x000D_
       case "right":_x000D_
         p += (100-y) + "% " + x + "%, "; break;_x000D_
       case "left":_x000D_
        default:_x000D_
         p += y + "% " + x + "%, "; break;          _x000D_
      }_x000D_
    }_x000D_
    _x000D_
    switch(o) { _x000D_
      case "top":_x000D_
        p += "100% 0%)"; break;_x000D_
      case "bottom":_x000D_
        p += "100% 100%)";_x000D_
        break;_x000D_
     case "right":_x000D_
       p += "100% 100%)"; break;_x000D_
     case "left":_x000D_
      default:_x000D_
       p += "0% 100%)"; break;_x000D_
    }_x000D_
    _x000D_
    return p;_x000D_
  }_x000D_
};_x000D_
_x000D_
var text = document.querySelector("#text");_x000D_
var divs = document.querySelectorAll(".wave");_x000D_
var freq=2*Math.PI; //angular frequency in radians/sec_x000D_
var windowWidth = 1; //the time domain window which determines the range from [t, t+windowWidth] that will be evaluated to create the polygon_x000D_
var sampleSize = 60;_x000D_
divs.forEach(function(wave) {_x000D_
  var loc = wave.classList[1];_x000D_
_x000D_
  var polyCalc = new PolyCalc(_x000D_
   function(t) { //The time domain wave function_x000D_
     return (Math.sin(freq * t) + 1)/2; //sine is [-1, -1], so we remap to [0,1]_x000D_
    },_x000D_
    function(y, i) { //slice function, takes the time domain result and the slice index and returns a new value in [0, 1]  _x000D_
      return MapRange(y, 0.0, 1.0, 0.65, 1.0);  //Here we adjust the range of the wave to 'flatten' it out a bit.  We don't use the index in this case, since it is irrelevant_x000D_
    },_x000D_
    windowWidth, //1 second, which with an angular frequency of 2pi rads/sec will produce one full period._x000D_
    sampleSize, //the number of samples to make, the larger the number, the smoother the curve, but the more pionts in the final polygon_x000D_
    loc //the location_x000D_
  );_x000D_
  _x000D_
    var polyText = polyCalc.CalcPolygon(0);_x000D_
    wave.style.clipPath = polyText;_x000D_
    wave.style.shapeOutside = polyText;_x000D_
    wave.addEventListener("click",function(e) {document.querySelector("#polygon").innerText = polyText;});_x000D_
  });_x000D_
_x000D_
function MapRange(value, min, max, newMin, newMax) {_x000D_
  return value * (newMax - newMin)/(max-min) + newMin;_x000D_
}_x000D_
_x000D_
//Animation - animate the wave by uncommenting this section_x000D_
//Also demonstrates a slice function which uses the index of the slice to alter the output for a dampening effect._x000D_
/*_x000D_
var t = 0;_x000D_
var speed = 1/180;_x000D_
_x000D_
var polyTop = document.querySelector(".top");_x000D_
_x000D_
var polyTopCalc = new PolyCalc(_x000D_
   function(t) {_x000D_
     return (Math.sin(freq * t) + 1)/2;_x000D_
    },_x000D_
    function(y, i) {       _x000D_
      return MapRange(y, 0.0, 1.0, (sampleSize-i)/sampleSize, 1.0);_x000D_
    },_x000D_
    windowWidth, sampleSize, "top"_x000D_
  );_x000D_
_x000D_
function animate() {_x000D_
  var polyT = polyTopCalc.CalcPolygon(t);    _x000D_
    t+= speed;_x000D_
    polyTop.style.clipPath = polyT;    _x000D_
    requestAnimationFrame(animate);_x000D_
}_x000D_
_x000D_
requestAnimationFrame(animate);_x000D_
*/
_x000D_
div div {_x000D_
  padding:10px;_x000D_
  /*overflow:scroll;*/_x000D_
}_x000D_
_x000D_
.left {_x000D_
  height:100%;_x000D_
  width:35%;_x000D_
  float:left;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  height:200px;_x000D_
  width:35%;_x000D_
  float:right;_x000D_
}_x000D_
_x000D_
.top { _x000D_
  width:100%;_x000D_
  height: 200px;  _x000D_
}_x000D_
_x000D_
.bottom {_x000D_
  width:100%;_x000D_
  height:200px;_x000D_
}_x000D_
_x000D_
.green {_x000D_
  background:linear-gradient(to bottom, #b4ddb4 0%,#83c783 17%,#52b152 33%,#008a00 67%,#005700 83%,#002400 100%); _x000D_
} _x000D_
_x000D_
.mainContainer {_x000D_
  width:100%;_x000D_
  float:left;_x000D_
}_x000D_
_x000D_
#polygon {_x000D_
  padding-left:20px;_x000D_
  margin-left:20px;_x000D_
  width:100%;_x000D_
}
_x000D_
<div class="mainContainer">_x000D_
_x000D_
  <div class="wave top green">_x000D_
    Click to see the polygon CSS_x000D_
  </div>_x000D_
  _x000D_
  <!--div class="wave left green">_x000D_
  </div-->_x000D_
  <!--div class="wave right green">_x000D_
  </div-->  _x000D_
  <!--div class="wave bottom green"></div-->  _x000D_
</div>_x000D_
<div id="polygon"></div>
_x000D_
_x000D_
_x000D_

Windows path in Python

In case you'd like to paste windows path from other source (say, File Explorer) - you can do so via input() call in python console:

>>> input()
D:\EP\stuff\1111\this_is_a_long_path\you_dont_want\to_type\or_edit_by_hand
'D:\\EP\\stuff\\1111\\this_is_a_long_path\\you_dont_want\\to_type\\or_edit_by_hand'

Then just copy the result

Laravel migration table field's type change

update: 31 Oct 2018, Still usable on laravel 5.7 https://laravel.com/docs/5.7/migrations#modifying-columns

To make some change to existing db, you can modify column type by using change() in migration.

This is what you could do

Schema::table('orders', function ($table) {
    $table->string('category_id')->change();
});

please note you need to add doctrine/dbal dependency to composer.json for more information you can find it here http://laravel.com/docs/5.1/migrations#modifying-columns

Capturing URL parameters in request.GET

When a URL is like domain/search/?q=haha, you would use request.GET.get('q', '').

q is the parameter you want, and '' is the default value if q isn't found.

However, if you are instead just configuring your URLconf**, then your captures from the regex are passed to the function as arguments (or named arguments).

Such as:

(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),

Then in your views.py you would have

def profile_page(request, username):
    # Rest of the method

Commenting in a Bash script inside a multiline command

The backslash escapes the #, interpreting it as its literal character instead of a comment character.

How can you use php in a javascript function

you use script in php..

<?php

        $num = 1;
        echo $num;

    echo '<input type="button"
           name="lol" 
           value="Click to increment"
           onclick="Inc()" />
    <br>
    <script>
        function Inc()
        {';
            $num = 2;
            echo $num;

        echo '}
    </script>';
?>

Use FontAwesome or Glyphicons with css :before

@keithwyland answer is great. Here's a SCSS mixin:

@mixin font-awesome($content){
    font-family: FontAwesome;
    font-weight: normal;
    font-style: normal;
    display: inline-block;
    text-decoration: inherit;
    content: $content;
}

Usage:

@include font-awesome("\f054");

The easiest way to transform collection to array?

If you use it more than once or in a loop, you could define a constant

public static final Foo[] FOO = new Foo[]{};

and do the conversion it like

Foo[] foos = fooCollection.toArray(FOO);

The toArray method will take the empty array to determine the correct type of the target array and create a new array for you.


Here's my proposal for the update:

Collection<Foo> foos = new ArrayList<Foo>();
Collection<Bar> temp = new ArrayList<Bar>();
for (Foo foo:foos) 
    temp.add(new Bar(foo));
Bar[] bars = temp.toArray(new Bar[]{});

Descending order by date filter in AngularJs

You can prefix the argument in orderBy with a '-' to have descending order instead of ascending. I would write it like this:

<div class="recent" 
   ng-repeat="reader in book.reader | orderBy: '-created_at' | limitTo: 1">
</div>

This is also stated in the documentation for the filter orderBy.

How can I represent an 'Enum' in Python?

The new standard in Python is PEP 435, so an Enum class will be available in future versions of Python:

>>> from enum import Enum

However to begin using it now you can install the original library that motivated the PEP:

$ pip install flufl.enum

Then you can use it as per its online guide:

>>> from flufl.enum import Enum
>>> class Colors(Enum):
...     red = 1
...     green = 2
...     blue = 3
>>> for color in Colors: print color
Colors.red
Colors.green
Colors.blue

install beautiful soup using pip

pip is a command line tool, not Python syntax.

In other words, run the command in your console, not in the Python interpreter:

pip install beautifulsoup4

You may have to use the full path:

C:\Python27\Scripts\pip install beautifulsoup4

or even

C:\Python27\Scripts\pip.exe install beautifulsoup4

Windows will then execute the pip program and that will use Python to install the package.

Another option is to use the Python -m command-line switch to run the pip module, which then operates exactly like the pip command:

python -m pip install beautifulsoup4

or

python.exe -m pip install beautifulsoup4

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):

def getAny(dic, keys, default=None):
    return (keys or default) and dic.get(keys[0], 
                                         getAny( dic, keys[1:], default=default))

or even better, without recursion and more clear:

def getAny(dic, keys, default=None):
    for k in keys: 
        if k in dic:
           return dic[k]
    return default

Then that could be used in a way similar to the dict.get method, like:

getAny(myDict, keySet)

and even have a default result in case of no keys found at all:

getAny(myDict, keySet, "not found")

What does [object Object] mean?

It's the value returned by that object's toString() function.


I understand what you're trying to do, because I answered your question yesterday about determining which div is visible. :)
The whichIsVisible() function returns an actual jQuery object, because I thought that would be more programmatically useful. If you want to use this function for debugging purposes, you can just do something like this:

function whichIsVisible_v2()
{
    if (!$1.is(':hidden')) return '#1';
    if (!$2.is(':hidden')) return '#2';
}

That said, you really should be using a proper debugger rather than alert() if you're trying to debug a problem. If you're using Firefox, Firebug is excellent. If you're using IE8, Safari, or Chrome, they have built-in debuggers.

Add views in UIStackView programmatically

Swift 5 version of Oleg Popov's answer, which is based on user1046037's answer

//Image View
let imageView = UIImageView()
imageView.backgroundColor = UIColor.blue
imageView.heightAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.image = UIImage(named: "buttonFollowCheckGreen")

//Text Label
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.yellow
textLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text  = "Hi World"
textLabel.textAlignment = .center

//Stack View
let stackView   = UIStackView()
stackView.axis  = NSLayoutConstraint.Axis.vertical
stackView.distribution  = UIStackView.Distribution.equalSpacing
stackView.alignment = UIStackView.Alignment.center
stackView.spacing   = 16.0

stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(textLabel)
stackView.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(stackView)

//Constraints
stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

Can typescript export a function?

If you are using this for Angular, then export a function via a named export. Such as:

function someFunc(){}

export { someFunc as someFuncName }

otherwise, Angular will complain that object is not a function.

Unicode character as bullet for list-item in CSS

To add a star use the Unicode character 22C6.

I added a space to make a little gap between the li and the star. The code for space is A0.

li:before {
    content: '\22C6\A0';
}

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.

I can't figure out exactly what's there, yet ...

edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.

A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.

If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.

How to get all columns' names for all the tables in MySQL?

To list all the fields from a table in MySQL:

select * 
  from information_schema.columns 
 where table_schema = 'your_DB_name' 
   and table_name = 'Your_tablename'

How to recognize swipe in all 4 directions

First create a baseViewController and add viewDidLoad this code "swift4":

class BaseViewController: UIViewController {             

     override func viewDidLoad() {
         super.viewDidLoad()
         let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
         swipeRight.direction = UISwipeGestureRecognizerDirection.right
         self.view.addGestureRecognizer(swipeRight)
         let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
         swipeLeft.direction = UISwipeGestureRecognizerDirection.left
         self.view.addGestureRecognizer(swipeLeft)
     }

     // Example Tabbar 5 pages
     @objc func swiped(_ gesture: UISwipeGestureRecognizer) {
         if gesture.direction == .left {
            if (self.tabBarController?.selectedIndex)! < 5 {
                self.tabBarController?.selectedIndex += 1
            }
         } else if gesture.direction == .right {
             if (self.tabBarController?.selectedIndex)! > 0 {
                 self.tabBarController?.selectedIndex -= 1
             }
         }
     }  
}

And use this baseController class:

class YourViewController: BaseViewController {
    // its done. Swipe successful
    //Now you can use all the Controller you have created without writing any code.    
}

How to show disable HTML select option in by default?

we can disable using this technique.

<select class="form-control" name="option_select">
  <option selected="true" disabled="disabled">Select option </option>
  <option value="Option A">Option A</option>
  <option value="Option B">Option B</option>
  <option value="Option C">Option C</option>
</select>

Compare two date formats in javascript/jquery

As in your example, the fit_start_time is not later than the fit_end_time.

Try it the other way round:

var fit_start_time  = $("#fit_start_time").val(); //2013-09-5
var fit_end_time    = $("#fit_end_time").val(); //2013-09-10

if(Date.parse(fit_start_time) <= Date.parse(fit_end_time)){
    alert("Please select a different End Date.");
}

Update

Your code implies that you want to see the alert with the current variables you have. If this is the case then the above code is correct. If you're intention (as per the implication of the alert message) is to make sure their fit_start_time variable is a date that is before the fit_end_time, then your original code is fine, but the data you're getting from the jQuery .val() methods is not parsing correctly. It would help if you gave us the actual HTML which the selector is sniffing at.

SQL where datetime column equals today's date?

There might be another way, but this should work:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET] 
WHERE day(Submission_date)=day(now) and 
     month(Submission_date)=month(now)
     and year(Submission_date)=year(now)

Converting Date and Time To Unix Timestamp

Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...

let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);

to prove it:

let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);

enjoy!

How do I get a decimal value when using the division operator in Python?

You could also try adding a ".0" at the end of the number.

4.0/100.0

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

In fact I have the problem with a form on each row of a table, with javascript (actually jquery) :

like Lothre1 said, "some browsers in the process of rendering will close form tag right after the declaration leaving inputs outside of the element"

which makes my input fields OUTSIDE the form, therefore I can't access the children of my form through the DOM with JAVASCRIPT..

typically, the following JQUERY code won't work :

$('#id_form :input').each(function(){/*action*/});
// this is supposed to select all inputS 
// within the form that has an id ='id_form'

BUT the above exemple doesn't work with the rendered HTML :

<table>
    <form id="id_form"></form>
    <tr id="tr_id">
    <td><input type="text"/></td>
    <td><input type="submit"/></td>
    </tr>
    </table>

I'm still looking for a clean solution (though using the TR 'id' parameter to walk the DOM would fix this specific problem)

dirty solution would be (for jquery):

$('#tr_id :input').each(function(){/*action*/});
// this will select all the inputS
// fields within the TR with the id='tr_id'

the above exemple will work, but it's not really "clean", because it refers to the TR instead of the FORM, AND it requires AJAX ...

EDIT : complete process with jquery/ajax would be :

//init data string
// the dummy init value (1=1)is just here 
// to avoid dealing with trailing &
// and should not be implemented
// (though it works)
var data_str = '1=1'; 
// for each input in the TR
$('#tr_id :input').each(function(){

 //retrieve field name and value from the DOM
 var field = $(this).attr('name');
 var value = $(this).val();

 //iterate the string to pass the datas
 // so in the end it will render s/g like
 // "1=1&field1_name=value1&field2_name=value2"...
 data_str += '&' + field + '=' + value; 


});

//Sendind fields datawith ajax 
// to be treated 
$.ajax({
 type:"POST",
 url: "target_for_the_form_treatment",
 data:data_string,
 success:function(msg){
    /*actions on success of the request*/
 });
});

this way, the "target_for_the_form_treatment" should receive POST data as if a form was sent to him (appart from the post[1] = 1, but to implement this solution i would recommand dealing with the trailing '&' of the data_str instead).

still I don't like this solution, but I'm forced to use TABLE structure because of the dataTables jquery plugin...

Equivalent of Oracle's RowID in SQL Server

Check out the new ROW_NUMBER function. It works like this:

SELECT ROW_NUMBER() OVER (ORDER BY EMPID ASC) AS ROWID, * FROM EMPLOYEE

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

T-SQL to list all the user mappings with database roles/permissions for a Login

Did you sort this? I just found this code here:

http://www.pythian.com/news/29665/httpconsultingblogs-emc-comjamiethomsonarchive20070209sql-server-2005_3a00_-view-all-permissions-_2800_2_2900_-aspx/

I think I'll need to do a bit of tweaking, but essentially this has sorted it for me!

I hope it does for you too!

J

Enable & Disable a Div and its elements in Javascript

If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.

try this.

$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');

Typescript empty object for a typed variable

Caveats

Here are two worthy caveats from the comments.

Either you want user to be of type User | {} or Partial<User>, or you need to redefine the User type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. – jcalz

I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property Username is left undefined, while the type annotation is saying it can't be undefined. – Ian Liu Rodrigues

Answer

One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.

type User = {
    Username: string;
    Email: string;
}

const user01 = {} as User;
const user02 = <User>{};

user01.Email = "[email protected]";

Here is a working example for you.

Here are type assertions working with suggestion.

Http 415 Unsupported Media type error with JSON

I know this is way too late to help the OP with his problem, but to all of us who is just encountering this problem, I had solved this issue by removing the constructor with parameters of my Class which was meant to hold the json data.

How can I test a change made to Jenkinsfile locally?

A bit late to the party, but that's why I wrote jenny, a small reimplementation of some core Jenkinsfile steps. (https://github.com/bmustiata/jenny)

Attach to a processes output for viewing

How would I 'attach' a console/terminal-view to an applications output so I can see what it may be saying?

About this question, I know it is possible to catch the output, even when you didn't launch sceen command before launching the processus.

While I never tried it, I've found an interesting article which explains how to do using GDB (and without restarting your process).

redirecting-output-from-a-running-process

Basically:

  1. Check the open files list for your process, thanks to /proc/xxx/fd
  2. Attach your process with GDB
  3. While it is paused, close the file you are interested in, calling close() function (you can any function of your process in GDB. I suspect you need debug symbols in your process..)
  4. Open the a new file calling the create() or open() function. (Have a look in comments at the end, you'll see people suggest to use dup2() to ensure the same handle will be in use)
  5. Detach the process and let in run.

By the way, if you are running a linux OS on i386 box, comments are talking about a better tool to redirect output to a new console : 'retty' . If so, consider its use.

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

Commenting out a set of lines in a shell script

The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

I ran into the 'Expecting: ANY PRIVATE KEY' error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).

The cause of the problem was that I'd saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.

ModuleNotFoundError: What does it mean __main__ is not a package?

The problem still not resolved after remove the '.', then it start points the error to my folder. As i added this folder first time then i restarted the PyCharm and it automatically resolved the issue

Indexes of all occurrences of character in a string

A class for splitting strings I came up with. A short test is provided at the end.

SplitStringUtils.smartSplitToShorterStrings(String str, int maxLen, int maxParts) will split by spaces without breaking words, if possible, and if not, will split by indexes according to maxLen.

Other methods provided to control how it is split: bruteSplitLimit(String str, int maxLen, int maxParts), spaceSplit(String str, int maxLen, int maxParts).

public class SplitStringUtils {

  public static String[] smartSplitToShorterStrings(String str, int maxLen, int maxParts) {
    if (str.length() <= maxLen) {
      return new String[] {str};
    }
    if (str.length() > maxLen*maxParts) {
      return bruteSplitLimit(str, maxLen, maxParts);
    }

    String[] res = spaceSplit(str, maxLen, maxParts);
    if (res != null) {
      return res;
    }

    return bruteSplitLimit(str, maxLen, maxParts);
  }

  public static String[] bruteSplitLimit(String str, int maxLen, int maxParts) {
    String[] bruteArr = bruteSplit(str, maxLen);
    String[] ret = Arrays.stream(bruteArr)
          .limit(maxParts)
          .collect(Collectors.toList())
          .toArray(new String[maxParts]);
    return ret;
  }

  public static String[] bruteSplit(String name, int maxLen) {
    List<String> res = new ArrayList<>();
    int start =0;
    int end = maxLen;
    while (end <= name.length()) {
      String substr = name.substring(start, end);
      res.add(substr);
      start = end;
      end +=maxLen;
    }
    String substr = name.substring(start, name.length());
    res.add(substr);
    return res.toArray(new String[res.size()]);
  }

  public static String[] spaceSplit(String str, int maxLen, int maxParts) {
    List<Integer> spaceIndexes = findSplitPoints(str, ' ');
    List<Integer> goodSplitIndexes = new ArrayList<>();
    int goodIndex = -1; 
    int curPartMax = maxLen;
    for (int i=0; i< spaceIndexes.size(); i++) {
      int idx = spaceIndexes.get(i);
      if (idx < curPartMax) {
        goodIndex = idx;
      } else {
        goodSplitIndexes.add(goodIndex+1);
        curPartMax = goodIndex+1+maxLen;
      }
    }
    if (goodSplitIndexes.get(goodSplitIndexes.size()-1) != str.length()) {
      goodSplitIndexes.add(str.length());
    }
    if (goodSplitIndexes.size()<=maxParts) {
      List<String> res = new ArrayList<>();
      int start = 0;
      for (int i=0; i<goodSplitIndexes.size(); i++) {
        int end = goodSplitIndexes.get(i);
        if (end-start > maxLen) {
          return null;
        }
        res.add(str.substring(start, end));
        start = end;
      }
      return res.toArray(new String[res.size()]);
    }
    return null;
  }


  private static List<Integer> findSplitPoints(String str, char c) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == c) {
        list.add(i);
      }
    }
    list.add(str.length());
    return list;
  }
}

Simple test code:

  public static void main(String[] args) {
    String [] testStrings = {
        "123",
        "123 123 123 1123 123 123 123 123 123 123",
        "123 54123 5123 513 54w567 3567 e56 73w45 63 567356 735687 4678 4678 u4678 u4678 56rt64w5 6546345",
        "1345678934576235784620957029356723578946",
        "12764444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444",
        "3463356 35673567567 3567 35 3567 35 675 653 673567 777777777777777777777777777777777777777777777777777777777777777777"
    };

    int max = 35;
    int maxparts = 2;


    for (String str : testStrings) {
      System.out.println("TEST\n    |"+str+"|");
      printSplitDetails(max, maxparts);
      String[] res = smartSplitToShorterStrings(str, max, maxparts);
      for (int i=0; i< res.length;i++) {
        System.out.println("  "+i+": "+res[i]);
      }
      System.out.println("===========================================================================================================================================================");
    }

  }

  static void printSplitDetails(int max, int maxparts) {
    System.out.print("  X: ");
    for (int i=0; i<max*maxparts; i++) {
      if (i%max == 0) {
        System.out.print("|");
      } else {
        System.out.print("-");
      }
    }
    System.out.println();
  }

How do I perform HTML decoding/encoding using Python/Django?

With the standard library:

  • HTML Escape

    try:
        from html import escape  # python 3.x
    except ImportError:
        from cgi import escape  # python 2.x
    
    print(escape("<"))
    
  • HTML Unescape

    try:
        from html import unescape  # python 3.4+
    except ImportError:
        try:
            from html.parser import HTMLParser  # python 3.x (<3.4)
        except ImportError:
            from HTMLParser import HTMLParser  # python 2.x
        unescape = HTMLParser().unescape
    
    print(unescape("&gt;"))
    

Get filename in batch for loop

I am a little late but I used this:

dir /B *.* > dir_file.txt

then you can make a simple FOR loop to extract the file name and use them. e.g:

for /f "tokens=* delims= " %%a in (dir_file.txt) do (
gawk -f awk_script_file.awk %%a
)

or store them into Vars (!N1!, !N2!..!Nn!) for later use. e.g:

set /a N=0
for /f "tokens=* delims= " %%a in (dir_file.txt) do (
set /a N+=1
set v[!N!]=%%a
)

How to add CORS request in header in Angular 5

Make the header looks like this for HttpClient in NG5:

let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'apikey': this.apikey,
        'appkey': this.appkey,
      }),
      params: new HttpParams().set('program_id', this.program_id)
    };

You will be able to make api call with your localhost url, it works for me ..

  • Please never forget your params columnd in the header: such as params: new HttpParams().set('program_id', this.program_id)

C++ STL Vectors: Get iterator from index?

Also; auto it = std::next(v.begin(), index);

Update: Needs a C++11x compliant compiler

Batch not-equal (inequality) operator

Use NEQ instead.

if "asdf" NEQ "fdas" echo asdf

How to access custom attributes from event object in React?

I think it's recommended to bind all methods where you need to use this.setState method which is defined in the React.Component class, inside the constructor, in your case you constructor should be like

    constructor() {
        super()
        //This binding removeTag is necessary to make `this` work in the callback
        this.removeTag = this.removeTag.bind(this)
    }
    removeTag(event){
        console.log(event.target)
        //use Object destructuring to fetch all element values''
        const {style, dataset} = event.target
        console.log(style)
        console.log(dataset.tag)
    }
   render() {
   ...
      <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
   ...},

For more reference on Object destructuring https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

Using CookieContainer with WebClient class

I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

internal static class MyWebRequestCreator
{
    private static IWebRequestCreate myCreator;

    public static IWebRequestCreate MyHttp
    {
        get
        {
            if (myCreator == null)
            {
                myCreator = new MyHttpRequestCreator();
            }
            return myCreator;
        }
    }

    private class MyHttpRequestCreator : IWebRequestCreate
    {
        public WebRequest Create(Uri uri)
        {
            var req = System.Net.WebRequest.CreateHttp(uri);
            req.CookieContainer = new CookieContainer();
            return req;
        }
    }
}

Now all you have to do is opt in for which domains you want to use this:

    WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);

That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

How to run server written in js with Node.js

Nodejs is a scripting language (like Python or Ruby, and unlike PHP or C++). To run your code, you need to enter a command in the terminal / shell / command prompt. Look for an application shortcut in your operating system by one of those names.

The command to run in the terminal will be

node server.js

But you will first need to browse in the terminal to the same folder as the file server.js. The syntax for using the terminal varies by operating system, look for its documentation.

Find duplicate lines in a file and count how many time each line was duplicated?

In windows using "Windows PowerShell" I used the command mentioned below to achieve this

Get-Content .\file.txt | Group-Object | Select Name, Count

Also we can use the where-object Cmdlet to filter the result

Get-Content .\file.txt | Group-Object | Where-Object { $_.Count -gt 1 } | Select Name, Count

Can jQuery get all CSS styles associated with an element?

@marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:

for (var i = 0; i < css.length; i += 1) {
    s[css[i]] = css.getPropertyValue(css[i]);
}

Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

Check if a value exists in pandas dataframe index

df = pandas.DataFrame({'g':[1]}, index=['isStop'])

#df.loc['g']

if 'g' in df.index:
    print("find g")

if 'isStop' in df.index:
    print("find a") 

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

This is how I do it:

from datetime import datetime
from time import mktime

dt = datetime.now()
sec_since_epoch = mktime(dt.timetuple()) + dt.microsecond/1000000.0

millis_since_epoch = sec_since_epoch * 1000

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

My problem solved by changing jdk to default , like this. Open Jdk was installed but don't know why intellij set configuration to java-8-openjdk-amd64. This was the problem.I have changed to default-java and no more red error.

enter image description here

How can I set the default value for an HTML <select> element?

I prefer this:

<select>
   <option selected hidden>Choose here</option>
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="3">Three</option>
   <option value="4">Four</option>
   <option value="5">Five</option>
</select>

'Choose here' disappears after an option has been selected.

How to apply CSS page-break to print a table with lots of rows?

this is working for me:

<td>
  <div class="avoid">
    Cell content.
  </div>
</td>
...
<style type="text/css">
  .avoid {
    page-break-inside: avoid !important;
    margin: 4px 0 4px 0;  /* to keep the page break from cutting too close to the text in the div */
  }
</style>

From this thread: avoid page break inside row of table

string encoding and decoding?

That's because your input string can’t be converted according to the encoding rules (strict by default).

I don't know, but I always encoded using directly unicode() constructor, at least that's the ways at the official documentation:

unicode(your_str, errors="ignore")

How to set a default value in react-select

If you've come here for react-select v2, and still having trouble - version 2 now only accepts an object as value, defaultValue, etc.

That is, try using value={{value: 'one', label: 'One'}}, instead of just value={'one'}.

How to dynamically add and remove form fields in Angular 2

add and remove text input element dynamically any one can use this this will work Type of Contact Balance Fund Equity Fund Allocation Allocation % is required! Remove Add Contact

userForm: FormGroup;
  public contactList: FormArray;
  // returns all form groups under contacts
  get contactFormGroup() {
    return this.userForm.get('funds') as FormArray;
  }
  ngOnInit() {
    this.submitUser();
  }
  constructor(public fb: FormBuilder,private router: Router,private ngZone: NgZone,private userApi: ApiService) { }
  // contact formgroup
  createContact(): FormGroup {
    return this.fb.group({
      fundName: ['', Validators.compose([Validators.required])], // i.e Email, Phone
      allocation: [null, Validators.compose([Validators.required])]
    });
  }


  // triggered to change validation of value field type
  changedFieldType(index) {
    let validators = null;

    validators = Validators.compose([
      Validators.required,
      Validators.pattern(new RegExp('^\\+[0-9]?()[0-9](\\d[0-9]{9})$')) // pattern for validating international phone number
    ]);

    this.getContactsFormGroup(index).controls['allocation'].setValidators(
      validators
    );

    this.getContactsFormGroup(index).controls['allocation'].updateValueAndValidity();
  }

  // get the formgroup under contacts form array
  getContactsFormGroup(index): FormGroup {
    // this.contactList = this.form.get('contacts') as FormArray;
    const formGroup = this.contactList.controls[index] as FormGroup;
    return formGroup;
  }

  submitUser() {
    this.userForm = this.fb.group({
      first_name: ['', [Validators.required]],
      last_name: [''],
      email: ['', [Validators.required]],
      company_name: ['', [Validators.required]],
      license_start_date: ['', [Validators.required]],
      license_end_date: ['', [Validators.required]],
      gender: ['Male'],
      funds: this.fb.array([this.createContact()])
    })
    this.contactList = this.userForm.get('funds') as FormArray;
  }
  addContact() {
    this.contactList.push(this.createContact());
  }
  removeContact(index) {
    this.contactList.removeAt(index);
  }

C++ array initialization

Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++.

Since this initalizer is universal, for bool array you don't really need a different "syntax". 0 works as an initializer for bool type as well, so

bool myBoolArray[ARRAY_SIZE] = { 0 };

is guaranteed to initialize the entire array with false. As well as

char* myPtrArray[ARRAY_SIZE] = { 0 };

in guaranteed to initialize the whole array with null-pointers of type char *.

If you believe it improves readability, you can certainly use

bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };

but the point is that = { 0 } variant gives you exactly the same result.

However, in C++ = { 0 } might not work for all types, like enum types, for example, which cannot be initialized with integral 0. But C++ supports the shorter form

T myArray[ARRAY_SIZE] = {};

i.e. just an empty pair of {}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.

How to convert empty spaces into null values, using SQL Server?

Maybe something like this?

UPDATE [MyTable]
SET [SomeField] = NULL
WHERE [SomeField] is not NULL
AND LEN(LTRIM(RTRIM([SomeField]))) = 0

Android SDK location

If you only installed Xamarin with Visual Studio setup, the android SDK location is :

C:\Program Files (x86)\Android\android-sdk

You can find it in Android SDK Manager as said Raj Asapu

In visual Studio : Android SDK Manger from Visual Studio

Note : you should not use Program Files path to install Android Studio due to the space in path ! Android studio setup after Xamarin

How to store Java Date to Mysql datetime with JPA

Are you perhaps using java.sql.Date? While that has millisecond granularity as a Java class (it is a subclass of java.util.Date, bad design decision), it will be interpreted by the JDBC driver as a date without a time component. You have to use java.sql.Timestamp instead.

When using a Settings.settings file in .NET, where is the config actually stored?

All your settings are stored in the respective .config file.

The .settings file simply provides a strongly typed class for a set of settings that belong together, but the actual settings are stored in app.config or a .config file in your application.

If you add a .settings file, an app.config will be automatically added to house the settings if you don't already have one.

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

Adding headers when using httpClient.GetAsync

Following the greenhoorn's answer, you can use "Extensions" like this:

  public static class HttpClientExtensions
    {
        public static HttpClient AddTokenToHeader(this HttpClient cl, string token)
        {
            //int timeoutSec = 90;
            //cl.Timeout = new TimeSpan(0, 0, timeoutSec);
            string contentType = "application/json";
            cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
            cl.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token));
            var userAgent = "d-fens HttpClient";
            cl.DefaultRequestHeaders.Add("User-Agent", userAgent);
            return cl;
        }
    }

And use:

string _tokenUpdated = "TOKEN";
HttpClient _client;
_client.AddTokenToHeader(_tokenUpdated).GetAsync("/api/values")

JSONResult to String

You can also use Json.NET.

return JsonConvert.SerializeObject(jsonResult.Data);

How do I POST urlencoded form data with $http without jQuery?

you need to post plain javascript object, nothing else

           var request = $http({
                method: "post",
                url: "process.cfm",
                transformRequest: transformRequestAsFormPost,
                data: { id: 4, name: "Kim" }
            });

            request.success(
                function( data ) {
                    $scope.localData = data;
                }
            );

if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side

How to return a result from a VBA function

For non-object return types, you have to assign the value to the name of your function, like this:

Public Function test() As Integer
    test = 1
End Function

Example usage:

Dim i As Integer
i = test()

If the function returns an Object type, then you must use the Set keyword like this:

Public Function testRange() As Range
    Set testRange = Range("A1")
End Function

Example usage:

Dim r As Range
Set r = testRange()

Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:

Function test(ByVal justReturnOne As Boolean) As Integer
    If justReturnOne Then
        test = 1
        Exit Function
    End If
    'more code...
    test = 2
End Function

Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx

JWT refresh token flow

Below are the steps to do revoke your JWT access token:

  1. When you do log in, send 2 tokens (Access token, Refresh token) in response to the client.
  2. The access token will have less expiry time and Refresh will have long expiry time.
  3. The client (Front end) will store refresh token in his local storage and access token in cookies.
  4. The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token.
  5. Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token.
  6. Once the refresh token is expired, the User will be logged out.

Please let me know if you need more details, I can share the code (Java + Spring boot) as well.

For your questions:

Q1: It's another JWT with fewer claims put in with long expiry time.

Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.

Q3: Yes, Correct

How to tar certain file types in all subdirectories?

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -I 'pigz -9' -cf target.tgz

for multicore or just for one core:

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -czf target.tgz

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

elasticsearch bool query combine must with OR

I recently had to solve this problem too, and after a LOT of trial and error I came up with this (in PHP, but maps directly to the DSL):

'query' => [
    'bool' => [
        'should' => [
            ['prefix' => ['name_first' => $query]],
            ['prefix' => ['name_last' => $query]],
            ['prefix' => ['phone' => $query]],
            ['prefix' => ['email' => $query]],
            [
                'multi_match' => [
                    'query' => $query,
                    'type' => 'cross_fields',
                    'operator' => 'and',
                    'fields' => ['name_first', 'name_last']
                ]
            ]
        ],
        'minimum_should_match' => 1,
        'filter' => [
            ['term' => ['state' => 'active']],
            ['term' => ['company_id' => $companyId]]
        ]
    ]
]

Which maps to something like this in SQL:

SELECT * from <index> 
WHERE (
    name_first LIKE '<query>%' OR
    name_last LIKE '<query>%' OR
    phone LIKE  '<query>%' OR
    email LIKE '<query>%'
)
AND state = 'active'
AND company_id = <query>

The key in all this is the minimum_should_match setting. Without this the filter totally overrides the should.

Hope this helps someone!

Why is __dirname not defined in node REPL?

I was also trying to join my path using path.join(__dirname, 'access.log') but it was throwing the same error.

Here is how I fixed it:

I first imported the path package and declared a variable named __dirname, then called the resolve path method.

In CommonJS

var path = require("path");

var __dirname = path.resolve();

In ES6+

import path  from 'path';

const __dirname = path.resolve();

Happy coding.......

Simple way to sort strings in the (case sensitive) alphabetical order

The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html

private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
        public int compare(String str1, String str2) {
            return ComparisonChain.start().
                                compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
                                compare(str1,str2).
                                result();
         }
 };
Collections.sort(list, stringAlphabeticalComparator);

The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:

"AA","Aa","aa","Development","development"

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

Global Git ignore

From here.

If you create a file in your repo named .gitignore git will use its rules when looking at files to commit. Note that git will not ignore a file that was already tracked before a rule was added to this file to ignore it. In such a case the file must be un-tracked, usually with :

git rm --cached filename

Is it your case ?

Open a URL in a new tab (and not a new window)

I think that you can't control this. If the user had setup their browser to open links in a new window, you can't force this to open links in a new tab.

JavaScript open in a new window, not tab

How to set JAVA_HOME in Linux for all users

Copy the bin file path you installed

YOUR PATH

open terminal and edit environment file by typing following command,

sudo nano /etc/environment

In this file, add the following line (replacing YOUR_PATH by the just copied path):

JAVA_HOME="YOUR_PATH"

That should be enough to set the environment variable. Now reload this file:

source /etc/environment

now test it by executing:

echo $JAVA_HOME

Is it possible to sort a ES6 map object?

As far as I see it's currently not possible to sort a Map properly.

The other solutions where the Map is converted into an array and sorted this way have the following bug:

var a = new Map([[1, 2], [3,4]])
console.log(a);    // a = Map(2) {1 => 2, 3 => 4}

var b = a;
console.log(b);    // b = Map(2) {1 => 2, 3 => 4}

a = new Map();     // this is when the sorting happens
console.log(a, b); // a = Map(0) {}     b = Map(2) {1 => 2, 3 => 4}

The sorting creates a new object and all other pointers to the unsorted object get broken.

jQuery fade out then fade in

This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn(); is what you require