Programs & Examples On #Rspec

RSpec is a behavior-driven development (BDD) framework for the Ruby programming language, inspired by JBehave. It contains its own fully integrated mocking framework based upon JMock. The framework can be considered a domain-specific language (DSL) and resembles a natural language specification.

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

I had this same error. I had everything written in correctly, including the Listing 10.13 from the tutorial.

Rails.application.configure do
.
.
.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delevery_method :test
host = 'example.com'
config.action_mailer.default_url_options = { host: host }
.
.
.
end

obviously with "example.com" replaced with my server url.

What I had glossed over in the tutorial was this line:

After restarting the development server to activate the configuration...

So the answer for me was to turn the server off and back on again.

How do you run a single test/spec file in RSpec?

This question is an old one, but it shows up at the top of Google when searching for how to run a single test. I don't know if it's a recent addition, but to run a single test out of a spec you can do the following:

rspec path/to/spec:<line number>

where -line number- is a line number that contains part of your test. For example, if you had a spec like:

1: 
2: it "should be awesome" do
3:   foo = 3
4:   foo.should eq(3)
5: end
6:

Let's say it's saved in spec/models/foo_spec.rb. Then you would run:

rspec spec/models/foo_spec.rb:2

and it would just run that one spec. In fact, that number could be anything from 2 to 5.

Hope this helps!

How to check for a JSON response using RSpec?

Simple and easy to way to do this.

# set some variable on success like :success => true in your controller
controller.rb
render :json => {:success => true, :data => data} # on success

spec_controller.rb
parse_json = JSON(response.body)
parse_json["success"].should == true

RSpec: how to test if a method was called?

The below should work

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

How to get Rails.logger printing to the console/stdout when running rspec?

A solution that I like, because it keeps rspec output separate from actual rails log output, is to do the following:

  • Open a second terminal window or tab, and arrange it so that you can see both the main terminal you're running rspec on as well as the new one.
  • Run a tail command in the second window so you see the rails log in the test environment. By default this can be like $ tail -f $RAILS_APP_DIR/logs/test.log or tail -f $RAILS_APP_DIR\logs\test.log for Window users
  • Run your rspec suites

If you are running a multi-pane terminal like iTerm, this becomes even more fun and you have rspec and the test.log output side by side.

When to use RSpec let()?

I always prefer let to an instance variable for a couple of reasons:

  • Instance variables spring into existence when referenced. This means that if you fat finger the spelling of the instance variable, a new one will be created and initialized to nil, which can lead to subtle bugs and false positives. Since let creates a method, you'll get a NameError when you misspell it, which I find preferable. It makes it easier to refactor specs, too.
  • A before(:each) hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined by let, the initialization code only runs if the example calls it.
  • You can refactor from a local variable in an example directly into a let without changing the referencing syntax in the example. If you refactor to an instance variable, you have to change how you reference the object in the example (e.g. add an @).
  • This is a bit subjective, but as Mike Lewis pointed out, I think it makes the spec easier to read. I like the organization of defining all my dependent objects with let and keeping my it block nice and short.

A related link can be found here: http://www.betterspecs.org/#let

How to run a single RSpec test?

Usually I do:

rspec ./spec/controllers/groups_controller_spec.rb:42

Where 42 represents the line of the test I want to run.

EDIT1:

You could also use tags. See here.

EDIT 2:

Try:

bundle exec rspec ./spec/controllers/groups_controller_spec.rb:42

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

To scrolldown from any position in the recyclerview to bottom

edittext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                      rv.scrollToPosition(rv.getAdapter().getItemCount() - 1);
                    }
                }, 1000);
            }
        });

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

How to write to a file, using the logging Python module?

http://docs.python.org/library/logging.handlers.html#filehandler

The FileHandler class, located in the core logging package, sends logging output to a disk file.

Best practice to validate null and empty collection in Java

You can use org.apache.commons.lang.Validate's "notEmpty" method:

Validate.notEmpty(myCollection) -> Validate that the specified argument collection is neither null nor a size of zero (no elements); otherwise throwing an exception.

Doctrine findBy 'does not equal'

There is now a an approach to do this, using Doctrine's Criteria.

A full example can be seen in How to use a findBy method with comparative criteria, but a brief answer follows.

use \Doctrine\Common\Collections\Criteria;

// Add a not equals parameter to your criteria
$criteria = new Criteria();
$criteria->where(Criteria::expr()->neq('prize', 200));

// Find all from the repository matching your criteria
$result = $entityRepository->matching($criteria);

Calculate difference between two datetimes in MySQL

If your start and end datetimes are on different days use TIMEDIFF.

SELECT TIMEDIFF(datetime1,datetime2)

if datetime1 > datetime2 then

SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")

gives: 24:01:00

and datetime1 < datetime2

SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")

gives: -24:01:00

How to get cookie's expire time

Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:

$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );

then when you get your cookie next time:

$cookie = json_decode( $_COOKIE[ "cookiename" ] );

you can simply extract the expiry time, which was inserted as data inside the cookie itself..

$expiry = $cookie->expiry;

and additionally the data which will come out as a usable object :)

$data = $cookie->data;
$value1 = $cookie->data->value1;

etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!

SharePoint 2013 get current user using JavaScript

I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.

//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
    alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
}, function(){alert(":(");});

Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.

How to check if a string contains a substring in Bash

My .bash_profile file and how I used grep:

If the PATH environment variable includes my two bin directories, don't append them,

# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

U=~/.local.bin:~/bin

if ! echo "$PATH" | grep -q "home"; then
    export PATH=$PATH:${U}
fi

docker run <IMAGE> <MULTIPLE COMMANDS>

If you want to store the result in one file outside the container, in your local machine, you can do something like this.

RES_FILE=$(readlink -f /tmp/result.txt)

docker run --rm -v ${RES_FILE}:/result.txt img bash -c "cat /etc/passwd | grep root > /result.txt"

The result of your commands will be available in /tmp/result.txt in your local machine.

Why does python use 'else' after for and while loops?

The else keyword can be confusing here, and as many people have pointed out, something like nobreak, notbreak is more appropriate.

In order to understand for ... else ... logically, compare it with try...except...else, not if...else..., most of python programmers are familiar with the following code:

try:
    do_something()
except:
    print("Error happened.") # The try block threw an exception
else:
    print("Everything is find.") # The try block does things just find.

Similarly, think of break as a special kind of Exception:

for x in iterable:
    do_something(x)
except break:
    pass # Implied by Python's loop semantics
else:
    print('no break encountered')  # No break statement was encountered

The difference is python implies except break and you can not write it out, so it becomes:

for x in iterable:
    do_something(x)
else:
    print('no break encountered')  # No break statement was encountered

Yes, I know this comparison can be difficult and tiresome, but it does clarify the confusion.

How do I set a value in CKEditor with Javascript?

I have used the below code and it is working fine as describing->

CKEDITOR.instances.mail_msg.insertText(obj["template"]);

Here-> CKEDITOR ->Your editor Name, mail_msg -> Id of your textarea(to which u bind the ckeditor), obj["template"]->is the value that u want to bind

What is __init__.py for?

An __init__.py file makes imports easy. When an __init__.py is present within a package, function a() can be imported from file b.py like so:

from b import a

Without it, however, you can't import directly. You have to amend the system path:

import sys
sys.path.insert(0, 'path/to/b.py')

from b import a

How to use JavaScript to change the form action

Try this:

var frm = document.getElementById('search-theme-form') || null;
if(frm) {
   frm.action = 'whatever_you_need.ext' 
}

Get a resource using getResource()

TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
  • leading slash to denote the root of the classpath
  • slashes instead of dots in the path
  • you can call getResource() directly on the class.

Difference between @click and v-on:click Vuejs

There is no difference between the two, one is just a shorthand for the second.

The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.

<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>

Source: official documentation.

How to enable curl in Wamp server

I got the same issue and this solved it for me. Perhaps this might be a fix for your problem too.

Here is the fix. Follow this link http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/

Go to "Fixed curl extensions" and download the extension that matches your PHP version.

Extract and copy "php_curl.dll" to the extension directory of your wamp installation. (i.e. C:\wamp\bin\php\php5.3.13\ext)

Restart Apache

Done!

Refer to: http://blog.nterms.com/2012/07/php-curl-issues-with-wamp-server-on.html

Cheers!

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Problem: You're trying to import data (using mysqldump file) to your mysql database ,but it seems you don't have permission to perform that operation.

Solution: Assuming you data is migrated ,seeded and updated in your mysql database, take snapshot using mysqldump and export it to file

mysqldump -u [username] -p [databaseName] --set-gtid-purged=OFF > [filename].sql

From mysql documentation:

GTID - A global transaction identifier (GTID) is a unique identifier created and associated with each transaction committed on the server of origin (master). This identifier is unique not only to the server on which it originated, but is unique across all servers in a given replication setup. There is a 1-to-1 mapping between all transactions and all GTIDs.

--set-gtid-purged=OFF SET @@GLOBAL.gtid_purged is not added to the output, and SET @@SESSION.sql_log_bin=0 is not added to the output. For a server where GTIDs are not in use, use this option or AUTO. Only use this option for a server where GTIDs are in use if you are sure that the required GTID set is already present in gtid_purged on the target server and should not be changed, or if you plan to identify and add any missing GTIDs manually.

Afterwards connect to your mysql with user root ,give permissions , flush them ,and verify that your user privileges were updated correctly.

mysql -u root -p
UPDATE mysql.user SET Super_Priv='Y' WHERE user='johnDoe' AND host='%';
FLUSH PRIVILEGES;
mysql> SHOW GRANTS FOR 'johnDoe';
+------------------------------------------------------------------+
| Grants for johnDoe                                               |
+------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `johnDoe`                                  |
| GRANT ALL PRIVILEGES ON `db1`.* TO `johnDoe`                     |
+------------------------------------------------------------------+

now reload the data and the operation should be permitted.

mysql -h [host] -u [user] -p[pass] [db_name] < [mysql_dump_name].sql

How can the error 'Client found response content type of 'text/html'.. be interpreted

That means that your consumer is expecting XML from the webservice but the webservice, as your error shows, returns HTML because it's failing due to a timeout.

So you need to talk to the remote webservice provider to let them know it's failing and take corrective action. Unless you are the provider of the webservice in which case you should catch the exceptions and return XML telling the consumer which error occurred (the 'remote provider' should probably do that as well).

ToList().ForEach in Linq

You can use Array.ForEach()

Array.ForEach(employees, employee => {
   Array.ForEach(employee.Departments, department => department.SomeProperty = null);
   Collection.AddRange(employee.Departments);
});

Linq select objects in list where exists IN (A,B,C)

var statuses = new[] { "A", "B", "C" };

var filteredOrders = from order in orders.Order
                             where statuses.Contains(order.StatusCode)
                             select order;

Create a Date with a set timezone without using a string representation

This may help someone, put UTC at the end of what you pass in to the new constructor

At least in chrome you can say var date = new Date("2014-01-01 11:00:00 UTC")

ImportError: No module named six

For me the issue wasn't six but rst2pdf itself. head -1 $(which rst2pdf) (3.8) didn't match python3 --version (3.9). My solution:

pip3 install rst2pdf

Sum across multiple columns with dplyr

dplyr >= 1.0.0

In newer versions of dplyr you can use rowwise() along with c_across to perform row-wise aggregation for functions that do not have specific row-wise variants, but if the row-wise variant exists it should be faster.

Since rowwise() is just a special form of grouping and changes the way verbs work you'll likely want to pipe it to ungroup() after doing your row-wise operation.

To select a range of rows:

df %>%
  dplyr::rowwise() %>% 
  dplyr::mutate(sumrange = sum(dplyr::c_across(x1:x5), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()

To select rows by type:

df %>%
  dplyr::rowwise() %>% 
  dplyr::mutate(sumnumeric = sum(c_across(where(is.numeric)), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()

In your specific case a row-wise variant exists so you can do the following (note the use of across instead):

df %>%
  dplyr::mutate(sumrow = rowSums(dplyr::across(x1:x5), na.rm = T))

For more information see the page on rowwise.

Dealing with float precision in Javascript

You could do something like this:

> +(Math.floor(y/x)*x).toFixed(15);
1.2

How to programmatically empty browser cache?

It's possible, you can simply use jQuery to substitute the 'meta tag' that references the cache status with an event handler / button, and then refresh, easy,

$('.button').click(function() {
    $.ajax({
        url: "",
        context: document.body,
        success: function(s,x){

            $('html[manifest=saveappoffline.appcache]').attr('content', '');
                $(this).html(s);
        }
    }); 
});

NOTE: This solution relies on the Application Cache that is implemented as part of the HTML 5 spec. It also requires server configuration to set up the App Cache manifest. It does not describe a method by which one can clear the 'traditional' browser cache via client- or server-side code, which is nigh impossible to do.

How to avoid Python/Pandas creating an index in a saved csv?

Another solution if you want to keep this column as index.

pd.read_csv('filename.csv', index_col='Unnamed: 0')

How do I plot list of tuples in Python?

With gnuplot using gplot.py

from gplot import *

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

gplot.log('y')
gplot(*zip(*l))

enter image description here

Is there a way to list open transactions on SQL Server 2000 database?

DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.

An informational message is displayed if there are no active transactions in the log.

DBCC OPENTRAN

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

In my case ; what solved my issue was.....

You may had json like this, the keys without " double quotations....

{ name: "test", phone: "2324234" }

So try any online Json Validator to make sure you have right syntax...

Json Validator Online

Get environment value in controller

You can use with this format (tested on Laravel 5.5). In my case I used it for gettting the data of database connections and use on Controller:

$User = env('DB_USERNAMEchild','');
$Pass = env('DB_PASSWORDchild','');

The second parameter can be null, or set any default in case of DB_USERNAMEchild is null.

Your .env file can be the same:

DB_HOST=localhost
DB_DATABASE=FATHERBD
DB_USERNAME=root
DB_PASSWORD=password

DB_DATABASEchild=ZTEST
DB_USERNAMEchild=root
DB_PASSWORDchild=passwordofchild

Does svn have a `revert-all` command?

Use the recursive switch --recursive (-R)

svn revert -R .

How to use GROUP BY to concatenate strings in SQL Server?

Using Replace Function and FOR JSON PATH

SELECT T3.DEPT, REPLACE(REPLACE(T3.ENAME,'{"ENAME":"',''),'"}','') AS ENAME_LIST
FROM (
 SELECT DEPT, (SELECT ENAME AS [ENAME]
        FROM EMPLOYEE T2
        WHERE T2.DEPT=T1.DEPT
        FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) ENAME
    FROM EMPLOYEE T1
    GROUP BY DEPT) T3

For sample data and more ways click here

How to "wait" a Thread in Android

Don't use wait(), use either android.os.SystemClock.sleep(1000); or Thread.sleep(1000);.

The main difference between them is that Thread.sleep() can be interrupted early -- you'll be told, but it's still not the full second. The android.os call will not wake early.

Java TreeMap Comparator

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());

How to write inside a DIV box with javascript

You can use one of the following methods:

document.getElementById('log').innerHTML = "text";

document.getElementById('log').innerText = "text";

document.getElementById('log').textContent = "text";

For Jquery:

$("#log").text("text");

$("#log").html("text");

Displaying one div on top of another

Use CSS position: absolute; followed by top: 0px; left 0px; in the style attribute of each DIV. Replace the pixel values with whatever you want.

You can use z-index: x; to set the vertical "order" (which one is "on top"). Replace x with a number, higher numbers are on top of lower numbers.

Here is how your new code would look:

<div>
  <div id="backdrop" style="z-index: 1; position: absolute; top: 0px; left: 0px;"><img alt="" src='/backdrop.png' /></div>
  <div id="curtain" style="z-index: 2; position: absolute; top: 0px; left: 0px; background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;">&nbsp;</div>
</div>

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

Adding an assets folder in Android Studio

An image of how to in Android Studio 1.5.1.

Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...

enter image description here

The ternary (conditional) operator in C

like dwn said, Performance was one of its benefits during the rise of complex processors, MSDN blog Non-classical processor behavior: How doing something can be faster than not doing it gives an example which clearly says the difference between ternary (conditional) operator and if/else statement.

give the following code:

#include <windows.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>

int array[10000];

int countthem(int boundary)
{
 int count = 0;
 for (int i = 0; i < 10000; i++) {
  if (array[i] < boundary) count++;
 }
 return count;
}

int __cdecl wmain(int, wchar_t **)
{
 for (int i = 0; i < 10000; i++) array[i] = rand() % 10;

 for (int boundary = 0; boundary <= 10; boundary++) {
  LARGE_INTEGER liStart, liEnd;
  QueryPerformanceCounter(&liStart);

  int count = 0;
  for (int iterations = 0; iterations < 100; iterations++) {
   count += countthem(boundary);
  }

  QueryPerformanceCounter(&liEnd);
  printf("count=%7d, time = %I64d\n",
         count, liEnd.QuadPart - liStart.QuadPart);
 }
 return 0;
}

the cost for different boundary are much different and wierd (see the original material). while if change:

 if (array[i] < boundary) count++;

to

 count += (array[i] < boundary) ? 1 : 0;

The execution time is now independent of the boundary value, since:

the optimizer was able to remove the branch from the ternary expression.

but on my desktop intel i5 cpu/windows 10/vs2015, my test result is quite different with msdn blog.

when using debug mode, if/else cost:

count=      0, time = 6434
count= 100000, time = 7652
count= 200800, time = 10124
count= 300200, time = 12820
count= 403100, time = 15566
count= 497400, time = 16911
count= 602900, time = 15999
count= 700700, time = 12997
count= 797500, time = 11465
count= 902500, time = 7619
count=1000000, time = 6429

and ternary operator cost:

count=      0, time = 7045
count= 100000, time = 10194
count= 200800, time = 12080
count= 300200, time = 15007
count= 403100, time = 18519
count= 497400, time = 20957
count= 602900, time = 17851
count= 700700, time = 14593
count= 797500, time = 12390
count= 902500, time = 9283
count=1000000, time = 7020 

when using release mode, if/else cost:

count=      0, time = 7
count= 100000, time = 9
count= 200800, time = 9
count= 300200, time = 9
count= 403100, time = 9
count= 497400, time = 8
count= 602900, time = 7
count= 700700, time = 7
count= 797500, time = 10
count= 902500, time = 7
count=1000000, time = 7

and ternary operator cost:

count=      0, time = 16
count= 100000, time = 17
count= 200800, time = 18
count= 300200, time = 16
count= 403100, time = 22
count= 497400, time = 16
count= 602900, time = 16
count= 700700, time = 15
count= 797500, time = 15
count= 902500, time = 16
count=1000000, time = 16

the ternary operator is slower than if/else statement on my machine!

so according to different compiler optimization techniques, ternal operator and if/else may behaves much different.

How to get certain commit from GitHub project

To just download a commit using the 7-digit SHA1 short form do:

Working Example:

https://github.com/python/cpython/archive/31af650.zip  

Description:

 `https://github.com/username/projectname/archive/commitshakey.zip`

If you have the long hash key 31af650ee25f65794b75d4dfefed6fe4758781c1, just get the first 7 chars 31af650. It's the default for GitHub.

How can I create an Asynchronous function in Javascript?

Unfortunately, JavaScript doesn't provide an async functionality. It works only in a single one thread. But the most of the modern browsers provide Workers, that are second scripts which gets executed in background and can return a result. So, I reached a solution I think it's useful to asynchronously run a function, which creates a worker for each async call.

The code below contains the function async to call in background.

Function.prototype.async = function(callback) {
    let blob = new Blob([ "self.addEventListener('message', function(e) { self.postMessage({ result: (" + this + ").apply(null, e.data) }); }, false);" ], { type: "text/javascript" });
    let worker = new Worker(window.URL.createObjectURL(blob));
    worker.addEventListener("message", function(e) {
        this(e.data.result);
    }.bind(callback), false);
    return function() {
        this.postMessage(Array.from(arguments));
    }.bind(worker);
};

This is an example for usage:

(function(x) {
    for (let i = 0; i < 999999999; i++) {}
        return x * 2;
}).async(function(result) {
    alert(result);
})(10);

This executes a function which iterate a for with a huge number to take time as demonstration of asynchronicity, and then gets the double of the passed number. The async method provides a function which calls the wanted function in background, and in that which is provided as parameter of async callbacks the return in its unique parameter. So in the callback function I alert the result.

Array to Hash Ruby

All answers assume the starting array is unique. OP did not specify how to handle arrays with duplicate entries, which result in duplicate keys.

Let's look at:

a = ["item 1", "item 2", "item 3", "item 4", "item 1", "item 5"]

You will lose the item 1 => item 2 pair as it is overridden bij item 1 => item 5:

Hash[*a]
=> {"item 1"=>"item 5", "item 3"=>"item 4"}

All of the methods, including the reduce(&:merge!) result in the same removal.

It could be that this is exactly what you expect, though. But in other cases, you probably want to get a result with an Array for value instead:

{"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

The naïve way would be to create a helper variable, a hash that has a default value, and then fill that in a loop:

result = Hash.new {|hash, k| hash[k] = [] } # Hash.new with block defines unique defaults.
a.each_slice(2) {|k,v| result[k] << v }
a
=> {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

It might be possible to use assoc and reduce to do above in one line, but that becomes much harder to reason about and read.

Dockerfile if else condition with external arguments

From some reason most of the answers here didn't help me (maybe it's related to my FROM image in the Dockerfile)

So I preferred to create a bash script in my workspace combined with --build-arg in order to handle if statement while Docker build by checking if the argument is empty or not

Bash script:

#!/bin/bash -x

if test -z $1 ; then 
    echo "The arg is empty"
    ....do something....
else 
    echo "The arg is not empty: $1"
    ....do something else....
fi

Dockerfile:

FROM ...
....
ARG arg
COPY bash.sh /tmp/  
RUN chmod u+x /tmp/bash.sh && /tmp/bash.sh $arg
....

Docker Build:

docker build --pull -f "Dockerfile" -t $SERVICE_NAME --build-arg arg="yes" .

Remark: This will go to the else (false) in the bash script

docker build --pull -f "Dockerfile" -t $SERVICE_NAME .

Remark: This will go to the if (true)

Edit 1:

After several tries I have found the following article and this one which helped me to understand 2 things:

1) ARG before FROM is outside of the build

2) The default shell is /bin/sh which means that the if else is working a little bit different in the docker build. for example you need only one "=" instead of "==" to compare strings.

So you can do this inside the Dockerfile

ARG argname=false   #default argument when not provided in the --build-arg
RUN if [ "$argname" = "false" ] ; then echo 'false'; else echo 'true'; fi

and in the docker build:

docker build --pull -f "Dockerfile" --label "service_name=${SERVICE_NAME}" -t $SERVICE_NAME --build-arg argname=true .

Why should I use the keyword "final" on a method parameter in Java?

Sometimes it's nice to be explicit (for readability) that the variable doesn't change. Here's a simple example where using final can save some possible headaches:

public void setTest(String test) {
    test = test;
}

If you forget the 'this' keyword on a setter, then the variable you want to set doesn't get set. However, if you used the final keyword on the parameter, then the bug would be caught at compile time.

How do I test a website using XAMPP?

create a folder inside htdocs, place your website there, access it via localhost or Internal IP (if you're behind a router) - check out this video demo here

Action Image MVC3 Razor

slide modification changed Helper

     public static IHtmlString ActionImageLink(this HtmlHelper html, string action, object routeValues, string styleClass, string alt)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);
        var anchorBuilder = new TagBuilder("a");
        anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
        anchorBuilder.AddCssClass(styleClass);
        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

        return new HtmlString(anchorHtml);
    }

CSS Class

.Edit {
       background: url('../images/edit.png') no-repeat right;
       display: inline-block;
       height: 16px;
       width: 16px;
      }

Create the link just pass the class name

     @Html.ActionImageLink("Edit", new { id = item.ID }, "Edit" , "Edit") 

How to set scope property with ng-init?

Try this Code

var app = angular.module('myapp', []);
  app.controller('testController', function ($scope, $http) {
       $scope.init = function(){           
       alert($scope.testInput);
   };});

_x000D_
_x000D_
<body ng-app="myapp">_x000D_
      <div ng-controller='testController' data-ng-init="testInput='value'; init();" class="col-sm-9 col-lg-9" >_x000D_
      </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

The problem could be in Flex's SOAP encoder. Try extending the SOAP encoder in your Flex application and debug the program to see how the null value is handled.

My guess is, it's passed as NaN (Not a Number). This will mess up the SOAP message unmarshalling process sometime (most notably in the JBoss 5 server...). I remember extending the SOAP encoder and performing an explicit check on how NaN is handled.

Determine command line working directory when running node bin script

Current Working Directory

To get the current working directory, you can use:

process.cwd()

However, be aware that some scripts, notably gulp, will change the current working directory with process.chdir().

Node Module Path

You can get the path of the current module with:

  • __filename
  • __dirname

Original Directory (where the command was initiated)

If you are running a script from the command line, and you want the original directory from which the script was run, regardless of what directory the script is currently operating in, you can use:

process.env.INIT_CWD

Original directory, when working with NPM scripts

It's sometimes desirable to run an NPM script in the current directory, rather than the root of the project.

This variable is available inside npm package scripts as:

$INIT_CWD.

You must be running a recent version of NPM. If this variable is not available, make sure NPM is up to date.

This will allow you access the current path in your package.json, e.g.:

scripts: {
  "customScript": "gulp customScript --path $INIT_CWD"
}

Mapping over values in a python dictionary

To avoid doing indexing from inside lambda, like:

rval = dict(map(lambda kv : (kv[0], ' '.join(kv[1])), rval.iteritems()))

You can also do:

rval = dict(map(lambda(k,v) : (k, ' '.join(v)), rval.iteritems()))

What good are SQL Server schemas?

I know it's an old thread, but I just looked into schemas myself and think the following could be another good candidate for schema usage:

In a Datawarehouse, with data coming from different sources, you can use a different schema for each source, and then e.g. control access based on the schemas. Also avoids the possible naming collisions between the various source, as another poster replied above.

How to validate an OAuth 2.0 access token for a resource server?

OAuth v2 specs indicates:

Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications.

My Authorisation Server has a webservice (SOAP) endpoint that allows the Resource Server to know whether the access_token is valid.

How to revert multiple git commits?

I'm so frustrated that this question can't just be answered. Every other question is in relation to how to revert correctly and preserve history. This question says "I want the head of the branch to point to A, i.e. I want B, C, D, and HEAD to disappear and I want head to be synonymous with A."

git checkout <branch_name>
git reset --hard <commit Hash for A>
git push -f

I learned a lot reading Jakub's post, but some guy in the company (with access to push to our "testing" branch without Pull-Request) pushed like 5 bad commits trying to fix and fix and fix a mistake he made 5 commits ago. Not only that, but one or two Pull Requests were accepted, which were now bad. So forget it, I found the last good commit (abc1234) and just ran the basic script:

git checkout testing
git reset --hard abc1234
git push -f

I told the other 5 guys working in this repo that they better make note of their changes for the last few hours and Wipe/Re-Branch from the latest testing. End of the story.

Vim delete blank lines

  1. how to remove all the blanks lines

    :%s,\n\n,^M,g
    

    (do this multiple times util all the empty lines went gone)

  2. how to remove all the blanks lines leaving SINGLE empty line

    :%s,\n\n\n,^M^M,g
    

    (do this multiple times)

  3. how to remove all the blanks lines leaving TWO empty lines AT MAXIMUM,

    :%s,\n\n\n\n,^M^M^M,g
    

    (do this multiple times)

in order to input ^M, I have to control-Q and control-M in windows

Return row of Data Frame based on value in a column - R

You could use dplyr:

df %>% group_by("Amount") %>% slice(which.min(x))

Twig for loop for arrays with keys

These are extended operations (e.g., sort, reverse) for one dimensional and two dimensional arrays in Twig framework:

1D Array

Without Key Sort and Reverse

{% for key, value in array_one_dimension %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

Key Sort

{% for key, value in array_one_dimension|keys|sort %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

Key Sort and Reverse

{% for key, value in array_one_dimension|keys|sort|reverse %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

2D Arrays

Without Key Sort and Reverse

{% for key_a, value_a in array_two_dimension %}
    {% for key_b, value_b in array_two_dimension[key_a] %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Outer Array

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a] %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Both Outer and Inner Arrays

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Outer Array & Key Sort and Reverse on Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort and Reverse on Outer Array & Key Sort on Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort and Reverse on Both Outer and Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Find a file by name in Visual Studio Code

It's Ctrl+Shift+O / Cmd+Shift+O on mac. You can see it if you close all tabs

Change the column label? e.g.: change column "A" to column "Name"

If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok

How can I get a resource "Folder" from inside my jar File?

Another solution, you can do it using ResourceLoader like this:

import org.springframework.core.io.Resource;
import org.apache.commons.io.FileUtils;

@Autowire
private ResourceLoader resourceLoader;

...

Resource resource = resourceLoader.getResource("classpath:/path/to/you/dir");
File file = resource.getFile();
Iterator<File> fi = FileUtils.iterateFiles(file, null, true);
while(fi.hasNext()) {
    load(fi.next())
}

How do I disable a Button in Flutter?

According to the docs:

"If the onPressed callback is null, then the button will be disabled and by default will resemble a flat button in the disabledColor."

https://docs.flutter.io/flutter/material/RaisedButton-class.html

So, you might do something like this:

    RaisedButton(
      onPressed: calculateWhetherDisabledReturnsBool() ? null : () => whatToDoOnPressed,
      child: Text('Button text')
    );

What is the meaning of polyfills in HTML5?

First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.

The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "

Source and example of polyfill here:

http://www.programmerinterview.com/index.php/html5/html5-polyfill/

How to query a MS-Access Table from MS-Excel (2010) using VBA

All you need is a ADODB.Connection

Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset   ' Microsoft ActiveX Data Objects Library

Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"

Set rs = cnn.Execute(SQLQuery) ' Retrieve the data

Using IF ELSE in Oracle

You can use Decode as well:

SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
      AND A.ITEM_KEY = b.item_key
      AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
                         and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item

CSS3 gradient background set on body doesn't stretch but instead repeats?

Setting html { height: 100%} can wreak havoc with IE. Here's an example (png). But you know what works great? Just set your background on the <html> tag.

html {
  -moz-linear-gradient(top, #fff, #000);
  /* etc. */
}

Background extends to the bottom and no weird scrolling behavior occurs. You can skip all of the other fixes. And this is broadly supported. I haven't found a browser that doesn't let you apply a background to the html tag. It's perfectly valid CSS and has been for a while. :)

Difference between 'cls' and 'self' in Python classes?

cls implies that method belongs to the class while self implies that the method is related to instance of the class,therefore member with cls is accessed by class name where as the one with self is accessed by instance of the class...it is the same concept as static member and non-static members in java if you are from java background.

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

Make a Bash alias that takes a parameter?

An alternative solution is to use marker, a tool I've created recently that allows you to "bookmark" command templates and easily place cursor at command place-holders:

commandline marker

I found that most of time, I'm using shell functions so I don't have to write frequently used commands again and again in the command-line. The issue of using functions for this use case, is adding new terms to my command vocabulary and having to remember what functions parameters refer to in the real-command. Marker goal is to eliminate that mental burden.

Undefined reference to pthread_create in Linux

Acutally, it gives several examples of compile commands used for pthreads codes are listed in the table below, if you continue reading the following tutorial:

https://computing.llnl.gov/tutorials/pthreads/#Compiling

enter image description here

How to use format() on a moment.js duration?

If all hours must be displayed (more than 24) and if '0' before hours is not necessary, then formatting can be done with a short line of code:

Math.floor(duration.as('h')) + moment.utc(duration.as('ms')).format(':mm:ss')

What is the difference between square brackets and parentheses in a regex?

These regexes are equivalent (for matching purposes):

  • /^(7|8|9)\d{9}$/
  • /^[789]\d{9}$/
  • /^[7-9]\d{9}$/

The explanation:

  • (a|b|c) is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9) to make it a non capturing group.

  • [abc] is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d] = [abcd])

The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def) which does not translate to a character class.

How does the bitwise complement operator (~ tilde) work?

~ flips the bits in the value.

Why ~2 is -3 has to do with how numbers are represented bitwise. Numbers are represented as two's complement.

So, 2 is the binary value

00000010

And ~2 flips the bits so the value is now:

11111101

Which, is the binary representation of -3.

how to remove pagination in datatable

It's working

Try below code

$('#example').dataTable({
    "bProcessing": true,
    "sAutoWidth": false,
    "bDestroy":true,
    "sPaginationType": "bootstrap", // full_numbers
    "iDisplayStart ": 10,
    "iDisplayLength": 10,
    "bPaginate": false, //hide pagination
    "bFilter": false, //hide Search bar
    "bInfo": false, // hide showing entries
})

Replace an element into a specific position of a vector

You can do that using at. You can try out the following simple example:

const size_t N = 20;
std::vector<int> vec(N);
try {
    vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
    std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);

Notice that method at returns an allocator_type::reference, which is that case is a int&. Using at is equivalent to assigning values like vec[i]=....


There is a difference between at and insert as it can be understood with the following example:

const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
    vec[i] = i + 1;
}

vec.insert(vec.begin()+2, 10);

If we now print out vec we will get:

1 2 10 3 4 5 0 0 0

If, instead, we did vec.at(2) = 10, or vec[2]=10, we would get

1 2 10 4 5 0 0 0

How do I change a TCP socket to be non-blocking?

If you want to change socket to non blocking , precisely accept() to NON-Blocking state then

    int flags=fcntl(master_socket, F_GETFL);
        fcntl(master_socket, F_SETFL,flags| O_NONBLOCK); /* Change the socket into non-blocking state  F_SETFL is a command saying set flag and flag is 0_NONBLOCK     */                                          

while(1){
    if((newSocket = accept(master_socket, (struct sockaddr *) &address, &addr_size))<0){
                if(errno==EWOULDBLOCK){
                       puts("\n No clients currently available............ \n");
                       continue;
               }
    }else{
          puts("\nClient approched............ \n");
    }

}

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Nicer code for this:

yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);

How do I force a favicon refresh?

Simon, I suppose there's a reason none of the other answers is accepted so far. Thus I believe this could be a Grails issue nevertheless - Especially if you're using the 'Resources Plugin'.

If your plugins provide a favicon (which - illogically - many do), they might override the one you desired to use - given yours is in a plugin itself.

If deleting the favicon from all your plugins temporary resolves the issue then you're very likely experiencing this:

http://jira.grails.org/browse/GPRESOURCES-134

Count unique values in a column in Excel

Here’s another quickie way to get the unique value count, as well as to get the unique values. Copy the column you care about into another worksheet, then select the entire column. Click on Data -> Remove Duplicates -> OK. This removes all duplicated values.

Deleting a file in VBA

1.) Check here. Basically do this:

Function FileExists(ByVal FileToTest As String) As Boolean
   FileExists = (Dir(FileToTest) <> "")
End Function

I'll leave it to you to figure out the various error handling needed but these are among the error handling things I'd be considering:

  • Check for an empty string being passed.
  • Check for a string containing characters illegal in a file name/path

2.) How To Delete a File. Look at this. Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here's a function for you:

Sub DeleteFile(ByVal FileToDelete As String)
   If FileExists(FileToDelete) Then 'See above          
      ' First remove readonly attribute, if set
      SetAttr FileToDelete, vbNormal          
      ' Then delete the file
      Kill FileToDelete
   End If
End Sub

Again, I'll leave the error handling to you and again these are the things I'd consider:

  • Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory?

  • Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set?


EDIT: Marking this answer as community wiki so anyone can modify it if need be.

Sending multipart/formdata with jQuery.ajax

All the solutions above are looks good and elegant, but the FormData() object does not expect any parameter, but use append() after instantiate it, like what one wrote above:

formData.append(val.name, val.value);

Artisan migrate could not find driver

Make sure that you've installed php-mysql, the pdo needs php-mysql to operate properly. If not you could simply type

sudo apt install php-mysql

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

java.util.Date is independent of the timezone. When you print cal_Two though the Calendar instance has got its timezone set to UTC, cal_Two.getTime() would return a Date instance which does not have a timezone (and is always in the default timezone)

Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
System.out.println(cal_Two.getTimeZone());

Output:

 Sat Jan 25 16:40:28 IST 2014
    sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] 

From the javadoc of TimeZone.setDefault()

Sets the TimeZone that is returned by the getDefault method. If zone is null, reset the default to the value it had originally when the VM first started.

Hence, moving your setDefault() before cal_Two is instantiated you would get the correct result.

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());

Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());

Output:

Sat Jan 25 11:15:29 UTC 2014
Sat Jan 25 11:15:29 UTC 2014

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

When you do not provide mapDispatchToProps as a second argument, like this:

export default connect(mapStateToProps)(Checkbox)

then you are automatically getting the dispatch to component's props, so you can just:

class SomeComp extends React.Component {
  constructor(props, context) {
    super(props, context);
  }
  componentDidMount() {
    this.props.dispatch(ACTION GOES HERE);
  }
....

without any mapDispatchToProps

Git pull command from different user

This command will help to pull from the repository as the different user:

git pull https://[email protected]/projectfolder/projectname.git master

It is a workaround, when you are using same machine that someone else used before you, and had saved credentials

How do I merge a specific commit from one branch into another in Git?

SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work

The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:

enter image description here

If you want to pull commit e43a6 into your master branch, you can run

$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
 3 files changed, 17 insertions(+), 3 deletions(-)

This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:

enter image description here

Now you can remove your topic branch and drop the commits you didn’t want to pull in.

Cannot refer to a non-final variable inside an inner class defined in a different method

If the variable required to be final, cannot be then you can assign the value of the variable to another variable and make THAT final so you can use it instead.

What is the best way to do a substring in a batch file?

As an additional info to Joey's answer, which isn't described in the help of set /? nor for /?.

%~0 expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as

%~0   - mYbAtCh
%~n0  - mybatch
%~nx0 - mybatch.bat

But there is one exception, expanding in a subroutine could fail

echo main- %~0
call :myFunction
exit /b

:myFunction
echo func - %~0
echo func - %~n0
exit /b

This results to

main - myBatch
Func - :myFunction
func - mybatch

In a function %~0 expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!

Angular JS POST request not sending JSON data

you can use your method by this way

var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();

$http({
    url: '/api/apiControllerName/methodName',
    method: 'POST',
    params: {application:app, from:d1, to:d2},
    headers: { 'Content-Type': 'application/json;charset=utf-8' },
    //timeout: 1,
    //cache: false,
    //transformRequest: false,
    //transformResponse: false
}).then(function (results) {
    return results;
}).catch(function (e) {

});

Is there a way to have printf() properly print out an array (of floats, say)?

You have to loop through the array and printf() each element:

for(int i=0;i<10;++i) {
  printf("%.2f ", foo[i]);
}

printf("\n");

How to check if the request is an AJAX request with PHP

You could try using a $_SESSION variable to make sure that a request was made from a browser. Otherwise, you could have the request sent through a database or file [server-side].

Format the date using Ruby on Rails

Easiest is to use strftime (docs).

If it's for use on the view side, better to wrap it in a helper, though.

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

Create an application setup in visual studio 2013

Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and release the Visual Studio Installer Projects Extension. You can now create installers in VS2013, download the extension here from the visualstudiogallery.

visual-studio-installer-projects-extension

Reading images in python

Easy way

from IPython.display import Image

Image(filename ="Covid.jpg" size )

How to scroll up or down the page to an anchor using jQuery?

My approach with jQuery to just make all of the embedded anchor links slide instead of jump instantly

It's really similar to the answer by Santi Nunez but it's more reliable.

Support

  • Multi-framework environment.
  • Before the page has finished loading.
<a href="#myid">Go to</a>
<div id="myid"></div>
// Slow scroll with anchors
(function($){
    $(document).on('click', 'a[href^=#]', function(e){
        e.preventDefault();
        var id = $(this).attr('href');
        $('html,body').animate({scrollTop: $(id).offset().top}, 500);
    });
})(jQuery);

Best Timer for using in a Windows service

Both System.Timers.Timer and System.Threading.Timer will work for services.

The timers you want to avoid are System.Web.UI.Timer and System.Windows.Forms.Timer, which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building.

Use System.Timers.Timer like the following example (also, make sure that you use a class level variable to prevent garbage collection, as stated in Tim Robinson's answer):

using System;
using System.Timers;

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        // Normally, the timer is declared at the class level,
        // so that it stays in scope as long as it is needed.
        // If the timer is declared in a long-running method,  
        // KeepAlive must be used to prevent the JIT compiler 
        // from allowing aggressive garbage collection to occur 
        // before the method ends. (See end of method.)
        //System.Timers.Timer aTimer;

        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(10000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */

If you choose System.Threading.Timer, you can use as follows:

using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        AutoResetEvent autoEvent     = new AutoResetEvent(false);
        StatusChecker  statusChecker = new StatusChecker(10);

        // Create the delegate that invokes methods for the timer.
        TimerCallback timerDelegate = 
            new TimerCallback(statusChecker.CheckStatus);

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n", 
            DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer = 
                new Timer(timerDelegate, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period.\n");

        // When autoEvent signals the second time, dispose of 
        // the timer.
        autoEvent.WaitOne(5000, false);
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    int invokeCount, maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if(invokeCount == maxCount)
        {
            // Reset the counter and signal Main.
            invokeCount  = 0;
            autoEvent.Set();
        }
    }
}

Both examples comes from the MSDN pages.

C# how to convert File.ReadLines into string array?

string[] lines = File.ReadLines("c:\\file.txt").ToArray();

Although one wonders why you'll want to do that when ReadAllLines works just fine.

Or perhaps you just want to enumerate with the return value of File.ReadLines:

var lines = File.ReadAllLines("c:\\file.txt");
foreach (var line in lines)
{
    Console.WriteLine("\t" + line);
}

What does the 'Z' mean in Unix timestamp '120314170138Z'?

The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.

How do I add space between two variables after a print in Python

You should use python Explicit Conversion Flag PEP-3101

'My name is {0!s:10} {1}'.format('Dunkin', 'Donuts')

'My name is Dunkin Donuts'

or

'My name is %-10s %s' % ('Dunkin', 'Donuts')

'My name is Dunkin Donuts'

https://www.python.org/dev/peps/pep-3101/

Getting RSA private key from PEM BASE64 Encoded private key file

Make sure your id_rsa file doesn't have any extension like .txt or .rtf. Rich Text Format adds additional characters to your file and those gets added to byte array. Which eventually causes invalid private key error. Long story short, Copy the file, not content.

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

If you press CTRL + I it will just format tabs/whitespaces in code and pressing CTRL + SHIFT + F format all code that is format tabs/whitespaces and also divide code lines in a way that it is visible without horizontal scroll.

Android open pdf file

The reason you don't have permissions to open file is because you didn't grant other apps to open or view the file on your intent. To grant other apps to open the downloaded file, include the flag(as shown below): FLAG_GRANT_READ_URI_PERMISSION

Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(getUriFromFile(localFile), "application/pdf");
browserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|
Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(browserIntent);

And for function:

getUriFromFile(localFile)

private Uri getUriFromFile(File file){
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        return Uri.fromFile(file);
    }else {
        return FileProvider.getUriForFile(itemView.getContext(), itemView.getContext().getApplicationContext().getPackageName() + ".provider", file);
    }
}

H2 in-memory database. Table not found

<bean id="benchmarkDataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1" />
    <property name="username" value="sa" />
    <property name="password" value="" />
</bean>

How to add conditional attribute in Angular 2?

in angular-2 attribute syntax is

<div [attr.role]="myAriaRole">

Binds attribute role to the result of expression myAriaRole.

so can use like

[attr.role]="myAriaRole ? true: null"

Launching Spring application Address already in use

image of Spring Tool Suite and stop application button

In my case looking in the servers window only showed a tomcat server that I had never used for this project. My SpringBoot project used an embedded tomcat server and it did not stop when my application finished. This button which I indicate with a red arrow will stop the application and the Tomcat server so next time I run the application I will not get the error that an Instance of Tomcat is already running on port 8080.

actual error messages:

Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.

Caused by: java.net.BindException: Address already in use Caused by: org.apache.catalina.LifecycleException: service.getName(): "Tomcat"; Protocol handler start failed

I will now be looking into a way to shut down all services on completion of my SpringBoot Consuming Rest application in this tutorial https://spring.io/guides/gs/consuming-rest/

spring-boot

I have created a table in hive, I would like to know which directory my table is created in?

To see both of the structure and location (directory) of an any (internal or external)table, we can use table's create statment-

show create table table_name;

Setting a divs background image to fit its size?

Wanted to add a solution for IE8 and below (as low as IE5.5 I think), which cannot use background-size

div{
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=
'/path/to/img.jpg', sizingMethod='scale');
}

Using PropertyInfo to find out the property type

I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)

public static bool IsStringType(object data)
    {
        return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
    }

how to change listen port from default 7001 to something different?

You can change the listen port as per your requirement. This task can be accomplished in two diffrent ways. By changing config.xml file By changing in admin console Change the listen port in config.xml as per your requirement and bounce the domain. Admin Console Login to AdminConsole->Server->Configuration->ListenPort (Change it) Note: It is a bad practice to edit config.xml and try to edit in admin console(It's a good practise as well)

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

If you know the type will never be null or undefined, you should declare it as foo: Bar without the ?. Declaring a type with the ? Bar syntax means it could potentially be undefined, which is something you need to check for.

In other words, the compiler is doing exactly what you're asking it to. If you want it to be optional, you'll need to the check later.

How to comment in Vim's config files: ".vimrc"?

Same as above. Use double quote to start the comment and without the closing quote.

Example:

set cul "Highlight current line

Taskkill /f doesn't kill a process

I had the exact same issue, found this fix on another site: powershell.exe "Get-Process processname| Stop-Process" it worked for me and I was in the same boat where I had to restart, the /T would not work.

What is the hamburger menu icon called and the three vertical dots icon called?

According to Reddit, more options icon and kabob menu are popular names. I prefer the latter as it goes well with hamburger menu.

Getting today's date in YYYY-MM-DD in Python?

I prefer this, because this is simple, but maybe somehow inefficient and buggy. You must check the exit code of shell command if you want a strongly error-proof program.

os.system('date +%Y-%m-%d')

Find character position and update file name

If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.

 $text = "asdfNAME=PC123456<>Diweursejsfdjiwr"

asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456

 $text.IndexOf("E=")

7 - this is the "FIND" command for Powershell

 $text.substring(10,5)

C1234 - this is the "MID" command for Powershell

 $text.substring($text.IndexOf("E=")+2,8)

PC123456 - tada it has found and cut our text

-RavonTUS

How to generate xsd from wsdl

(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :

Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.

This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).

Excel VBA Check if directory exists error

If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then
   MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY"
End If

How to put two divs on the same line with CSS in simple_form in rails?

why not use flexbox ? so wrap them into another div like that

_x000D_
_x000D_
.flexContainer { _x000D_
   _x000D_
  margin: 2px 10px;_x000D_
  display: flex;_x000D_
} _x000D_
_x000D_
.left {_x000D_
  flex-basis : 30%;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  flex-basis : 30%;_x000D_
}
_x000D_
<form id="new_production" class="simple_form new_production" novalidate="novalidate" method="post" action="/projects/1/productions" accept-charset="UTF-8">_x000D_
    <div style="margin:0;padding:0;display:inline">_x000D_
        <input type="hidden" value="?" name="utf8">_x000D_
        <input type="hidden" value="2UQCUU+tKiKKtEiDtLLNeDrfBDoHTUmz5Sl9+JRVjALat3hFM=" name="authenticity_token">_x000D_
    </div>_x000D_
    <div class="flexContainer">_x000D_
      <div class="left">Proj Name:</div>_x000D_
      <div class="right">must have a name</div>_x000D_
    </div>_x000D_
    <div class="input string required"> </div>_x000D_
 </form>
_x000D_
_x000D_
_x000D_

feel free to play with flex-basis percentage to get more customized space.

What does "The APR based Apache Tomcat Native library was not found" mean?

It means exactly what it says: "The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path"

The library referred to is bundled into an OS specific dll (tcnative-1.dll) loaded via JNI. It allows tomcat to use OS functionalities not provided in the Java Runtime (such as sendfile, epoll, OpenSSL, system status, etc.). Tomcat will run just fine without it, but for some use cases, it will be faster with the native libraries.

If you really want it, download the tcnative-1.dll (or libtcnative.so for Linux) and put it in the bin folder, and add a system property to the launch configuration of the tomcat server in eclipse.

 -Djava.library.path=c:\dev\tomcat\bin

Java optional parameters

This is an old question maybe even before actual Optional type was introduced but these days you can consider few things: - use method overloading - use Optional type which has advantage of avoiding passing NULLs around Optional type was introduced in Java 8 before it was usually used from third party lib such as Google's Guava. Using optional as parameters / arguments can be consider as over-usage as the main purpose was to use it as a return time.

Ref: https://itcodehub.blogspot.com/2019/06/using-optional-type-in-java.html

Minimum Hardware requirements for Android development

I've just started using Java on Eclipse (Juno) after a 15 year break from Java. I was using the ADK on a 1.6GHz Atom N270 with 4Gb RAM on W7 32bit on a nearly empty disk. Not sure if it is the Atom or whether Java is as bad as it used to be 15 years ago but it takes over 2 minutes for Eclipse to even start. The emulator does turn up eventually but is extremely sluggish. Even without the emulator, Eclipse is sluggish.

On a 1.6GHz Core i7 or a 2GHz Core 2 Duo, operation is reasonable. Emulator works, Eclipse takes about 5 to 10 seconds to be ready for work. Moral of the story: don't use an Atom or any other low powered processor. It is sluggish even with 4Gb memory and having the same clock speed as a high end processor.

I've also tried it in a VMWare VM on the 1.6GHz Core i7 and on the Core 2. It is reasonably fast until the the emulator is started. It then slows down to the point of no return. Redraws is now very much like that of the Atom but at least it responds when the buttons are clicked. Note that it is now running an emulator within an emulator. The only problem with VMs is that every so often W7 does what W7 does. There is a wait cursor and whole machine is totally unresponsive for a minute or two then it springs back to life. This was with VMWare V3. V4/V5 might be different. Varying the number of cores/processors did not make any difference to eclipse or the emulator.

How do I count unique visitors to my site?

Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.

In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.

Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!


Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).

How to install gdb (debugger) in Mac OSX El Capitan?

Install Homebrew first :

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then run this : brew install gdb

How to reload/refresh jQuery dataTable?

You can try the following:

function InitOverviewDataTable() {
    oOverviewTable = $('#HelpdeskOverview').dataTable({
        "bPaginate": true,
        "bJQueryUI": true, // ThemeRoller-stöd
        "bLengthChange": false,
        "bFilter": false,
        "bSort": false,
        "bInfo": true,
        "bAutoWidth": true,
        "bProcessing": true,
        "iDisplayLength": 10,
        "sAjaxSource": '/Helpdesk/ActiveCases/noacceptancetest'
    });
}

function RefreshTable(tableId, urlData) {
    $.getJSON(urlData, null, function(json) {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i = 0; i < json.aaData.length; i++) {
            table.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
    });
}
// Edited by Prasad
function AutoReload() {
    RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');

    setTimeout(function() {
        AutoReload();
    }, 30000);
}

$(document).ready(function() {
    InitOverviewDataTable();
    setTimeout(function() {
        AutoReload();
    }, 30000);
});

http://www.meadow.se/wordpress/?p=536

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

git checkout all the files

Other way which I found useful is:

git checkout <wildcard> 

Example:

git checkout *.html

More generally:

git checkout <branch> <filename/wildcard>

Set focus on textbox in WPF

In Code behind you can achieve it only by doing this.

 private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtIndex.Focusable = true;
            txtIndex.Focus();
        }

Note: It wont work before window is loaded

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

How to go back last page

yes you can do it. write this code on your typescript component and enjoy!

import { Location } from '@angular/common'
import { Component, Input } from '@angular/core'

@Component({
    selector: 'return_page',
    template: `<button mat-button (click)="onReturn()">Back</button>`,
})
export class ReturnPageComponent {
  constructor(private location: Location) { }

  onReturn() {
    this.location.back();
  }
}

Hiding a password in a python script (insecure obfuscation only)

base64 is the way to go for your simple needs. There is no need to import anything:

>>> 'your string'.encode('base64')
'eW91ciBzdHJpbmc=\n'
>>> _.decode('base64')
'your string'

VBoxManage: error: Failed to create the host-only adapter

Try these:

sudo modprobe vboxnetadp

sudo modprobe vboxnetflt

sudo modprobe vboxdrv

Stripping everything but alphanumeric chars from a string in Python

I just timed some functions out of curiosity. In these tests I'm removing non-alphanumeric characters from the string string.printable (part of the built-in string module). The use of compiled '[\W_]+' and pattern.sub('', str) was found to be fastest.

$ python -m timeit -s \
     "import string" \
     "''.join(ch for ch in string.printable if ch.isalnum())" 
10000 loops, best of 3: 57.6 usec per loop

$ python -m timeit -s \
    "import string" \
    "filter(str.isalnum, string.printable)"                 
10000 loops, best of 3: 37.9 usec per loop

$ python -m timeit -s \
    "import re, string" \
    "re.sub('[\W_]', '', string.printable)"
10000 loops, best of 3: 27.5 usec per loop

$ python -m timeit -s \
    "import re, string" \
    "re.sub('[\W_]+', '', string.printable)"                
100000 loops, best of 3: 15 usec per loop

$ python -m timeit -s \
    "import re, string; pattern = re.compile('[\W_]+')" \
    "pattern.sub('', string.printable)" 
100000 loops, best of 3: 11.2 usec per loop

How to get the selected date value while using Bootstrap Datepicker?

Generally speaking,

$('#startdate').data('date') 

is best because

$('#startdate').val()

not work if you have a datepicker "inline"

how to call an ASP.NET c# method using javascript

There are several options. You can use the WebMethod attribute, for your purpose.

How to install MySQLdb package? (ImportError: No module named setuptools)

If MySQLdb's now distributed in a way that requires setuptools, your choices are either to download the latter (e.g. from here) or refactor MySQLdb's setup.py to bypass setuptools (maybe just importing setup and Extension from plain distutils instead might work, but you may also need to edit some of the setup_*.py files in the same directory).

Depending on how your site's Python installation is configured, installing extensions for your own individual use without requiring sysadm rights may be hard, but it's never truly impossible if you have shell access. You'll need to tweak your Python's sys.path to start with a directory of your own that's your personal equivalent of the system-wide site pacages directory, e.g. by setting PYTHONPATH persistently in your own environment, and then manually place in said personal directory what normal installs would normally place in site-packages (and/or subdirectories thereof).

Creating a directory in /sdcard fails

If this is happening to you with Android 6 and compile target >= 23, don't forget that we are now using runtime permissions. So giving permissions in the manifest is not enough anymore.

Filter data.frame rows by a logical condition

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

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

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

Specifically to the original question:

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

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

ImportError: No module named - Python

from ..gen_py.lib import MyService

or

from main.gen_py.lib import MyService

Make sure you have a (at least empty) __init__.py file on each directory.

How can I copy columns from one sheet to another with VBA in Excel?

I'm not sure why you'd be getting subscript out of range unless your sheets weren't actually called Sheet1 or Sheet2. When I rename my Sheet2 to Sheet_2, I get that same problem.

In addition, some of your code seems the wrong way about (you paste before selecting the second sheet). This code works fine for me.

Sub OneCell()
    Sheets("Sheet1").Select
    Range("A1:A3").Copy
    Sheets("Sheet2").Select
    Range("b1:b3").Select
    ActiveSheet.Paste
End Sub

If you don't want to know about what the sheets are called, you can use integer indexes as follows:

Sub OneCell()
    Sheets(1).Select
    Range("A1:A3").Copy
    Sheets(2).Select
    Range("b1:b3").Select
    ActiveSheet.Paste
End Sub

npm check and update package if needed

When installing npm packages (both globally or locally) you can define a specific version by using the @version syntax to define a version to be installed.

In other words, doing: npm install -g [email protected] will ensure that only 0.9.2 is installed and won't reinstall if it already exists.

As a word of a advice, I would suggest avoiding global npm installs wherever you can. Many people don't realize that if a dependency defines a bin file, it gets installed to ./node_modules/.bin/. Often, its very easy to use that local version of an installed module that is defined in your package.json. In fact, npm scripts will add the ./node_modules/.bin onto your path.

As an example, here is a package.json that, when I run npm install && npm test will install the version of karma defined in my package.json, and use that version of karma (installed at node_modules/.bin/karma) when running the test script:

{
 "name": "myApp",
 "main": "app.js",
 "scripts": {
   "test": "karma test/*",
 },
 "dependencies": {...},
 "devDependencies": {
   "karma": "0.9.2"
 }
}

This gives you the benefit of your package.json defining the version of karma to use and not having to keep that config globally on your CI box.

Check that a variable is a number in UNIX shell

Here's a version using only the features available in a bare-bones shell (ie it'd work in sh), and with one less process than using grep:

if expr "$var" : '[0-9][0-9]*$'>/dev/null; then
    echo yes
else
    echo no
fi

This checks that the $var represents only an integer; adjust the regexp to taste, and note that the expr regexp argument is implicitly anchored at the beginning.

How to start/stop/restart a thread in Java?

If your task is performing some kind of action in a loop there is a way to pause/restart processing, but I think it would have to be outside what the Thread API currently offers. If its a single shot process I am not aware of any way to suspend/restart without running into API that has been deprecated or is no longer allowed.

As for looped processes, the easiest way I could think of is that the code that spawns the Task instantiates a ReentrantLock and passes it to the task, as well as keeping a reference itself. Every time the Task enters its loop it attempts a lock on the ReentrantLock instance and when the loop completes it should unlock. You may want to encapsulate all this try/finally, making sure you let go of the lock at the end of the loop, even if an exception is thrown.

If you want to pause the task simply attempt a lock from the main code (since you kept a reference handy). What this will do is wait for the loop to complete and not let it start another iteration (since the main thread is holding a lock). To restart the thread simply unlock from the main code, this will allow the task to resume its loops.

To permanently stop the thread I would use the normal API or leave a flag in the Task and a setter for the flag (something like stopImmediately). When the loop encountered a true value for this flag it stops processing and completes the run method.

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

to make this work in both FF and IE you must write both ways:


    button_element.setAttribute('onclick','doSomething();'); // for FF
    button_element.onclick = function() {doSomething();}; // for IE

thanks to this post.

UPDATE: This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:

// get old onclick attribute
var onclick = button_element.getAttribute("onclick");  

// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") { 
    button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome

// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
    button_element.onclick = function() { 
        doSomething();
        onclick();
    }; // for IE7
}

Using FFmpeg in .net?

A solution that is viable for both Linux and Windows is to just get used to using console ffmpeg in your code. I stack up threads, write a simple thread controller class, then you can easily make use of what ever functionality of ffmpeg you want to use.

As an example, this contains sections use ffmpeg to create a thumbnail from a time that I specify.

In the thread controller you have something like

List<ThrdFfmpeg> threads = new List<ThrdFfmpeg>();

Which is the list of threads that you are running, I make use of a timer to Pole these threads, you can also set up an event if Pole'ing is not suitable for your application. In this case thw class Thrdffmpeg contains,

public class ThrdFfmpeg
{
    public FfmpegStuff ffm { get; set; }
    public Thread thrd { get; set; }
}

FFmpegStuff contains the various ffmpeg functionality, thrd is obviously the thread.

A property in FfmpegStuff is the class FilesToProcess, which is used to pass information to the called process, and receive information once the thread has stopped.

public class FileToProcess
{
    public int videoID { get; set; }
    public string fname { get; set; }
    public int durationSeconds { get; set; }
    public List<string> imgFiles { get; set; }
}

VideoID (I use a database) tells the threaded process which video to use taken from the database. fname is used in other parts of my functions that use FilesToProcess, but not used here. durationSeconds - is filled in by the threads that just collect video duration. imgFiles is used to return any thumbnails that were created.

I do not want to get bogged down in my code when the purpose of this is to encourage the use of ffmpeg in easily controlled threads.

Now we have our pieces we can add to our threads list, so in our controller we do something like,

        AddThread()
        {
        ThrdFfmpeg thrd;
        FileToProcess ftp;

        foreach(FileToProcess ff in  `dbhelper.GetFileNames(txtCategory.Text))`
        {
            //make a thread for each
            ftp = new FileToProcess();
            ftp = ff;
            ftp.imgFiles = new List<string>();
            thrd = new ThrdFfmpeg();
            thrd.ffm = new FfmpegStuff();
            thrd.ffm.filetoprocess = ftp;
            thrd.thrd = new   `System.Threading.Thread(thrd.ffm.CollectVideoLength);`

         threads.Add(thrd);
        }
        if(timerNotStarted)
             StartThreadTimer();
        }

Now Pole'ing our threads becomes a simple task,

private void timerThreads_Tick(object sender, EventArgs e)
    {
        int runningCount = 0;
        int finishedThreads = 0;
        foreach(ThrdFfmpeg thrd in threads)
        {
            switch (thrd.thrd.ThreadState)
            {
                case System.Threading.ThreadState.Running:
                    ++runningCount;


 //Note that you can still view data progress here,
    //but remember that you must use your safety checks
    //here more than anywhere else in your code, make sure the data
    //is readable and of the right sort, before you read it.
                    break;
                case System.Threading.ThreadState.StopRequested:
                    break;
                case System.Threading.ThreadState.SuspendRequested:
                    break;
                case System.Threading.ThreadState.Background:
                    break;
                case System.Threading.ThreadState.Unstarted:


//Any threads that have been added but not yet started, start now
                    thrd.thrd.Start();
                    ++runningCount;
                    break;
                case System.Threading.ThreadState.Stopped:
                    ++finishedThreads;


//You can now safely read the results, in this case the
   //data contained in FilesToProcess
   //Such as
                    ThumbnailsReadyEvent( thrd.ffm );
                    break;
                case System.Threading.ThreadState.WaitSleepJoin:
                    break;
                case System.Threading.ThreadState.Suspended:
                    break;
                case System.Threading.ThreadState.AbortRequested:
                    break;
                case System.Threading.ThreadState.Aborted:
                    break;
                default:
                    break;
            }
        }


        if(flash)
        {//just a simple indicator so that I can see
         //that at least one thread is still running
            lbThreadStatus.BackColor = Color.White;
            flash = false;
        }
        else
        {
            lbThreadStatus.BackColor = this.BackColor;
            flash = true;
        }
        if(finishedThreads >= threads.Count())
        {

            StopThreadTimer();
            ShowSample();
            MakeJoinedThumb();
        }
    }

Putting your own events onto into the controller class works well, but in video work, when my own code is not actually doing any of the video file processing, poling then invoking an event in the controlling class works just as well.

Using this method I have slowly built up just about every video and stills function I think I will ever use, all contained in the one class, and that class as a text file is useable on the Lunux and Windows version, with just a small number of pre-process directives.

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

I have solved as plist file.

  1. Add a NSAppTransportSecurity : Dictionary.
  2. Add Subkey named " NSAllowsArbitraryLoads " as Boolean : YES

enter image description here

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

For Nginx, the only thing that worked for me was adding this header:

add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';

Along with the Access-Control-Allow-Origin header:

add_header 'Access-Control-Allow-Origin' '*';

Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

How can the default node version be set using NVM?

Lets say to want to make default version as 10.19.0.

nvm alias default v10.19.0

But it will give following error

! WARNING: Version 'v10.19.0' does not exist.
default -> v10.19.0 (-> N/A)

In That case you need to run two commands in the following order

# Install the version that you would like 
nvm install 10.19.0

# Set 10.19.0 (or another version) as default
nvm alias default 10.19.0

How do I parse command line arguments in Java?

Take a look at the Commons CLI project, lots of good stuff in there.

How to copy an object by value, not by reference

You may use clone() which works well if your object has immutable objects and/or primitives, but it may be a little problematic when you don't have these ( such as collections ) for which you may need to perform a deep clone.

User userCopy = (User) user.clone();//make a copy

for(...) {
    user.age = 1;
    user.id = -1;

    UserDao.update(user)
    user = userCopy; 
}

It seems like you just want to preserve the attributes: age and id which are of type int so, why don't you give it a try and see if it works.

For more complex scenarios you could create a "copy" method:

publc class User { 
    public static User copy( User other ) {
         User newUser = new User();
         newUser.age = other.age;
         newUser.id = other.id;
         //... etc. 
         return newUser;
    }
}

It should take you about 10 minutes.

And then you can use that instead:

     User userCopy = User.copy( user ); //make a copy
     // etc. 

To read more about clone read this chapter in Joshua Bloch "Effective Java: Override clone judiciously"

How to convert an xml string to a dictionary?

@dibrovsd: Solution will not work if the xml have more than one tag with same name

On your line of thought, I have modified the code a bit and written it for general node instead of root:

from collections import defaultdict
def xml2dict(node):
    d, count = defaultdict(list), 1
    for i in node:
        d[i.tag + "_" + str(count)]['text'] = i.findtext('.')[0]
        d[i.tag + "_" + str(count)]['attrib'] = i.attrib # attrib gives the list
        d[i.tag + "_" + str(count)]['children'] = xml2dict(i) # it gives dict
     return d

How to setup FTP on xampp

I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!

What is your single most favorite command-line trick using Bash?

type -a PROG

in order to find all the places where PROG is available, usually somewhere in ~/bin rather than the one in /usr/bin/PROG that might have been expected.

html <input type="text" /> onchange event not working

Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.

Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().

Let's say that your input field has an id and name of "city":

<input type="text" name="city" id="city" />

Have a global variable named "city":

var city = "";

Add this to your page initialization:

setInterval(lookForCityChange, 100);

Then define a lookForCityChange() function:

function lookForCityChange()
{
    var newCity = document.getElementById("city").value;
    if (newCity != city) {
        city = newCity;
        doSomething(city);     // do whatever you need to do
    }
}

In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.

If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.

Phone mask with jQuery and Masked Input Plugin

You can use the phone alias with Inputmask v3

$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });

_x000D_
_x000D_
$(function() {_x000D_
  $('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });_x000D_
});
_x000D_
<label for="phone">Phone</label>_x000D_
    <input name="phone" type="tel">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.numeric.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.date.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.phone.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/jquery.inputmask.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/phone-codes/phone.js"></script>
_x000D_
_x000D_
_x000D_

https://github.com/RobinHerbots/Inputmask#aliases

Altering a column to be nullable

for Oracle Database 10g users:

alter table mytable modify(mycolumn null);

You get "ORA-01735: invalid ALTER TABLE option" when you try otherwise

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

In my case, I created a new "Solution Configuration" like shown in the image. So when I select my custom one as "Prod", it doesnt recognize TestMehods for some reason. Changing back to "Debug" solves the problem

enter image description here

How can one change the timestamp of an old commit in Git?

A better way to handle all of these suggestions in one command is

LC_ALL=C GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"

This will set the last commit's commit and author date to "right now."

How do you get the currently selected <option> in a <select> via JavaScript?

The .selectedIndex of the select object has an index; you can use that to index into the .options array.

Find the server name for an Oracle database

The query below demonstrates use of the package and some of the information you can get.

select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual

NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.

Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.

How can I use UserDefaults in Swift?

Best way to use UserDefaults

Steps

  1. Create extension of UserDefaults
  2. Create enum with required Keys to store in local
  3. Store and retrieve the local data wherever you want

Sample

extension UserDefaults{

    //MARK: Check Login
    func setLoggedIn(value: Bool) {
        set(value, forKey: UserDefaultsKeys.isLoggedIn.rawValue)
        //synchronize()
    }

    func isLoggedIn()-> Bool {
        return bool(forKey: UserDefaultsKeys.isLoggedIn.rawValue)
    }

    //MARK: Save User Data
    func setUserID(value: Int){
        set(value, forKey: UserDefaultsKeys.userID.rawValue)
        //synchronize()
    }

    //MARK: Retrieve User Data
    func getUserID() -> Int{
        return integer(forKey: UserDefaultsKeys.userID.rawValue)
    }
}

enum for Keys used to store data

enum UserDefaultsKeys : String {
    case isLoggedIn
    case userID
}

Save in UserDefaults where you want

UserDefaults.standard.setLoggedIn(value: true)          // String
UserDefaults.standard.setUserID(value: result.User.id!) // String

Retrieve data anywhere in app

print("ID : \(UserDefaults.standard.getUserID())")
UserDefaults.standard.getUserID()

Remove Values

UserDefaults.standard.removeObject(forKey: UserDefaultsKeys.userID) 

This way you can store primitive data in best

Update You need no use synchronize() to store the values. As @Moritz pointed out the it unnecessary and given the article about it.Check comments for more detail

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

How to get the full URL of a Drupal page?

The following is more Drupal-ish:

url(current_path(), array('absolute' => true)); 

Jquery $.ajax fails in IE on cross domain calls

@Furqan Could you please let me know whether you tested this with HTTP POST method,

Since I am also working on the same kind of situation, but I am not able to POST the data to different domain.

But after reading this it was quite simple...only thing is you have to forget about OLD browsers. I am giving code to send with POST method from same above URL for quick reference

function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    xhr = null;
}
return xhr;
}

var request = createCORSRequest("POST", "http://www.sanshark.com/");
var content = "name=sandesh&lastname=daddi";
if (request){
    request.onload = function(){
    //do something with request.responseText
   alert(request.responseText);
};

 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.setRequestHeader("Content-length", content.length);
            request.send(content);
}

Bash script - variable content as a command to run

Your are probably looking for eval $var.

What does it mean when an HTTP request returns status code 0?

wininet.dll returns both standard and non-standard status codes that are listed below.

401 - Unauthorized file
403 - Forbidden file
404 - File Not Found
500 - some inclusion or functions may missed
200 - Completed

12002 - Server timeout
12029,12030, 12031 - dropped connections (either web server or DB server)
12152 - Connection closed by server.
13030 - StatusText properties are unavailable, and a query attempt throws an exception

For the status code "zero" are you trying to do a request on a local webpage running on a webserver or without a webserver?

XMLHttpRequest status = 0 and XMLHttpRequest statusText = unknown can help you if you are not running your script on a webserver.

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

In Swift 4 or 4.2

You can add on your vc

preferredStatusBarStyle

and set return value to

.lightContent or .default

ex:

override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
}

What is Shelving in TFS?

I come across this all the time, so supplemental information regarding branches:

If you're working with multiple branches, shelvesets are tied to the specific branch in which you created them. So, if you let a changeset rust on the shelf for too long and have to unshelve to a different branch, then you have to do that with the July release of the power tools.

tfpt unshelve /migrate

List of zeros in python

zeros=[0]*4

you can replace 4 in the above example with whatever number you want.

Clearing _POST array fully

You can use a combination of both unset() and initialization:

unset($_POST);
$_POST = array();

Or in a single statement:

unset($_POST) ? $_POST = array() : $_POST = array();

But what is the reason you want to do this?

Difference between Console.Read() and Console.ReadLine()?

Console.Read() reads a single key, where Console.Readline() waits for the Enter key.

How to access Spring MVC model object in javascript file?

in controller:

JSONObject jsonobject=new JSONObject();
jsonobject.put("error","Invalid username");
response.getWriter().write(jsonobject.toString());

in javascript:

f(data!=success){



 var errorMessage=jQuery.parseJson(data);
  alert(errorMessage.error);
}

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

How to stop (and restart) the Rails Server?

I had to restart the rails application on the production so I looked for an another answer. I have found it below:

http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger

How to execute a MySQL command from a shell script?

As stated before you can use -p to pass the password to the server.

But I recommend this:

mysql -h "hostaddress" -u "username" -p "database-name" < "sqlfile.sql"

Notice the password is not there. It would then prompt your for the password. I would THEN type it in. So that your password doesn't get logged into the servers command line history.

This is a basic security measure.

If security is not a concern, I would just temporarily remove the password from the database user. Then after the import - re-add it.

This way any other accounts you may have that share the same password would not be compromised.

It also appears that in your shell script you are not waiting/checking to see if the file you are trying to import actually exists. The perl script may not be finished yet.

Fix footer to bottom of page

We can use FlexBox for Sticky Footer and Header without using POSITIONS in CSS.

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
  height: 50px;_x000D_
  flex-shrink: 0;_x000D_
  background-color: #037cf5;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  height: 50px;_x000D_
  flex-shrink: 0;_x000D_
  background-color: #134c7d;_x000D_
}_x000D_
_x000D_
main {_x000D_
  flex: 1 0 auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <header>HEADER</header>_x000D_
  <main class="content">_x000D_
_x000D_
  </main>_x000D_
  <footer>FOOTER</footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

DEMO - JSFiddle

Note : Check browser supports for FlexBox. caniuse

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

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).

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Convert string to ASCII value python

you can actually do it with numpy:

import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)

How do I check for vowels in JavaScript?

  //function to find vowel
const vowel = (str)=>{
  //these are vowels we want to check for
  const check = ['a','e','i','o','u'];
  //keep track of vowels
  var count = 0;
  for(let char of str.toLowerCase())
  {
    //check if each character in string is in vowel array
    if(check.includes(char)) count++;
  }
  return count;
}

console.log(vowel("hello there"));

Class 'DOMDocument' not found

After a long time suffering from it in PHPunit...

For those using namespace, which is very common with Frameworks or CMS, a good check in addition to seeing if php-xml is installed and active, is to remember to declare the DOMDocument after the namespace:

namespace YourNameSpace\YourNameSpace;

use DOMDocument; //<--- here, check this!

Difference between @Mock and @InjectMocks

@InjectMocks annotation can be used to inject mock fields into a test object automatically.

In below example @InjectMocks has used to inject the mock dataMap into the dataLibrary .

@Mock
Map<String, String> dataMap ;

@InjectMocks
DataLibrary dataLibrary = new DataLibrary();


    @Test
    public void whenUseInjectMocksAnnotation_() {
        Mockito.when(dataMap .get("aData")).thenReturn("aMeaning");

        assertEquals("aMeaning", dataLibrary .getMeaning("aData"));
    }

YYYY-MM-DD format date in shell script

In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date (usually GNU date).

As such:

# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1 

# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1 

# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal

In bash (<4.2):

# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')

# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')

# print current date directly
echo $(date '+%Y-%m-%d')

Other available date formats can be viewed from the date man pages (for external non-bash specific command):

man date

How to identify and switch to the frame in selenium webdriver when frame does not have id

There are three ways to switch to the frame

1)Can use id
2)Can use name of the frame
3)Can use WebElement of the frame

2->driver.switchTo().frame("name of the frame");

What is the Python equivalent of static variables inside a function?

_counter = 0
def foo():
   global _counter
   _counter += 1
   print 'counter is', _counter

Python customarily uses underscores to indicate private variables. The only reason in C to declare the static variable inside the function is to hide it outside the function, which is not really idiomatic Python.

How do I revert back to an OpenWrt router configuration?

Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.

So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.

  • Enter Failsafe mode (hold the reset button on boot for a few seconds)
  • Assign a static IP address, 192.168.1.2, to your PC. Example of a command: netsh interface ip set address name="Ethernet" static 192.168.1.2 255.255.255.0 192.168.1.1
  • Connect to address 192.168.1.1 from telnet (I use PuTTY) and login/password isn't required).
  • Run 'mount_root' (otherwise 'firstboot' won't be available).
  • Run 'firstboot' to reset.
  • Run 'reboot -f' to reboot.

Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp

How do I implement basic "Long Polling"?

Simplest NodeJS

const http = require('http');

const server = http.createServer((req, res) => {
  SomeVeryLongAction(res);
});

server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});

server.listen(8000);

// the long running task - simplified to setTimeout here
// but can be async, wait from websocket service - whatever really
function SomeVeryLongAction(response) {
  setTimeout(response.end, 10000);
}

Production wise scenario in Express for exmaple you would get response in the middleware. Do you what you need to do, can scope out all of the long polled methods to Map or something (that is visible to other flows), and invoke <Response> response.end() whenever you are ready. There is nothing special about long polled connections. Rest is just how you normally structure your application.

If you dont know what i mean by scoping out, this should give you idea

const http = require('http');
var responsesArray = [];

const server = http.createServer((req, res) => {
  // not dealing with connection
  // put it on stack (array in this case)
  responsesArray.push(res);
  // end this is where normal api flow ends
});

server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});

// and eventually when we are ready to resolve
// that if is there just to ensure you actually 
// called endpoint before the timeout kicks in
function SomeVeryLongAction() {
  if ( responsesArray.length ) {
    let localResponse = responsesArray.shift();
    localResponse.end();
  }
}

// simulate some action out of endpoint flow
setTimeout(SomeVeryLongAction, 10000);
server.listen(8000);

As you see, you could really respond to all connections, one, do whatever you want. There is id for every request so you should be able to use map and access specific out of api call.

How do I get the current date in JavaScript?

If your looking to format into a string.

statusUpdate = "time " + new Date(Date.now()).toLocaleTimeString();

output "time 11:30:53 AM"

How do I fix PyDev "Undefined variable from import" errors?

The post marked as answer gives a workaround, not a solution.

This solution works for me:

  • Go to Window - Preferences - PyDev - Interpreters - Python Interpreter
  • Go to the Forced builtins tab
  • Click on New...
  • Type the name of the module (multiprocessing in my case) and click OK

Not only will the error messages disappear, the module members will also be recognized.

Android RelativeLayout programmatically Set "centerInParent"

Completely untested, but this should work:

View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);

add android:configChanges="orientation|screenSize" inside your activity in your manifest

npm install Error: rollbackFailedOptional

Hi I'm also new to react and I also faced this problem after so many trouble I found solution: Just run in your command prompt or terminal :

npm config set registry http://registry.npmjs.org/

This will resolve your problem. Reference link: http://blog.csdn.net/zhalcie2011/article/details/78726679

how to download file in react js

Download file


For downloading you can use multiple ways as been explained above, moreover I will also provide my strategy for this scenario.

  1. npm install --save react-download-link
  2. import DownloadLink from "react-download-link";
  3. React download link for client side cache data
    <DownloadLink 
        label="Download" 
        filename="fileName.txt"
        exportFile={() => "Client side cache data here…"}
    />
    
  4. Download link for client side cache data with Promises
    <DownloadLink
        label="Download with Promise"
        filename="fileName.txt"
        exportFile={() => Promise.resolve("cached data here …")}
    />
    
  5. Download link for data from URL with Promises Function to Fetch data from URL
     getDataFromURL = (url) => new Promise((resolve, reject) => {
        setTimeout(() => {
            fetch(url)
                .then(response => response.text())
                .then(data => {
                    resolve(data)
                });
        });
    }, 2000);
    
  6. DownloadLink component calling Fetch function
    <DownloadLink
          label=”Download”
          filename=”filename.txt”
          exportFile={() => Promise.resolve(this. getDataFromURL (url))}
    />
    

Happy coding! ;)

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

Go for the simplest and shortest if you can -- DISTINCT seems to be more what you are looking for only because it will give you EXACTLY the answer you need and only that!

What is base 64 encoding used for?

Mostly, I've seen it used to encode binary data in contexts that can only handle ascii - or a simple - character sets.